diff --git a/.env b/.env index 8f22e9d..573b06c 100644 --- a/.env +++ b/.env @@ -2,8 +2,3 @@ CHANGELOG_START_TAG=ical4j-command-0.1.0 CHANGELOG_END_TAG=HEAD GRADLE_VERSION=8.4 - -# Cloudflare R2 -AWS_PROFILE?=r2 -AWS_ENDPOINT?=https://595c17c39386dfc0d142476ebc3798e0.r2.cloudflarestorage.com -DIST_BUCKET=s3://ical4j-files diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 76c0580..ef382bf 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,26 +1,51 @@ -# This workflow will build a Java project with Gradle -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle +# JVM tests on every push and pull request, plus one native smoke run on linux x64. The full +# native matrix runs only on release tags (release.yml), since native builds are slow. -name: Java CI with Gradle +name: Build -on: [push] +on: + push: + pull_request: permissions: read-all jobs: - build: - + test: + name: JVM tests runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + # Full history + tags so axion-release resolves the version. + fetch-depth: 0 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + - uses: gradle/actions/setup-gradle@v4 + - name: Test and JVM smoke run + run: ./gradlew build jvmSmoke + + native-smoke: + name: Native smoke (linux x64) + runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions/setup-java@v1 - with: - java-version: 17 -# - name: Grant execute permission for gradlew -# run: chmod +x gradlew - - name: Build with Gradle -# run: ./gradlew build - uses: eskatos/gradle-command-action@v1 - with: - arguments: build + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '25' + distribution: graalvm-community + github-token: ${{ secrets.GITHUB_TOKEN }} + - uses: gradle/actions/setup-gradle@v4 + + - name: Build native executable + run: ./gradlew nativeCompile --no-configuration-cache + + - name: Smoke suite + run: ./gradlew nativeSmoke --no-configuration-cache + + - name: Startup time + run: ./gradlew nativeStartup --no-configuration-cache diff --git a/.github/workflows/publish-snapshots.yml b/.github/workflows/publish-snapshots.yml index 816edde..cf7405b 100644 --- a/.github/workflows/publish-snapshots.yml +++ b/.github/workflows/publish-snapshots.yml @@ -7,12 +7,24 @@ on: permissions: contents: read - checks: write - pull-requests: write jobs: test: - uses: ical4j/ical4j/.github/workflows/test.yml@develop + name: Test + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + - uses: gradle/actions/setup-gradle@v4 + - name: Test and JVM smoke run + run: ./gradlew check jvmSmoke publish: name: Publish Artifact @@ -31,9 +43,9 @@ jobs: with: distribution: temurin java-version: 17 - - name: Setup Gradle - uses: gradle/gradle-build-action@v2 + - uses: gradle/actions/setup-gradle@v4 + # The single org.ical4j:ict jar; the native executables are released from tags only. - name: Publish snapshot to Central Portal run: ./gradlew publishToMavenCentral --no-configuration-cache env: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..f5ba82c --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,94 @@ +# On an `ict-` tag: build and smoke-test the native executable on each platform, attach +# them with SHA-256 checksums to a GitHub Release, and publish the jar to Maven Central. + +name: Release + +on: + push: + tags: + - 'ict-*' + +permissions: + contents: read + +jobs: + native: + name: Native ${{ matrix.os }}-${{ matrix.arch }} + strategy: + fail-fast: false + matrix: + include: + - { runner: ubuntu-latest, os: linux, arch: x64, ext: '' } + - { runner: ubuntu-24.04-arm, os: linux, arch: arm64, ext: '' } + - { runner: macos-latest, os: macos, arch: arm64, ext: '' } + - { runner: windows-latest, os: windows, arch: x64, ext: '.exe' } + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '25' + distribution: graalvm-community + github-token: ${{ secrets.GITHUB_TOKEN }} + - uses: gradle/actions/setup-gradle@v4 + + - name: Build and smoke-test the native executable + run: ./gradlew nativeCompile nativeSmoke --no-configuration-cache + + - name: Name the executable for the release + shell: bash + run: | + version="${GITHUB_REF_NAME#ict-}" + mkdir dist + cp "build/native/nativeCompile/ict${{ matrix.ext }}" "dist/ict-${version}-${{ matrix.os }}-${{ matrix.arch }}${{ matrix.ext }}" + + - uses: actions/upload-artifact@v4 + with: + name: ict-${{ matrix.os }}-${{ matrix.arch }} + path: dist/* + if-no-files-found: error + + github-release: + name: GitHub Release + needs: native + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v4 + with: + path: dist + merge-multiple: true + + - name: Checksums + working-directory: dist + run: sha256sum ict-* > "ict-${GITHUB_REF_NAME#ict-}-checksums.sha256" + + - name: Create the release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: gh release create "$GITHUB_REF_NAME" dist/* --repo "$GITHUB_REPOSITORY" --title "ict ${GITHUB_REF_NAME#ict-}" --generate-notes + + maven-central: + name: Publish to Maven Central + needs: native + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + - uses: gradle/actions/setup-gradle@v4 + + - name: Publish release to Central Portal + run: ./gradlew publishToMavenCentral --no-configuration-cache + env: + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.CENTRAL_PORTAL_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.CENTRAL_PORTAL_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_SIGNING_KEY }} + ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.GPG_SIGNING_PASSWORD }} diff --git a/.gitignore b/.gitignore index 475e3e1..140265c 100644 --- a/.gitignore +++ b/.gitignore @@ -18,7 +18,8 @@ gradle-app.setting *.iml # Spring AI weather demo build artifacts -**/model-context-protocol/**/target/ # Claude Code workspace files .claude/ +# particulars workspace pointer (machine-specific) +.dkf diff --git a/Makefile b/Makefile index 4f4d1cf..b8d15c3 100644 --- a/Makefile +++ b/Makefile @@ -1,11 +1,13 @@ SHELL:=/bin/bash -include .env +# Optional local settings (GRADLE_VERSION, GRAALVM_HOME, SDKROOT, ...). +-include .env +export GRAALVM_HOME SDKROOT NEXT_VERSION=$(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)) CHANGE_JUSTIFICATION=$(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)) -.PHONY: all gradlew clean check build changelog currentVersion markNextVersion tag push run \ - verify release publish +.PHONY: all gradlew clean check test build installDist dist native smoke changelog currentVersion \ + markNextVersion install verify release publish all: check @@ -30,9 +32,13 @@ installDist: dist: ./gradlew distZip -uploadDist: dist - AWS_PROFILE=$(AWS_PROFILE) aws s3 sync --endpoint=$(AWS_ENDPOINT) --acl public-read --exclude "*" --include "*.zip" \ - build/distributions $(DIST_BUCKET)/releases +# Native executable at build/native/nativeCompile/ict. Needs GRAALVM_HOME (GraalVM CE for JDK 25+). +native: + $(if $(GRAALVM_HOME),JAVA_HOME=$(GRAALVM_HOME)) ./gradlew nativeCompile --no-configuration-cache + +# Smoke suite and startup time against the native executable built by `make native`. +smoke: native + ./gradlew nativeSmoke nativeStartup -PictBinary=build/native/nativeCompile/ict changelog: git log "$(CHANGELOG_START_TAG)...$(CHANGELOG_END_TAG)" \ @@ -48,8 +54,10 @@ install: ./gradlew publishToMavenLocal verify: - ./gradlew verify + ./gradlew check jvmSmoke +# Tags ict- and pushes it; release.yml then builds and smoke-tests the native +# executables on each platform, attaches them to a GitHub Release and publishes the jar. release: verify ./gradlew release diff --git a/README.md b/README.md index 848b53b..4ff02eb 100644 --- a/README.md +++ b/README.md @@ -1,140 +1,198 @@ -# iCal4j Command Line +# ict + +`ict` is a command-line tool and MCP server for iCalendar and vCard data, built on +[iCal4j](https://github.com/ical4j/ical4j). It ships as a single native executable: one file, no +JVM required, and about 10 ms to start. + +The same operations are available two ways: + +- **From a terminal**: `ict [options]`, for example `ict list event --collection work`. +- **To an AI assistant**: `ict mcp` serves each operation as a Model Context Protocol tool over stdio. + +Both are generated from one operation registry, so every operation, its parameters and its +behaviour are identical in each. + +## Install + +Download the executable for your platform from +[GitHub Releases](https://github.com/ical4j/ical4j-command/releases). Each release carries: + +| File | Platform | +|---|---| +| `ict--linux-x64` | Linux, x86-64 | +| `ict--linux-arm64` | Linux, ARM64 | +| `ict--macos-arm64` | macOS, Apple silicon | +| `ict--windows-x64.exe` | Windows, x86-64 | +| `ict--checksums.sha256` | SHA-256 checksums for the above | + +```sh +sha256sum --check --ignore-missing ict-1.0.0-checksums.sha256 +install -m 755 ict-1.0.0-linux-x64 ~/.local/bin/ict +ict --version +``` + +On macOS, a downloaded binary is quarantined until you allow it. Run +`xattr -d com.apple.quarantine ict` or approve it in System Settings > Privacy & Security. + +The jar is also published to Maven Central as `org.ical4j:ict`, for running on a JVM or embedding. + +## Usage + +Commands are verb first: `ict `. `ict --help` lists the verbs, `ict --help` +lists the types under a verb, and `ict --help` lists that operation's options. + +```sh +# Collections live in a workspace +ict add collection --collection work +ict add collection --collection people --type card --description "Contacts" +ict list collection + +# Calendar data moves in and out of a collection with import/export +ict import calendar --collection work --file meetings.ics +curl -s https://example.com/holidays.ics | ict import calendar --collection work +ict list event --collection work +ict export calendar --collection work --uid 1234@example.com > meeting.ics +ict export calendar --collection work --format json # jCal + +# Cards work the same way +ict import card --collection people --file contacts.vcf +ict list entity --collection people +``` + +### Operations + +| Command | MCP tool | Does | +|---|---|---| +| `ict add collection --collection N [--type calendar\|card] [--description D]` | `add_collection` | Add a collection to the workspace | +| `ict get collection --collection N [--type T]` | `get_collection` | Describe a collection | +| `ict list collection` | `list_collection` | List the workspace's collections | +| `ict remove collection --collection N [--type T]` | `remove_collection` | Remove a collection and its contents | +| `ict import calendar --collection N [--file F]` | `import_calendar` | Import iCalendar data, merging by UID (stdin if no file) | +| `ict export calendar --collection N [--uid U]` | `export_calendar` | Export one object, or the whole collection, with its VTIMEZONEs | +| `ict remove calendar --collection N --uid U` | `remove_calendar` | Remove one calendar object | +| `ict import card --collection N [--file F]` | `import_card` | Import vCard data, merging by UID (stdin if no file) | +| `ict export card --collection N [--uid U]` | `export_card` | Export one card, or the whole collection | +| `ict remove card --collection N --uid U` | `remove_card` | Remove one card | +| `ict list event --collection N` | `list_event` | List events (VEVENT) | +| `ict list action --collection N` | `list_action` | List actions (VTODO) | +| `ict list note --collection N` | `list_note` | List notes (VJOURNAL) | +| `ict list entity --collection N` | `list_entity` | List contacts (cards) | + +The words come from a fixed vocabulary of verbs (`list`, `get`, `add`, `remove`, `import`, +`export`, and so on) and types (`event`, `action`, `note`, `entity`, `calendar`, `card`, +`collection`, ...). More operations are admitted as they gain tests; see +[`docs/command-protocols.md`](docs/command-protocols.md). + +### Global options + +These work on every command, before or after the verb. + +| Option | Effect | +|---|---| +| `--workspace W` | Act in workspace `W` instead of the active one from configuration | +| `--format text\|json\|xml` | Output format, `text` by default (see below) | +| `-v`, `-vv`, `-vvv` | Log at info, debug or trace level, to stderr | +| `-q`, `--quiet` | Log errors only | +| `--lenient` | Relax iCalendar parsing and unfolding | +| `-h`, `--help` / `-V`, `--version` | Help and version | + +### Output formats + +| Result | `text` (default) | `json` | `xml` | +|---|---|---|---| +| Calendar data | iCalendar (RFC 5545) | jCal (RFC 7265) | xCal (RFC 6321) | +| Card data | vCard (RFC 6350) | jCard (RFC 7095) | xCard (RFC 6351) | +| Lists of items | aligned columns with a header | array of objects | not available | +| Descriptions and status | `name: value` lines | object | not available | + +Results go to stdout and nothing else does: diagnostics and logs go to stderr, so `ict` output +can be piped safely. + +### Exit codes + +| Code | Meaning | +|---|---| +| 0 | Success | +| 1 | The operation failed: not found, already exists, invalid data, or a store error | +| 2 | Usage error: unknown command or option, missing required option | + +### Configuration + +Configuration and the local stores live in the platform data directory: +`~/Library/Application Support/iCal4j` on macOS, `~/.local/share/iCal4j` on Linux and +`%APPDATA%\iCal4j` on Windows. Set `ICT_DATA_DIR` to use another directory. + +```sh +ict config # list every setting +ict config workspace.active # show one +ict config workspace.active home # change one +``` + +| Environment variable | Effect | +|---|---| +| `ICT_DATA_DIR` | Data directory, in place of the platform default | +| `ICT_LOG_LEVEL` | Log level (`trace`, `debug`, `info`, `warn`, `error`, `off`); overrides `-v` and `-q` | + +## MCP server + +`ict mcp` runs a Model Context Protocol server on stdio. It exposes the operations above as tools +named `_`, with input schemas derived from the same option definitions, and runs until +the client closes its input. Calendars and cards come back as iCalendar or vCard text, lists and +descriptions as JSON. A failed operation (a missing collection, say) comes back as a tool result +with `isError` set, and the server keeps running. + +To use it from an MCP client, register the executable with the `mcp` argument. For Claude Code: + +```sh +claude mcp add ict -- /path/to/ict mcp +``` + +For Claude Desktop and other clients that use a JSON configuration: + +```json +{ + "mcpServers": { + "ict": { + "command": "/path/to/ict", + "args": ["mcp"], + "env": { "ICT_DATA_DIR": "/path/to/a/data/directory" } + } + } +} +``` + +`ICT_DATA_DIR` is optional; set it to give the assistant its own store, separate from the one +you use in the terminal. Add `"--workspace", ""` to `args` to pin a workspace. While the +server runs, stdout carries only protocol messages; logs (add `-v` to `args` to see more) go to +stderr, which most clients write to their MCP log. + +Tool handlers cannot read the protocol's stdin, so `import_calendar` and `import_card` need the +`file` argument when called over MCP. + +## Building from source + +The JVM build needs JDK 17; the native build needs GraalVM CE for JDK 25 or later. + +```sh +./gradlew build # compile and run the specs +./gradlew installDist # JVM launcher at build/install/ict/bin/ict +./gradlew jvmSmoke # smoke suite against the JVM build -A command framework for managing iCalendar and vCard data. +export GRAALVM_HOME=/path/to/graalvm-25 +JAVA_HOME=$GRAALVM_HOME ./gradlew nativeCompile --no-configuration-cache # build/native/nativeCompile/ict +./gradlew nativeSmoke nativeStartup -PictBinary=build/native/nativeCompile/ict +``` -## Overview +`make native` and `make smoke` wrap the last two lines. Native reachability metadata is checked in +under `src/main/resources/META-INF/native-image/org.ical4j/ict`; after adding an operation, run +`./gradlew mergeTracedMetadata` (with `GRAALVM_HOME` set) to capture what it needs from a smoke run +under the tracing agent, and review the diff. See +[`docs/command-protocols.md`](docs/command-protocols.md) for how operations are defined and admitted. + +On macOS 27, if native-image fails with `libSystem.B.tbd: unknown architecture`, the Command Line +Tools' clang does not yet understand the macOS 27 SDK. Point the build at an older SDK, for +example `SDKROOT=/Library/Developer/CommandLineTools/SDKs/MacOSX26.5.sdk`, or update the tools. + +## License -iCal4j Command is a collection of operations for common iCalendar and vCard -use cases. This includes direct manipulation of data objects, integration with -persistence stores, and systems interoperability. - -### Example Use Cases - -| Use Case | Description | -|--------------|-------------------------------------------------| -| Workspaces | Create workspaces for distinct knowledge graphs | -| Collections | Group related activities, notes and contacts | -| Events | Schedule and manage events and tasks | -| Actions | Track actions and to-dos | -| Issues | Manage issues and bug reports | -| Notes | Maintain notes and annotations | -| Observances | Reminders for important dates | -| Reports | Report on past activities and events | -| Availability | Share free/busy information | -| Entities | Maintain contact and organization information | - -## Command Line Interface (CLI) - -The CLI provides access to iCal4j Command operations via a terminal -interface. It supports a variety of commands for manipulating iCalendar and -vCard data, as well as managing workspaces and collections. - -### Calendar Commands - -The following commands directly manipulate iCalendar objects: - -* Validator - check validity of iCalendar data -* Filter - select a subset of iCalendar components using filter expressions -* Free Busy - generate free/busy information for specified iCalendar data -* Replace UIDs - regenerate UIDs for all iCalendar components -* Serialize - output iCalendar data in various formats (e.g. XML, JSON) -* Deserialize - read iCalendar data from various formats (e.g. XML, JSON) - -### vCard Commands - -* ... - - -### Strategy Commands - -Strategy commands use the `generate` verb (command group `generate`, alias `new`): - -* Generate Event - generate/overlay iCalendar data using strategy patterns - -### Store Commands - -* Add Workspace - add a new workspace for storing iCalendar/vCard collections -* List Workspaces - list available workspaces -* Remove Workspace - remove an existing workspace -* Get Workspace - retrieve details of a specific workspace - -### Collection Commands - -* ... - -### Channel Commands - -* ... - - -## Model Context Protocol (MCP) - -iCal4j Command supports the Model Context Protocol (MCP) for managing -iCalendar and vCard data in a structured manner. MCP defines a set of -operations for creating, retrieving, updating, and deleting data objects within -a defined context. - -### MCP Operations - -MCP operations follow the canonical vocabulary (see `docs/command-protocols.md`): a **verb** -applied to an **entity type** within a **locus**. The supported verbs are: - -* `add` / `remove` — add or remove an item within a locus (e.g. add a workspace, remove a - collection) -* `list` — enumerate items of a type within a locus (e.g. list events in a collection) -* `get` — retrieve a single item or its metadata -* `update` — modify an existing item -* `import` / `export` — move calendar/card serializations into or out of a collection - -These apply across the loci `workspace` and `collection`, and the entity types `entity` -(contact), `event`, `action`, `issue`, `note`, `observance`, `report`, `availability` and -`resource`. (`create`/`delete` are standardised on `add`/`remove`.) - -## Agentic User Agent - -iCal4j Command includes an Agentic User Agent that provides intelligent -automation capabilities for managing iCalendar and vCard data. The User Agent -can perform tasks such as scheduling events, sending notifications, and -managing contacts based on predefined rules and user preferences. - -### Prompts - -Some example prompts for the User Agent: - -* "Create a new event for a team meeting next Monday at 10 AM." -* "Add a contact for John Doe with email" -* "Generate a free/busy report for the next two weeks." -* "List all upcoming events in my calendar." -* "Update the location of the event 'Project Kickoff' to 'Conference Room B'." -* "Delete the contact for Jane Smith." -* "Send a notification to all attendees of the event 'Weekly Sync'." -* "Create a new workspace for project management." -* "List all workspaces available in my account." -* "Add a new collection for storing project-related notes." - -### Interactions - -The User Agent can interact with users through various channels, including -email, messaging apps, and voice assistants. It can also integrate with other -systems and services to enhance its capabilities. - -When prompted the agent may ask clarifying questions to ensure it understands the user's intent before taking action. - -For example: - -**User:** "Create birthday reminders for my family members." -**Agent:** "Could you please provide the names and birth dates of your family members?" - - - -## System Properties - -The following table describes System properties applicable to the iCal4j User Agent. - - -| System Property | Description | Value | Default | -|---------------------------------|---------------------------------------------------------------------------------|------------------------------------------------------|----------------------------------------------| -| org.ical4j.command.prodid | An application identifier used as the value for the iCalendar `PRODID` property | A string (e.g. `-//Apple Inc.//Mac OS X 10.8.5//EN`) | `-//iCal4j//User Agent//EN` | -| org.ical4j.command.organizer | The default URI used as the value for the iCalendar `ORGANIZER` property | A URI (e.g. `mailto:johnd@example.com`) | - | -| org.ical4j.command.uidgenerator | The `UidGenerator` implementation used to create `UID` properties | A fully qualified class name | `net.fortuna.ical4j.util.RandomUidGenerator` | - +[iCal4j License](https://raw.githubusercontent.com/ical4j/ical4j/master/LICENSE) (BSD-3-Clause). diff --git a/bnd.bnd b/bnd.bnd deleted file mode 100644 index bf05dac..0000000 --- a/bnd.bnd +++ /dev/null @@ -1 +0,0 @@ -Import-Package: !org.eclipse.jetty.server, !org.eclipse.jetty.servlet, * diff --git a/build.gradle b/build.gradle index 8015b35..671586e 100644 --- a/build.gradle +++ b/build.gradle @@ -14,17 +14,21 @@ buildscript { } plugins { + id 'java' + id 'groovy' + id 'application' // 1.20.1 is the minimum that works on Gradle 9 — 1.15.1 and earlier call // Provider.forUseAtConfigurationTime(), removed in Gradle 9, so the build // fails at configuration time on this repo's Gradle 9.2.1 wrapper. id 'pl.allegro.tech.build.axion-release' version '1.20.1' - id 'biz.aQute.bnd.builder' version "$bndVersion" apply false - id 'com.vanniktech.maven.publish' version '0.34.0' apply false + id 'com.vanniktech.maven.publish' version '0.34.0' + id 'org.graalvm.buildtools.native' version '1.1.12' } scmVersion { tag { - prefix = 'ical4j-command-' + // Releases are tagged ict-; release.yml builds the native executables from them. + prefix = 'ict-' } versionCreator 'versionWithBranch' branchVersionCreator = ['main': 'simple'] @@ -34,92 +38,303 @@ scmVersion { } } -configure(subprojects) { - apply plugin: 'java-library' - apply plugin: 'groovy' - apply plugin: 'biz.aQute.bnd.builder' - apply plugin: 'com.vanniktech.maven.publish' +repositories { + mavenCentral() + mavenLocal() + maven { + url 'https://central.sonatype.com/repository/maven-snapshots/' + } +} - repositories { - mavenCentral() - mavenLocal() - maven { - url 'https://central.sonatype.com/repository/maven-snapshots/' - } +group = 'org.ical4j' +description = 'ict: a single-binary command-line and MCP tool for iCalendar and vCard data' +version = scmVersion.version + +java { + sourceCompatibility = 17 + targetCompatibility = 17 +} + +dependencies { + implementation libs.ical4j.connector.api, libs.ical4j.integration.api, libs.ical4j.serializer, + libs.ical4j.vcard, libs.ical4j, libs.ical4j.extensions + + implementation(libs.ical4j) { + capabilities { + requireCapability("org.mnode.ical4j:ical4j-filter-expressions") } + } + + implementation libs.picocli, libs.night.config.toml + + // `ict mcp`: stdio server with programmatic tool registration. + implementation libs.mcp.core, libs.mcp.json.jackson2 + + // Logging: slf4j-simple to stderr only. stdout is reserved for command output and, + // under `ict mcp`, for the protocol stream. Level is chosen in cli.Main before any + // logger is created (see LogLevel). + implementation libs.slf4j.api + runtimeOnly libs.slf4j.simple - group = 'org.ical4j' - description = '''\ -Manipulate iCalendar data -''' - version = rootProject.scmVersion.version + testImplementation platform(libs.spock.bom), libs.spock.core + testRuntimeOnly libs.junit.platform +} + +test { + useJUnitPlatform() +} - java { - sourceCompatibility = 17 - targetCompatibility = 17 +// The version shown by `ict --version`. A resource rather than the manifest, which neither the +// native image nor an in-process test run has. +processResources { + def v = version.toString() + inputs.property('version', v) + filesMatching('org/ical4j/command/version.properties') { + expand(version: v) } +} - test { - useJUnitPlatform() +jar { + manifest { + attributes( + 'Implementation-Title': 'iCal4j Command-line Tool', + 'Implementation-Version': version, + 'Implementation-Vendor': 'Ben Fortuna' + ) } +} + +application { + mainClass = 'org.ical4j.command.cli.Main' + applicationName = 'ict' +} + +startScripts { + classpath = files('lib/*') +} + +// --------------------------------------------------------------------------------------------- +// GraalVM native image +// +// Build with GRAALVM_HOME pointing at GraalVM CE for JDK 25 or later: +// GRAALVM_HOME=... JAVA_HOME=$GRAALVM_HOME ./gradlew nativeCompile --no-configuration-cache +// --------------------------------------------------------------------------------------------- - dependencies { - api libs.ical4j.connector.api, libs.ical4j.integration.api, libs.ical4j.serializer, - libs.ical4j.vcard, libs.ical4j, libs.ical4j.extensions +// picocli-codegen's annotation processor fails on this tree ("ArgGroup has no options or +// positional parameters" for @ArgGroup fields inherited from abstract, non-@Command superclasses). +// picocli's runtime generators build the model exactly as the app does, so use those instead. +configurations { picocliCodegen } +dependencies { + picocliCodegen libs.picocli.codegen +} +def picocliMetadataDir = layout.buildDirectory.dir('generated/picocli-native-image/META-INF/native-image/org.ical4j/ict') -// implementation ("org.eclipse.jetty:jetty-server:$jettyVersion") { -// exclude group: 'org.slf4j', module: 'slf4j-api' -// } -// implementation ("org.eclipse.jetty:jetty-servlet:$jettyVersion") { -// exclude group: 'org.slf4j', module: 'slf4j-api' -// } -// implementation 'org.glassfish.jersey.containers:jersey-container-jetty-http:3.1.1', -// 'org.glassfish.jersey.inject:jersey-hk2:3.1.1' +[reflect: 'ReflectionConfigGenerator', resource: 'ResourceConfigGenerator', proxy: 'DynamicProxyConfigGenerator'].each { kind, gen -> + tasks.register("generatePicocli${kind.capitalize()}Config", JavaExec) { + group = 'native' + description = "Generate GraalVM ${kind}-config.json for the picocli command tree" + classpath = configurations.picocliCodegen + sourceSets.main.runtimeClasspath + mainClass = "picocli.codegen.aot.graalvm.${gen}" + def out = picocliMetadataDir.map { it.file("${kind}-config.json") } + args = ['--output', out.get().asFile.path, 'org.ical4j.command.cli.Main'] + outputs.file(out) + if (kind == 'reflect') { + // picocli registers every option/parameter type with all methods. Registering + // java.net.URL makes URL.getContent() a reflective root, whose JDK content handlers + // for images and audio live in java.desktop and drag AWT + javax.sound into the image. + doLast { + def f = out.get().asFile + def json = new groovy.json.JsonSlurper().parse(f) + json.removeAll { it.name == 'java.net.URL' } + f.text = groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(json)) + } + } + } +} + +tasks.register('generatePicocliMetadata') { + group = 'native' + description = 'Generate all GraalVM metadata for the picocli command tree' + dependsOn 'generatePicocliReflectConfig', 'generatePicocliResourceConfig', 'generatePicocliProxyConfig' +} -// compileOnly "biz.aQute.bnd:biz.aQute.bndlib:$bndVersion" - annotationProcessor 'org.osgi:osgi.core:8.0.0', - 'org.osgi:org.osgi.service.component.annotations:1.5.0', - 'org.osgi:org.osgi.service.metatype.annotations:1.4.1', - 'org.osgi:org.osgi.annotation:6.0.0' - // spock - testImplementation platform(libs.spock.bom), libs.spock.core +graalvmNative { + // Use GRAALVM_HOME / JAVA_HOME rather than Gradle toolchain resolution. + toolchainDetection = false + // The shared reachability-metadata repository needs GraalVM for JDK 23+. + // Pass -PnoMetadataRepo to compile on an older GraalVM without it. + metadataRepository { enabled = !project.hasProperty('noMetadataRepo') } + binaries { + main { + imageName = 'ict' + mainClass = 'org.ical4j.command.cli.Main' + // native-gradle-plugin 1.1.12 passes --shared with this config unless set explicitly. + sharedLibrary = false + buildArgs.add('-H:+ReportExceptionStackTraces') + // native-image runs its C toolchain with a clean environment. Pass SDKROOT through so + // a macOS SDK can be chosen when the default one does not suit the installed clang. + if (System.getenv('SDKROOT')) buildArgs.add('-ESDKROOT') + if (project.hasProperty('dryRun')) buildArgs.add('--dry-run') + if (project.hasProperty('callTree')) buildArgs.add('-H:+PrintAnalysisCallTree') + classpath.from(files(layout.buildDirectory.dir('generated/picocli-native-image')).builtBy('generatePicocliMetadata')) + } + } + // Tracing agent for a JVM run: ./gradlew -Pagent run --args='...' then ./gradlew metadataCopy + agent { + defaultMode = 'standard' + metadataCopy { + inputTaskNames.add('run') + outputDirectories.add('src/main/resources/META-INF/native-image/org.ical4j/ict') + mergeWithExisting = true + } + } +} - testRuntimeOnly libs.junit.platform +// --------------------------------------------------------------------------------------------- +// Smoke suite (src/smoke): drives an `ict` executable as a black box, one step per operation +// plus an `ict mcp` handshake, and fails if a registered operation has no step. +// +// ./gradlew jvmSmoke against the JVM build +// ./gradlew nativeSmoke against build/native/nativeCompile/ict +// ./gradlew nativeSmoke -PictBinary=... against a prebuilt binary (CI) +// ./gradlew traceSmoke JVM build under the tracing agent (needs GRAALVM_HOME), +// then mergeTracedMetadata; review the diff before commit +// ./gradlew nativeStartup median `ict --help` over ten runs, fails over 100 ms +// --------------------------------------------------------------------------------------------- +sourceSets { + smoke { + compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath + runtimeClasspath += sourceSets.main.output + sourceSets.main.runtimeClasspath } +} + +dependencies { + // SmokeSuiteTest checks that every registered operation has a smoke step. + testImplementation sourceSets.smoke.output +} + +def mainRuntimeClasspath = sourceSets.main.runtimeClasspath +def javaBin = { String home -> new File(home, "bin/java${org.gradle.internal.os.OperatingSystem.current().windows ? '.exe' : ''}").path } +def nativeBinary = providers.gradleProperty('ictBinary').orElse(layout.buildDirectory + .file("native/nativeCompile/ict${org.gradle.internal.os.OperatingSystem.current().windows ? '.exe' : ''}") + .map { it.asFile.path }) +def tracedMetadataDir = layout.buildDirectory.dir('native-agent/smoke') - // Publishing to the Sonatype Central Portal is configured via the vanniktech plugin. - // Host, auto-release and signing toggles live in gradle.properties - // (SONATYPE_HOST, SONATYPE_AUTOMATIC_RELEASE, RELEASE_SIGNING_ENABLED). - // Credentials and the signing key are supplied via ORG_GRADLE_PROJECT_* env vars in CI. - mavenPublishing { - coordinates(group.toString(), project.name, version.toString()) +tasks.register('jvmSmoke', JavaExec) { + group = 'verification' + description = 'Run the smoke suite against the JVM build' + classpath = sourceSets.smoke.runtimeClasspath + mainClass = 'org.ical4j.command.smoke.SmokeSuite' + def java = javaBin(System.getProperty('java.home')) + argumentProviders.add({ [java, '-cp', mainRuntimeClasspath.asPath, 'org.ical4j.command.cli.Main'] } as CommandLineArgumentProvider) +} - pom { - name = project.name - description = project.description - url = 'http://ical4j.github.io' +tasks.register('nativeSmoke', JavaExec) { + group = 'verification' + description = 'Run the smoke suite against the native executable' + classpath = sourceSets.smoke.runtimeClasspath + mainClass = 'org.ical4j.command.smoke.SmokeSuite' + if (!project.hasProperty('ictBinary')) { + dependsOn 'nativeCompile' + } + argumentProviders.add({ [nativeBinary.get()] } as CommandLineArgumentProvider) +} + +tasks.register('traceSmoke', JavaExec) { + group = 'native' + description = 'Run the smoke suite against the JVM build under the native-image tracing agent' + classpath = sourceSets.smoke.runtimeClasspath + mainClass = 'org.ical4j.command.smoke.SmokeSuite' + def graalHome = providers.environmentVariable('GRAALVM_HOME') + def out = tracedMetadataDir + outputs.dir(out) + doFirst { + if (!graalHome.present) { + throw new GradleException('traceSmoke needs GRAALVM_HOME pointing at GraalVM for JDK 25+') + } + project.delete(out) + } + argumentProviders.add({ + [javaBin(graalHome.get()), "-agentlib:native-image-agent=config-merge-dir=${out.get().asFile.path}", + '-cp', mainRuntimeClasspath.asPath, 'org.ical4j.command.cli.Main'] + } as CommandLineArgumentProvider) +} - licenses { - license { - name = 'iCal4j - License' - url = 'https://raw.githubusercontent.com/ical4j/ical4j/master/LICENSE' - distribution = 'repo' - } +// Merges the traced metadata on top of the checked-in file: entries are unioned, never removed, +// so the hand-written base entries survive. Review `git diff` before committing. +// +// Dropped while merging: probes for optional classes that are absent or unwanted (Groovy, +// JDBC, Micrometer, night-config formats other than the TOML instance passed explicitly) and +// single zoneinfo files, which the hand-written `zoneinfo/**` glob already covers. +def tracedNoise = ~/^(groovy\.|java\.sql\.|io\.micrometer\.|com\.electronwill\.nightconfig\.|zoneinfo\/(?!\*\*))/ +tasks.register('mergeTracedMetadata') { + group = 'native' + description = 'Merge traceSmoke output into src/main/resources/META-INF/native-image/org.ical4j/ict' + dependsOn 'traceSmoke' + def traced = tracedMetadataDir.map { it.file('reachability-metadata.json') } + def checkedIn = layout.projectDirectory.file('src/main/resources/META-INF/native-image/org.ical4j/ict/reachability-metadata.json') + doLast { + def slurper = new groovy.json.JsonSlurper() + def base = slurper.parse(checkedIn.asFile) + def extra = slurper.parse(traced.get().asFile) + extra.each { section, entries -> + if (entries instanceof List) { + def merged = (base[section] ?: []) as List + entries.findAll { e -> !((e.type ?: e.glob ?: '') ==~ (tracedNoise.pattern() + '.*')) } + .each { e -> if (!merged.contains(e)) merged << e } + base[section] = merged.sort { groovy.json.JsonOutput.toJson(it) } } + } + checkedIn.asFile.text = groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(base)) + '\n' + } +} + +tasks.register('nativeStartup', JavaExec) { + group = 'verification' + description = 'Report the median `ict --help` wall time of the native executable; fail over 100 ms' + classpath = sourceSets.smoke.runtimeClasspath + mainClass = 'org.ical4j.command.smoke.StartupTime' + if (!project.hasProperty('ictBinary')) { + dependsOn 'nativeCompile' + } + argumentProviders.add({ [nativeBinary.get(), '10', '100'] } as CommandLineArgumentProvider) +} + +// --------------------------------------------------------------------------------------------- +// Publishing to the Sonatype Central Portal via the vanniktech plugin. Host, auto-release and +// signing toggles live in gradle.properties (SONATYPE_HOST, SONATYPE_AUTOMATIC_RELEASE, +// RELEASE_SIGNING_ENABLED). Credentials and the signing key are supplied via +// ORG_GRADLE_PROJECT_* env vars in CI. The jar is published for embedding; the native binary +// attached to GitHub Releases is the primary deliverable. +// --------------------------------------------------------------------------------------------- +mavenPublishing { + coordinates(group.toString(), 'ict', version.toString()) - developers { - developer { - id = 'fortuna' - name = 'Ben Fortuna' - } + pom { + name = 'ict' + description = project.description + url = 'http://ical4j.github.io' + + licenses { + license { + name = 'iCal4j - License' + url = 'https://raw.githubusercontent.com/ical4j/ical4j/master/LICENSE' + distribution = 'repo' } + } - scm { - url = 'https://github.com/ical4j/ical4j-command' - connection = 'scm:git@github.com:ical4j/ical4j-command.git' - developerConnection = 'scm:git@github.com:ical4j/ical4j-command.git' + developers { + developer { + id = 'fortuna' + name = 'Ben Fortuna' } } + + scm { + url = 'https://github.com/ical4j/ical4j-command' + connection = 'scm:git@github.com:ical4j/ical4j-command.git' + developerConnection = 'scm:git@github.com:ical4j/ical4j-command.git' + } } -} \ No newline at end of file +} diff --git a/docs/command-protocols.md b/docs/command-protocols.md index 06e4661..09f02ba 100644 --- a/docs/command-protocols.md +++ b/docs/command-protocols.md @@ -1,118 +1,134 @@ -# iCal4j Command Protocols - -This document describes the various command protocols and tools provided by the iCal4j Command library for managing iCalendar and vCard data. - -## Canonical Vocabulary - -All command surfaces (CLI, MCP, agent) name operations from a single controlled vocabulary -defined in the `ical4j-command-core` module. Each operation is identified by a **verb**, an -**entity type**, and a **locus** (container). Surfaces share these names but dispatch -independently. - -- **Verbs** (`org.ical4j.command.core.Verb`): `list` (many), `get` (one), `generate` - (synthesise from a strategy/template), `add` (place into a locus), `update`, `remove` - (take out of a locus), `copy`, `move`, `filter`, `validate`, `import`, `export`, `send`, - `receive`. There is no `create`/`delete` — these are standardised on `add`/`remove`. +# Command protocols + +`ict` has one table of operations, the **registry**, and two **views** over it: the command line +and the MCP server. An operation is defined once, with its parameters and handler; each view +derives its own interface from that definition and executes through the registry. Nothing is +written per surface. + +``` + ┌──────────────────────────────┐ + ict │ cli.CommandTree │ + ────────────────► │ picocli subcommands/options │──┐ + └──────────────────────────────┘ │ ┌────────────────────────┐ + ├──►│ ops.Registry │──► handler(Context, Params) + ┌──────────────────────────────┐ │ │ (verb, subject, locus) │ │ + tools/call │ mcp.Tools │──┘ └────────────────────────┘ ▼ + ────────────────► │ tools + JSON input schemas │ Result + └──────────────────────────────┘ │ + ops.Renderer: text / json / xml ◄───┘ +``` + +## Vocabulary + +Operations are named from a controlled vocabulary in `org.ical4j.command.vocab`. The package +holds definitions only; it has no dispatch logic. + +- **Verbs** (`Verb`): `list` (many), `get` (one), `generate` (synthesise from a template), `add` + (place into a locus), `update`, `remove` (take out of a locus), `copy`, `move`, `filter`, + `validate`, `import`, `export`, `send`, `receive`. There is no `create` or `delete`; those + are `add` and `remove`. - **Entity types** (`EntityType`): `event`, `action`, `issue`, `note`, `observance`, - `availability`, `report`, `entity` (contact), `resource`. All live directly within a - collection. -- **Loci** (`Locus`): `workspace` ⊃ `collection` (two levels; entities live directly in a - collection). -- **Serialization families** (`SerializationFamily`): `calendar` (iCalendar), `card` - (vCard). These are NOT loci or entity types; data crosses a collection boundary via - `import`/`export`. -- **iTIP methods** (`SendMethod`): `publish`, `request`, `reply` are specialised forms of - `send`, not independent verbs. - -## Calendar Commands - -### Validator -- Purpose: Validates iCalendar data for conformance to specifications -- Location: `org.ical4j.command.calendar.Validator` -- Usage: Validates iCalendar objects for RFC compliance and structural integrity - -### Filter -- Purpose: Filters iCalendar components based on expressions -- Location: `org.ical4j.command.calendar.FilterCalendar` -- Usage: Selects subsets of iCalendar components using filter criteria - -### Free/Busy -- Purpose: Generates availability information -- Location: `org.ical4j.command.calendar.FreeBusy` -- Usage: Creates free/busy time reports from calendar data - -### Replace UIDs -- Purpose: Regenerates unique identifiers -- Location: `org.ical4j.command.calendar.ReplaceUids` -- Usage: Updates UIDs across all calendar components - -## Collection Management - -### Calendar Collections -- Import Calendar (`import-calendar`): Imports calendar data into a collection -- Export Calendar (`export-calendar`): Exports calendar data from a collection -- Remove Calendar (`remove-calendar`): Removes calendar data from a collection -- List: Enumerates calendar entities in a collection - -### Card Collections -- Import Card (`import-card`): Imports vCard data into a collection -- Export Card (`export-card`): Exports vCard data from a collection -- Remove Card (`remove-card`): Removes vCard data from a collection -- List: Enumerates vCard entities in a collection - -## Channel Operations - -### Calendar Channels -- Send Calendar: Transmits calendar data to specified endpoints. The iTIP methods - `publish`, `request` and `reply` are specialised forms of `send`. -- Receive Calendar: Accepts incoming calendar data - -### vCard Channels -- Send vCard: Transmits vCard data to specified endpoints -- Receive vCard: Accepts incoming vCard data - -## Store Operations - -### Collection Management -- Add Collection: Adds a collection to a workspace -- Remove Collection: Removes a collection from a workspace -- Get Collection: Retrieves collection metadata -- List Collections: Enumerates available collections -- Update Collection: Modifies collection properties - -## Strategy (Generation) Operations - -### Event Templates -- Purpose: Generates calendar data using simplified templates (the `generate` verb) -- Location: `org.ical4j.command.strategy.CreateEvent` (command name `generate event`) -- Usage: Synthesises calendar entries from template definitions - -## Configuration - -### System Properties -The following properties can be configured: - -- `org.ical4j.command.prodid`: Customizes the PRODID property -- `org.ical4j.command.organizer`: Sets default organizer URI -- `org.ical4j.command.uidgenerator`: Specifies UID generation implementation - -## Common Patterns - -### Input/Output Handling -- Input handling through `InputHandler` interface -- Output processing via `DefaultOutputHandlers` -- Support for various data formats and sources - -### Command Groups -- Calendar Command Group: Calendar-specific operations -- Card Command Group: vCard-specific operations -- Channel Command Group: Communication operations -- Collection Command Group: Data collection management -- Store Command Group: Storage operations -- Template Command Group: Template-based generation - -Each command follows a consistent protocol pattern: -1. Input validation -2. Operation execution -3. Result handling -4. Error management + `availability`, `report`, `entity` (a contact), `resource`. All live directly in a collection. +- **Serialization families** (`SerializationFamily`): `calendar` (iCalendar) and `card` (vCard), + the representations that `import` and `export` move across a collection boundary. +- **Loci** (`Locus`): `workspace` contains `collection`s, which contain entities; the hierarchy + is two levels deep. `channel` is the locus of `send` and `receive`, and `none` marks + operations on a stream or file that touch no store, such as `generate`. +- **iTIP methods** (`SendMethod`): `publish`, `request` and `reply` qualify `send`; they are not + verbs. + +The type axis of an operation is a `Subject`: an entity type, a serialization family, or a +container locus when the container itself is the object (`list collection in workspace`, +`add collection in workspace`). `channel` and `none` are never subjects. + +## Operations + +An operation is an `ops.Operation`: + +| Part | Type | Notes | +|---|---|---| +| identity | `OperationId(verb, subject, locus)` | written `list event in collection`, or `generate event` when the locus is `none` | +| description | `String` | one sentence; becomes CLI help and the MCP tool description | +| parameters | `List` | name, type (`string`, `integer`, `boolean`, `enum`, `path`, or a list of one), required flag, default, description | +| exposure | `Set` | `CLI`, `MCP`, or both (the default) | +| handler | `(Context, Params) -> Result` | the implementation | + +Handlers follow three rules: + +- **They return structure, not text.** A `Result` is a calendar, a card, identifiers, one or more + descriptors (name/value attributes), a status message or a validation report. `ops.Renderer` + turns it into text, JSON or XML for whichever surface asked. +- **They signal failure with a typed `OperationException`**: `NotFound`, `AlreadyExists`, + `Usage`, `InvalidData` or `Store`. Each surface maps these to its own convention. +- **They touch the world only through their `Context`**: the active workspace, the calendar and + card stores, and standard input. Surfaces build the context from configuration; specs build it + around a temp-dir store. Handlers never read configuration or write to a stream. + +The `Registry` rejects a second operation with the same identity, and `Operations.standard()` +assembles the operations the binary ships. + +## The CLI view + +`cli.CommandTree` builds the picocli tree from the registry at startup, using picocli's +programmatic API so no command class is annotated or reflected on. + +- One subcommand per verb that has CLI-exposed operations, in vocabulary order, and under each + one subcommand per operation, named by its subject: `ict list event`. +- Every parameter becomes an option, `--`, with the parameter's description, required + flag, choices and default in its help. Values reach the handler as strings and are converted + there, so no JDK type is ever registered for reflection. +- Loci are options. `--collection` is the shared `collection` parameter that every + collection-locus operation declares, so it appears only where it applies. `--workspace` is a + global option that overrides the configured active workspace. +- Global options (`--workspace`, `--format`, `-v`, `-q`, `--lenient`, `--help`, `--version`) + are inherited by every command. A parameter may not reuse one of their names. +- The CLI names an operation by verb and subject only, so two operations differing only in + locus cannot both be exposed to it; the tree builder fails at startup if they are. + +Results are rendered in the `--format` requested and written to stdout. Failures write +`ict: ` to stderr and exit 1, or 2 for usage errors (including picocli's own parse +errors and `OperationException.Usage`). Unexpected exceptions also print a stack trace. + +`ict config` is the one hand-written command. It edits the configuration the context is built +from, so it is not an operation. + +## The MCP view + +`mcp.Tools` turns each MCP-exposed operation into a tool and `mcp.McpCommand` serves them with +the MCP Java SDK's synchronous server on the stdio transport (`ict mcp`). + +- Tool names are `_`: `list_event`, `import_calendar`. As with the CLI, a name + clash fails at startup. +- The input schema is a JSON schema object generated from the parameters: `string`, `integer` + and `boolean` map directly, `enum` becomes a string with `enum` values, `path` a string, and + list parameters arrays. Required parameters are listed in `required`, defaults appear as + `default`, and unknown properties are rejected. +- Tools carry `readOnlyHint` for `list`, `get`, `export`, `validate` and `filter`, and + `destructiveHint` for `remove`, `move` and `update`. +- Calendars and cards are returned as iCalendar or vCard text; everything else as JSON text. + An `OperationException`, or any other failure, is returned as a tool result with `isError` + set and the message as its text. Protocol errors are left to the SDK. +- The server's stdout carries protocol messages only. `System.out` and picocli's output are + pointed at stderr while it runs, logging goes to stderr already, and handlers get an empty + stdin. A spec runs the server with `-vvv` and checks every stdout line is JSON-RPC. + +## Adding an operation + +An operation enters the registry only with tests and a smoke run (design D8 of the +`single-native-binary` change): + +1. Define it in the `ops` class for its subject and add it to `Operations.standard()`. +2. Write a Spock specification that runs its handler against a temp-dir store and names its + identity as a literal, for example `op('list event in collection')`. + `RegistryConformanceTest` fails the build for any registered operation that no + specification names. +3. Add a step to `src/smoke/.../SmokeSuite.java` that invokes it, marked with the identity it + covers. The suite, and `SmokeSuiteTest`, fail for any operation without a step. +4. Run `./gradlew mergeTracedMetadata` with `GRAALVM_HOME` set. This runs the smoke suite on the + JVM under the native-image tracing agent and merges what it records into the checked-in + reachability metadata. Review the diff. +5. Check the native binary: `./gradlew nativeSmoke`. + +Nothing is needed in `cli` or `mcp`: the command, its options, the tool and its schema all +follow from the definition. The commands awaiting admission, with the identity each is +expected to take, are listed in [`dropped-commands.md`](dropped-commands.md). diff --git a/docs/dropped-commands.md b/docs/dropped-commands.md new file mode 100644 index 0000000..4ea4614 --- /dev/null +++ b/docs/dropped-commands.md @@ -0,0 +1,104 @@ +# Dropped commands and their registry tuples + +Every hand-written picocli command was quarantined under `src/legacy` by the +`single-native-binary` change. None is compiled. This table records where each one is meant +to land in the operation registry as a (verb, type, locus) tuple from the vocabulary in +`org.ical4j.command.vocab`, so re-admission is a lookup rather than a rediscovery. + +Conventions: + +- **Locus `none`** marks operations that act on a stream or file rather than a store + (`generate`, `validate` on a file, `export` from a file). The registry needs a no-locus form + for these; the `Locus` enum today has only `workspace` and `collection`. +- **`export`/`import` with `--format`** replace the old `serialize`, `convert` and `print` + commands: those were all "write this object out in some representation". +- **Entities by UID** live directly in a collection. The old `remove-calendar` / `remove-card` + removed one stored object by identifier, so they become `remove --uid`, not a + `calendar`-family operation. +- **Cohort 1** is the set covered by the 13 Spock specs that were green at quarantine time. + Rows marked *1 (done)* were re-admitted in task 2.5 with new specs against local stores on a + temp directory; their legacy classes and mock-based specs were then deleted from `src/legacy`. +- **Not an operation** marks picocli group nodes that only held subcommands; the verb-first + tree replaces them. + +| Legacy class | Old invocation | Tuple (verb, type, locus) | Cohort | Notes | +|---|---|---|---|---| +| `collection.AddCollection` | `mkcol --type` | (`add`, `collection`, `workspace`) | 1 (done) | admitted: `CollectionOperations.add`, spec `CollectionOperationsTest` | +| `collection.RemoveCollection` | `rmcol ` | (`remove`, `collection`, `workspace`) | 1 (done) | admitted: `CollectionOperations.remove`, spec `CollectionOperationsTest` | +| `collection.GetCollectionDetails` | `get-collection-details ` | (`get`, `collection`, `workspace`) | 1 (done) | admitted: `CollectionOperations.get`, spec `CollectionOperationsTest` | +| `ListCommand` | `list [spec]` | (`list`, ``, `collection`) | 1 (done) | admitted as `list collection in workspace` (`CollectionOperations.list`) and `list event|action|note|entity in collection` (`ListOperations`), specs `CollectionOperationsTest`, `ListOperationsTest`. The old `--filter` is deferred to the `filter` verb | +| `collection.ListObjectUids` | `list-uids` | (`list`, ``, `collection`) | later | subsumed by `list` with a `--uids-only` output choice | +| `collection.ListCards` | `list-cards` | (`list`, `entity`, `collection`) | later | subsumed by `list entity` | +| `collection.UpdateCollection` | `update-collection` | (`update`, `collection`, `workspace`) | later | | +| `collection.CollectionCommandGroup` | `collections ...` | not an operation | | group node | +| `calendar.UpdateCalendar` | `import-calendar` | (`import`, `calendar`, `collection`) | 1 (done) | admitted: `CalendarOperations.importCalendar`, spec `CalendarOperationsTest` | +| `calendar.GetCalendar` | `export-calendar` | (`export`, `calendar`, `collection`) | 1 (done) | admitted: `CalendarOperations.exportCalendar`, spec `CalendarOperationsTest` | +| `calendar.DeleteCalendar` | `remove-calendar ` | (`remove`, ``, `collection`) | 1 (done) | admitted as (`remove`, `calendar`, `collection`): `CalendarOperations.removeCalendar`, spec `CalendarOperationsTest` | +| `card.UpdateCard` | `import-card` | (`import`, `card`, `collection`) | 1 (done) | admitted: `CardOperations.importCard`, spec `CardOperationsTest` | +| `card.GetCard` | `export-card` | (`export`, `card`, `collection`) | 1 (done) | admitted: `CardOperations.exportCard`, spec `CardOperationsTest` | +| `card.DeleteCard` | `remove-card ` | (`remove`, `entity`, `collection`) | 1 (done) | admitted: `CardOperations.removeCard`, spec `CardOperationsTest` | +| `ImportCalendars` | `import` | (`import`, `calendar`, `collection`) | later | duplicate of `import-calendar` with a different input path; merge | +| `ImportCards` | `import-cards` | (`import`, `card`, `collection`) | later | duplicate of `import-card`; merge | +| `ExportCommand` | `export` | (`export`, `calendar`\|`card`, `collection`) | later | family chosen by collection type | +| `strategy.CreateCalendar` | `generate calendar` | (`generate`, `calendar`, `none`) | 1 | spec: `CreateCalendarTest` | +| `strategy.CreateCard` | `generate card` | (`generate`, `card`, `none`) | 1 | spec: `CreateCardTest` | +| `strategy.CreateEvent` | `generate event` | (`generate`, `event`, `none`) | later | option declarations broken (flags without values); needs a rewrite before a spec | +| `strategy.CreateAction` | `generate action` | (`generate`, `action`, `none`) | later | | +| `strategy.CreateIssue` | `generate issue` | (`generate`, `issue`, `none`) | later | | +| `strategy.CreateNote` | `generate note` | (`generate`, `note`, `none`) | later | | +| `strategy.CreateObservance` | `generate observance` | (`generate`, `observance`, `none`) | later | | +| `strategy.CreateEntity` | `generate entity` | (`generate`, `entity`, `none`) | later | | +| `strategy.StrategyInfo` | `strategy` | not an operation | | printed nothing; strategy listing belongs in `generate --help` | +| `strategy.StrategyCommandGroup` | `generate` / `new` | not an operation | | group node; `generate` is the verb | +| `ValidatorCommand` | `validate -file\|-url\|-collection\|-` | (`validate`, `calendar`\|`card`, `none`) and (`validate`, ``, `collection`) | later | file form and collection form are two registry entries | +| `calendar.Validator` | `calendar validator` | (`validate`, `calendar`, `none`) | later | duplicate of `validate`; drop | +| `FilterCommand` | `filter --filter` | (`filter`, ``, `collection`) and file form | later | expression grammar rejected `summary contains 'x'` during the spike; check before admitting | +| `calendar.FilterCalendar` | `calendar filter` | (`filter`, ``, `collection`) | later | duplicate of `filter`; drop | +| `ConverterCommand` | `convert --format` | (`export`, `calendar`\|`card`, `none`) with `--format` | later | JCARD output cycles in Jackson on the JVM; XML/JSON calendar output works natively | +| `calendar.Serializer` | `calendar serialize` | (`export`, `calendar`, `none`) with `--format` | later | duplicate of `convert`; drop | +| `card.Serializer` | `card serialize` | (`export`, `card`, `none`) with `--format` | later | duplicate of `convert`; drop | +| `PrintCommand` | `print` | (`export`, `calendar`\|`card`, `collection`) text format | later | `export` with the default text renderer | +| `calendar.FreeBusy` | `freebusy` | (`generate`, `availability`, `none`) | later | free/busy is an `availability` entity generated from input | +| `calendar.ReplaceUids` | `replace-uids` | (`update`, ``, `none`) | later | a transform over a stream; may become an `export --regenerate-uids` option instead | +| `CopyCommand` | `copy` / `cp` | (`copy`, ``, `collection`) | later | | +| `MoveCommand` | `move` / `mv` | (`move`, ``, `collection`) | later | | +| `DeleteCommand` | `remove` / `rm` | (`remove`, ``, `collection`) | later | generic form of `remove-calendar` / `remove-card` | +| `EditCommand` | `edit` | (`update`, ``, `collection`) | later | | +| `metadata.GetProperty` | `get ` | (`get`, ``, `collection`) with `--property` | later | property access is an option on `get`, not its own verb | +| `metadata.SetCommandGroup` | `set ` | (`update`, ``, `collection`) with `--set` | later | | +| `metadata.UnsetProperty` | `unset ` | (`update`, ``, `collection`) with `--unset` | later | | +| `metadata.AddAttachment` | `add attach` | (`update`, ``, `collection`) with `--attach` | later | | +| `metadata.AddCategories` | `add categories` | (`update`, ``, `collection`) with `--category` | later | | +| `metadata.AddComment` | `add comment` | (`update`, ``, `collection`) with `--comment` | later | | +| `metadata.AddRelated` | `add related` | (`update`, ``, `collection`) with `--related` | later | | +| `metadata.AddCommandGroup` | `add ...` | not an operation | | group node; `add` the verb means placing an item in a locus, not adding metadata | +| `metadata.PropertyCommandGroup` | (base class) | not an operation | | | +| `revisions.ListRevisions` | `revisions` | (`list`, `report`, `collection`) | later | revisions are a report over a collection; store support unverified | +| `revisions.RevertRevision` | `revert` | (`update`, `collection`, `workspace`) | later | | +| `revisions.UndoRevisions` | `undo` | (`update`, `collection`, `workspace`) | later | | +| `channel.SendCalendarCommand` | `send-calendar` | (`send`, `calendar`, `channel`) with `--method` | later | iTIP method via `SendMethod`; channel is not a `Locus` today | +| `channel.SendVCardCommand` | `send-card` | (`send`, `card`, `channel`) | later | | +| `channel.ReceiveCalendarCommand` | `receive-calendar` | (`receive`, `calendar`, `channel`) | later | | +| `channel.ReceiveVCardCommand` | `receive-card` | (`receive`, `card`, `channel`) | later | | +| `channel.ChannelCommandGroup` | `channel ...` | not an operation | | group node | +| `workspace.ListWorkspaces` | `list-workspaces` / `lws` | (`list`, `workspace`, `none`) | later | worked on the JVM and natively during the spike; an easy early admission | +| `workspace.ActivateWorkspace` | `activate` / `chws` | (`update`, `workspace`, `none`) with `--active` | later | could also be `ict config workspace.active` | +| `workspace.PrintWorkspace` | `print-workspace` / `pws` | (`get`, `workspace`, `none`) | later | failed on the JVM with "Unable to initialise collection config" | +| `workspace.WorkspaceCommandGroup` | `workspace ...` | not an operation | | group node | +| `config.ConfigureCommand` | `configure` | not an operation | | becomes `ict config` (task 3.4), outside the registry | +| `calendar.CalendarCommandGroup` | `calendar ...` | not an operation | | group node | +| `card.CardCommandGroup` | `card ...` | not an operation | | group node | + +Support classes quarantined alongside, with no tuple of their own: `AbstractCommand`, +`DefaultOutputHandlers` (ported to `ops.Renderer` in task 2.6 and deleted), `InputHandler`, `InputOptions`, +`OutputOptions`, `calendar.AbstractCalendarCommand`, `card.AbstractEntityCommand`, +`channel.AbstractEgressChannelCommand`, `channel.AbstractIngressChannelCommand`, +`collection.AbstractCollectionCommand`, `workspace.AbstractWorkspaceCommand`. + +Vocabulary gaps this table exposes, to settle when the registry is defined (task 2.1): + +- a no-locus form (`none`) for stream and file operations and for `generate`; +- `channel` as the locus of `send` / `receive`, which the vocabulary spec names but the + `Locus` enum does not carry; +- `workspace` and `collection` as entity types when they are the thing being listed or + fetched, alongside their role as loci. diff --git a/docs/native-spike.md b/docs/native-spike.md new file mode 100644 index 0000000..b9c9676 --- /dev/null +++ b/docs/native-spike.md @@ -0,0 +1,159 @@ +# Native image spike (single-native-binary, task 0) + +Date: 2026-09-05. Branch: `spike/native-cli` (throwaway, off `single-native-binary`). +Goal: compile the current `ical4j-command-cli` module with GraalVM native-image before +restructuring anything, so the cost of the dependency set is known. + +## Result + +`./gradlew :ical4j-command-cli:nativeCompile` produces a working `ict` executable. + +| Measure | Native (GraalVM CE 25.3.4, macOS arm64) | JVM (Temurin 17, installDist) | +|---|---|---| +| `ict --help` wall time | 20–30 ms | 350–370 ms | +| Binary size | 50 MB, plus ~5 MB of AWT dylibs copied alongside | n/a | +| Compile time | 1 m 45 s, peak RSS 2.7 GB | n/a | + +Working natively without any extra metadata: `--version`, `--help` on every subcommand, +`validate -file`, `convert --help`, `filter --help`, `generate --help`. + +## Toolchain findings + +1. **GraalVM version.** `org.graalvm.buildtools.native` 1.1.12 refuses to use its shared + reachability-metadata repository with GraalVM for JDK 21 (schema too old). Either run + GraalVM for JDK 23+ or pass `-PnoMetadataRepo` (added to the cli build) to disable the + repository. GraalVM CE 25.3.4 is the version to standardise on. +2. **Shared-library default.** With plugin 1.1.12 and this build script the native-image + command line carried `--shared` even though `mainClass` was set, producing `ict.dylib`. + Setting `sharedLibrary = false` explicitly fixes it. Keep that line. +3. **picocli-codegen annotation processor fails on this tree.** Error: + `ArgGroup has no options or positional parameters ... FIELD input in AbstractEntityCommand`. + The `@ArgGroup InputOptions` fields live in abstract, non-`@Command` superclasses, which + the processor does not model. picocli's runtime generators + (`ReflectionConfigGenerator`, `ResourceConfigGenerator`, `DynamicProxyConfigGenerator`) + build the model the way the app does and work: 102 reflect entries generated. The cli + build now runs them as `generatePicocliMetadata` and feeds the output dir to the image + classpath. For the new registry-driven tree (design D2) the generators stay the right + tool because commands will not be annotated classes at all. +4. **Deprecated flags.** GraalVM 25 warns that `--no-fallback` has no effect and that + `proxy-config.json` is deprecated in favour of `reachability-metadata.json`. Harmless. + +## Dependency findings + +| Dependency | Native status | Action | +|---|---|---| +| picocli 4.7.7 | works with generated metadata | keep; runtime generators in build | +| ical4j 4.2.3 | parses and validates; ships its own `META-INF/native-image` (tz.alias resource + 2 reflect entries). Still logs `Error loading timezone aliases: inStream parameter is null` twice at startup, and the 618-file `zoneinfo` / `zoneinfo-global` trees are not registered, so VTIMEZONE generation will fail natively until they are | add resource-config for `zoneinfo/**`, `zoneinfo-global/**`, and check why `tz.alias` is not found despite the bundled pattern; ServiceLoader factories (`PropertyFactory` etc.) resolved without extra work | +| night-config 3.8.3 (toml) | **breaks** any command touching `CommandConfig`: `NoFormatFoundException: No suitable format for ictrc.toml`. `FormatDetector` locates `TomlFormat` via `Class.forName`, which is invisible to the image | one-line code fix: build `FileConfig` with `TomlFormat.instance()` explicitly, or a reflect entry for `com.electronwill.nightconfig.toml.TomlFormat` | +| log4j2 2.25.2 | initialises and logs to stderr natively (metadata repository supplies config) | still replace per design D7; it is 2 of the 35 jars and owns stdout/stderr routing | +| jackson databind + dataformat-xml + woodstox | image builds; not exercised at runtime (`convert` needs a valid input file) | exercise in task 0.2 with the tracing agent; repository has metadata for databind 2.15 and dataformat-xml 2.22 | +| commons-lang3 3.18.0 | only jar on the classpath referencing `java.desktop` (via `java.beans`); first suspected as the cause of the AWT dylibs | hypothesis disproved in task 0.3, see below: the cause is picocli's reflect-config for `java.net.URL` | +| `module-info.java` `requires java.desktop` | not the cause of the AWT libs; nothing in this repo uses AWT | remove module-info with the restructure | + +## Pre-existing (not native) issues surfaced + +- `src/test/resources/geo.ics` fails to parse on the JVM too (`Invalid GEO string`), so it is + not a valid smoke input. Need a known-good fixture. +- `ict generate event` declares `--summary` and `--description` as flags without values and + rejects any actual arguments. Confirms the strategy commands belong to the untested set. +- `ict strategy` prints nothing and exits 0. + +## Task 0.2: tracing agent + +Two captures were taken on GraalVM CE 25 (JDK 25 ran the Groovy 3 / Spock suite without +trouble): + +| Capture | How | Reflection entries | Resources | Signal | +|---|---|---|---|---| +| Test suite | `./gradlew -Pagent :ical4j-command-cli:test` with a caller filter excluding Spock, Groovy, JUnit and Gradle (`src/test/resources/native-agent/caller-filter.json`) | 507 | 52 | noisy: 243 log4j entries, Groovy `*BeanInfo`/`*Customizer` introspection, test-framework service files. The caller filter trims reflection but resource lookups still leak because the JDK is the caller | +| Manual invocations | JVM `installDist` launched with `-agentlib:native-image-agent=config-merge-dir=...` running `validate`, `convert` (JCAL, XCAL, JSCALENDAR), `list-workspaces`, `--version`, a vCard `validate`, and a calendar whose `TZID`s have no `VTIMEZONE` | 369 | 44 | clean: `TomlFormat`, `tz.alias`, `msTimezoneIds/Names`, `zoneinfo/tz.availableIds`, the two `zoneinfo/*.ics` files touched, StAX factories for XML | + +Merged into `src/main/resources/META-INF/native-image/org.ical4j/ict/reachability-metadata.json` +(447 reflection entries, 24 resource globs) with test-framework noise dropped and the two +per-file zoneinfo entries replaced by `zoneinfo/**` and `zoneinfo-global/**`, since any TZID can +be requested at runtime. + +Rebuilt with that file, the native binary passes everything that failed in task 0.1: + +| Command | Before | After | +|---|---|---| +| `ict list-workspaces`, `ict list --help` | `NoFormatFoundException` from night-config | works (reflect entry for `TomlFormat`) | +| `ict validate` on a calendar with TZIDs but no VTIMEZONE | untested | works, no alias warning (zoneinfo globs) | +| `ict convert --format XCAL` / `JCAL` / `JSCALENDAR` | untested | works (StAX service files, Jackson entries) | +| `ict validate --mode VCARD` | untested | works | +| `ict --help` | 20–30 ms | 30 ms, 54 MB binary | + +Lessons for the real build (design D6, task 5.2): +- Do not derive metadata from the Spock run. Drive the tracing agent from the native smoke + suite's command list on the JVM build instead, so the capture is exactly the surface the + binary must support and carries no test-framework noise. +- Keep a small hand-written base file (`zoneinfo/**`, `zoneinfo-global/**`, `tz.alias`, + `TomlFormat` until the code fix lands) and let the agent output merge on top. +- The AWT dylibs are unchanged (11 files next to the binary); that is a reachability question + for `java.beans` via commons-lang3, still open and still not blocking. + +Pre-existing JVM failures found while capturing, none native-related: +- `ict list` and `ict print-workspace` throw `Unable to initialise collection config` on the JVM. +- `ict convert --format JCARD` on a vCard fails in Jackson with a self-reference cycle through + `VCard.entities`, so the vCard JSON path in ical4j-serializer is broken independent of native. +- `ict filter --filter "summary contains 'Spike'"` rejects that expression; the grammar needs + checking before the `filter` verb is admitted. + +## Task 0.3: per-dependency cost, measured + +To separate what each dependency really needs from what the agent happened to record, the +447-entry merged file was replaced by a hand-written one and the binary rebuilt. Everything +that failed in 0.1 passes with this, 13 entries in total: + +```json +{ + "reflection": [ + { "type": "com.electronwill.nightconfig.toml.TomlFormat" }, + { "type": "net.fortuna.ical4j.model.TimeZoneRegistryImpl", "methods": [{ "name": "", "parameterTypes": [] }] }, + { "type": "net.fortuna.ical4j.util.MapTimeZoneCache", "methods": [{ "name": "", "parameterTypes": [] }] }, + { "type": "com.fasterxml.jackson.databind.ext.Java7SupportImpl", "methods": [{ "name": "", "parameterTypes": [] }] } + ], + "resources": [ + { "glob": "ictrc.default.toml" }, { "glob": "simplelogger.properties" }, { "glob": "ical4j.properties" }, + { "glob": "net/fortuna/ical4j/model/tz.alias" }, { "glob": "tz.alias" }, + { "glob": "zoneinfo/**" }, { "glob": "zoneinfo-global/**" }, + { "glob": "net/fortuna/ical4j/transform/compliance/msTimezoneIds" }, + { "glob": "net/fortuna/ical4j/transform/compliance/msTimezoneNames" } + ] +} +``` + +| Dependency | What it actually needs natively | Failure without it | Better fix in the new tree | +|---|---|---|---| +| night-config toml | one type entry for `TomlFormat` (`FormatDetector` probes it with `Class.forName`) | `NoFormatFoundException` on any config access | pass `TomlFormat.instance()` to `FileConfig.builder`, then no entry at all | +| ical4j | constructor entries for `TimeZoneRegistryImpl` and `MapTimeZoneCache` (both instantiated by name from `ical4j.properties` defaults), resource globs for `zoneinfo/**`, `zoneinfo-global/**`, `tz.alias`, `msTimezone*`, `ical4j.properties` | `ClassNotFoundException: TimeZoneRegistryImpl` when a TZID has no in-file VTIMEZONE; alias warnings at startup | contribute the entries upstream to ical4j's bundled `META-INF/native-image` (it already ships `tz.alias`), or keep them in our base file | +| jackson databind | one constructor entry for `Java7SupportImpl`; everything else comes from the plugin's metadata repository | none observed, entry captured by the agent | keep; it is one line | +| jackson-dataformat-xml + woodstox | nothing beyond the metadata repository; StAX providers resolve through automatic ServiceLoader support | none | keep as is while `--format XCAL` exists | +| log4j2 | nothing beyond the metadata repository plus our `log4j2.properties` resource | none | still replace (design D7), for stdout discipline not for native reasons | +| picocli | generated reflect-config, minus one entry (see below) | commands not instantiable | keep the runtime generators | + +### The AWT libraries were picocli's doing + +The 11 dylibs (`libawt`, `libfontmanager`, `libfreetype`, `libjsound`, ...) copied next to the +binary were not caused by commons-lang3. `-H:+PrintAnalysisCallTree` shows two roots: + +- `java.net.URL.getContent()` marked as a reflective root method. picocli's generated + reflect-config registers every option type with `allPublicMethods`, and `InputOptions` has a + `-url` option of type `java.net.URL`. The JDK's `ContentHandler`s for images and audio live in + `java.desktop` (`sun.awt.www.content.*`), so `getContent` reaches `Toolkit`, + `GraphicsEnvironment` and `javax.sound.sampled.AudioSystem`. +- Once those classes are in the analysis universe, type-hierarchy analysis adds + `sun.awt.SoftCache` behind `Map.clear()` and `EventDispatchThread` behind `Runnable.run()`. + +Removing the `java.net.URL` entry from the generated reflect-config (now done in a `doLast` on +`generatePicocliReflectConfig`) drops every dylib. The binary is a single 51 MB file, `-url` +still works because picocli converts the string with `new URL(String)` directly, and startup is +unchanged at 30 ms. For the registry-driven tree the lesson is: parameter types are +`String`/`Path`/enum, converted in the handler, so no JDK type is ever registered wholesale. + +## Decision for task 0.4 + +Proceed with plain GraalVM (design D6). The dependency set is not hostile: the only hard +failure is a `Class.forName` in night-config with a one-line fix, and the remaining work is +resource registration for ical4j's zoneinfo, which the tracing agent will capture. Quarkus is +not needed. diff --git a/gradle.properties b/gradle.properties index adc9979..cd8fbd0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,3 @@ -bndVersion = 7.1.0 - # Maven Central publishing (vanniktech maven-publish plugin). # Credentials and the signing key are provided via ORG_GRADLE_PROJECT_* env vars in CI: # ORG_GRADLE_PROJECT_mavenCentralUsername / ORG_GRADLE_PROJECT_mavenCentralPassword diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 4ca2999..f9f31fe 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -6,13 +6,11 @@ ical4j-connector = "2.0.0-beta1" ical4j-integration = "0.3.1" ical4j-serializer = "0.4.1" groovy = "3.0.25" -log4j = "2.25.2" +slf4j = "2.0.17" spock = "2.4-M7-groovy-3.0" junitVintage = "5.14.1" -picocli = "4.6.3" -langchain4j = "1.7.1" -spring-ai = "1.1.0" -spring-boot = "3.5.7" +picocli = "4.7.7" +mcp = "2.0.1" [libraries] ical4j = { module = "org.mnode.ical4j:ical4j", version.ref = "ical4j" } @@ -23,20 +21,20 @@ ical4j-integration-api = { module = "org.ical4j:ical4j-integration-api", version ical4j-serializer = { module = "org.ical4j:ical4j-serializer", version.ref = "ical4j-serializer" } picocli = { module = "info.picocli:picocli", version.ref = "picocli" } +picocli-codegen = { module = "info.picocli:picocli-codegen", version.ref = "picocli" } -night-config-toml = { group = "com.electronwill.night-config", name = "toml", version = "3.8.3"} - -langchain4j = { module = "dev.langchain4j:langchain4j", version.ref = "langchain4j" } -langchain4j-openai = { module = "dev.langchain4j:langchain4j-open-ai", version.ref = "langchain4j" } +# MCP Java SDK: core plus the Jackson 2 binding rather than the `mcp` aggregate, which binds +# Jackson 3 and would put a second Jackson into the image next to ical4j-serializer's. +mcp-core = { module = "io.modelcontextprotocol.sdk:mcp-core", version.ref = "mcp" } +mcp-json-jackson2 = { module = "io.modelcontextprotocol.sdk:mcp-json-jackson2", version.ref = "mcp" } -spring-ai = { module = "org.springframework.ai:spring-ai-starter-mcp-server", version.ref = "spring-ai" } -spring-boot-web = { module = "org.springframework.boot:spring-boot-starter-web", version.ref = "spring-boot"} +night-config-toml = { group = "com.electronwill.night-config", name = "toml", version = "3.8.3"} groovy = { module = "org.codehaus.groovy:groovy", version.ref = "groovy"} groovy-test = { module = "org.codehaus.groovy:groovy-test", version.ref = "groovy"} -log4j-core = { module = "org.apache.logging.log4j:log4j-core", version.ref = "log4j"} -log4j-slf4j2 = { module = "org.apache.logging.log4j:log4j-slf4j2-impl", version.ref = "log4j"} +slf4j-api = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } +slf4j-simple = { module = "org.slf4j:slf4j-simple", version.ref = "slf4j" } spock-bom = { module = "org.spockframework:spock-bom", version.ref = "spock"} spock-core = { module = "org.spockframework:spock-core", version.ref = "spock"} diff --git a/ical4j-command-agent/build.gradle b/ical4j-command-agent/build.gradle deleted file mode 100644 index c538335..0000000 --- a/ical4j-command-agent/build.gradle +++ /dev/null @@ -1,5 +0,0 @@ -dependencies { - api project(':ical4j-command-core') - - implementation libs.langchain4j, libs.langchain4j.openai -} diff --git a/ical4j-command-agent/src/main/java/org/ical4j/command/agent/CalendarUserAgent.java b/ical4j-command-agent/src/main/java/org/ical4j/command/agent/CalendarUserAgent.java deleted file mode 100644 index 1b042b6..0000000 --- a/ical4j-command-agent/src/main/java/org/ical4j/command/agent/CalendarUserAgent.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.ical4j.command.agent; - -import net.fortuna.ical4j.model.Calendar; - -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -public interface CalendarUserAgent { - - Calendar publish(String prompt) throws Exception; - - Calendar request(String prompt) throws Exception; - - Calendar reply(String prompt) throws Exception; -} diff --git a/ical4j-command-agent/src/main/java/org/ical4j/command/agent/CalendarValidator.java b/ical4j-command-agent/src/main/java/org/ical4j/command/agent/CalendarValidator.java deleted file mode 100644 index c46d80e..0000000 --- a/ical4j-command-agent/src/main/java/org/ical4j/command/agent/CalendarValidator.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.ical4j.command.agent; - -import dev.langchain4j.agent.tool.Tool; -import net.fortuna.ical4j.data.CalendarBuilder; -import net.fortuna.ical4j.data.ParserException; -import net.fortuna.ical4j.validate.ValidationResult; - -import java.io.IOException; -import java.io.StringReader; - -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -public class CalendarValidator { - - /** - * Validate a calendar string. - * @param calendar a calendar string - * @return a validation result, or null if the calendar is valid - */ - @Tool("Validate a calendar string") - public ValidationResult validate(String calendar) throws ParserException, IOException { - return new CalendarBuilder().build(new StringReader(calendar)).validate(); - } -} diff --git a/ical4j-command-agent/src/main/java/org/ical4j/command/agent/EntityBuilder.java b/ical4j-command-agent/src/main/java/org/ical4j/command/agent/EntityBuilder.java deleted file mode 100644 index 69e674e..0000000 --- a/ical4j-command-agent/src/main/java/org/ical4j/command/agent/EntityBuilder.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.ical4j.command.agent; - -import dev.langchain4j.agent.tool.Tool; -import net.fortuna.ical4j.vcard.Entity; -import net.fortuna.ical4j.vcard.property.Email; -import net.fortuna.ical4j.vcard.property.Fn; -import net.fortuna.ical4j.vcard.property.immutable.ImmutableKind; - -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -public class EntityBuilder { - - @Tool - Entity generateIndividual(String name) { - return new Entity().add(ImmutableKind.INDIVIDUAL).add(new Fn(name)); - } - - @Tool - Entity addEmail(Entity entity, String email) { - return entity.add(new Email(email)); - } -} diff --git a/ical4j-command-agent/src/main/java/org/ical4j/command/agent/EventGenerator.java b/ical4j-command-agent/src/main/java/org/ical4j/command/agent/EventGenerator.java deleted file mode 100644 index c8881ee..0000000 --- a/ical4j-command-agent/src/main/java/org/ical4j/command/agent/EventGenerator.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.ical4j.command.agent; - -import dev.langchain4j.agent.tool.Tool; -import net.fortuna.ical4j.extensions.strategy.event.Appointment; -import net.fortuna.ical4j.extensions.strategy.event.Meeting; -import net.fortuna.ical4j.model.component.VEvent; - -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -public class EventGenerator { - - @Tool - VEvent generateEvent(String prompt) { - // Implementation to generate an event based on the prompt - return null; // Placeholder return - } - - @Tool - VEvent generateMeeting(String prompt) { - // Implementation to generate a meeting based on the prompt - return new Meeting().get(); // Placeholder return - } - - @Tool - VEvent generateAppointment(String prompt) { - // Implementation to generate an appointment based on the prompt - return new Appointment().get(); // Placeholder return - } -} diff --git a/ical4j-command-agent/src/test/groovy/org/ical4j/command/agent/CalendarValidatorTest.groovy b/ical4j-command-agent/src/test/groovy/org/ical4j/command/agent/CalendarValidatorTest.groovy deleted file mode 100644 index 0cb39b4..0000000 --- a/ical4j-command-agent/src/test/groovy/org/ical4j/command/agent/CalendarValidatorTest.groovy +++ /dev/null @@ -1,38 +0,0 @@ -package org.ical4j.command.agent - -import spock.lang.Specification - -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -class CalendarValidatorTest extends Specification { -} diff --git a/ical4j-command-cli/build.gradle b/ical4j-command-cli/build.gradle deleted file mode 100644 index f69c3c7..0000000 --- a/ical4j-command-cli/build.gradle +++ /dev/null @@ -1,34 +0,0 @@ -apply plugin: 'application' - -dependencies { - api project(':ical4j-command-core') - - implementation libs.picocli, libs.night.config.toml - - implementation libs.log4j.core, libs.log4j.slf4j2 - - implementation(libs.ical4j) { - capabilities { - requireCapability("org.mnode.ical4j:ical4j-filter-expressions") - } - } -} - -jar { - manifest { - attributes( - 'Implementation-Title': 'iCal4j CLI', - 'Implementation-Version': version, - 'Implementation-Vendor': 'Ben Fortuna' - ) - } -} - -application { - mainClass = 'org.ical4j.command.CommandMain' -} - -startScripts { - applicationName = 'ict' - classpath = files('lib/*') -} diff --git a/ical4j-command-cli/src/main/java/module-info.java b/ical4j-command-cli/src/main/java/module-info.java deleted file mode 100644 index 43734aa..0000000 --- a/ical4j-command-cli/src/main/java/module-info.java +++ /dev/null @@ -1,36 +0,0 @@ -module ical4j.command { - requires java.base; - requires ical4j.command.core; - requires ical4j.core; - requires ical4j.vcard; - requires ical4j.connector.api; - - requires info.picocli; - requires ical4j.integration.api; - requires com.fasterxml.jackson.databind; - requires com.fasterxml.jackson.dataformat.xml; - requires ical4j.serializer; - requires org.slf4j; - requires org.apache.logging.log4j.core; - requires ical4j.extensions; - requires java.desktop; - requires com.electronwill.nightconfig.core; - - exports org.ical4j.command; - exports org.ical4j.command.calendar; - exports org.ical4j.command.channel; - exports org.ical4j.command.collection; - exports org.ical4j.command.card; - - opens org.ical4j.command to info.picocli; - opens org.ical4j.command.calendar to info.picocli; - opens org.ical4j.command.channel to info.picocli; - opens org.ical4j.command.collection to info.picocli; - opens org.ical4j.command.card to info.picocli; - exports org.ical4j.command.workspace; - opens org.ical4j.command.workspace to info.picocli; - exports org.ical4j.command.config; - opens org.ical4j.command.config to info.picocli; - exports org.ical4j.command.strategy; - opens org.ical4j.command.strategy to info.picocli; -} \ No newline at end of file diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/CommandMain.java b/ical4j-command-cli/src/main/java/org/ical4j/command/CommandMain.java deleted file mode 100644 index 850f88a..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/CommandMain.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.ical4j.command; - -import org.ical4j.command.collection.AddCollection; -import org.ical4j.command.collection.RemoveCollection; -import org.ical4j.command.config.ConfigureCommand; -import org.ical4j.command.metadata.AddCommandGroup; -import org.ical4j.command.metadata.GetProperty; -import org.ical4j.command.metadata.UnsetProperty; -import org.ical4j.command.metadata.SetCommandGroup; -import org.ical4j.command.revisions.ListRevisions; -import org.ical4j.command.revisions.RevertRevision; -import org.ical4j.command.revisions.UndoRevisions; -import org.ical4j.command.strategy.StrategyCommandGroup; -import org.ical4j.command.strategy.StrategyInfo; -import org.ical4j.command.workspace.ActivateWorkspace; -import org.ical4j.command.workspace.ListWorkspaces; -import org.ical4j.command.workspace.PrintWorkspace; -import picocli.CommandLine; - -@CommandLine.Command(name = "ict", description = "@|bold,fg(104) iCal4j Command-line Tool|@", - subcommands = { - // Collection commands - AddCollection.class, RemoveCollection.class, - // Common commands - ListCommand.class, CopyCommand.class, MoveCommand.class, DeleteCommand.class, EditCommand.class, PrintCommand.class, - // Strategy commands - StrategyCommandGroup.class, StrategyInfo.class, - // Metadata commands - AddCommandGroup.class, GetProperty.class, SetCommandGroup.class, UnsetProperty.class, - // Import/export commands - ImportCalendars.class, ExportCommand.class, - // Workspace commands - ListWorkspaces.class, ActivateWorkspace.class, PrintWorkspace.class, - // Revision commands - ListRevisions.class, RevertRevision.class, UndoRevisions.class, - // Utility commands - ValidatorCommand.class, FilterCommand.class, ConverterCommand.class, - ConfigureCommand.class}, - scope = CommandLine.ScopeType.INHERIT, mixinStandardHelpOptions = true, versionProvider = VersionProvider.class, - commandListHeading = "%n@|bold,fg(104) Common commands:|@%n", - footer = "@|yellow Copyright (c) Ben Fortuna |@", showAtFileInUsageHelp = true) -public class CommandMain extends GlobalOptions { - - public static void main(String[] args) { - int exitCode = new CommandLine(new CommandMain()).execute(args); - System.exit(exitCode); - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/DefaultOutputHandlers.java b/ical4j-command-cli/src/main/java/org/ical4j/command/DefaultOutputHandlers.java deleted file mode 100644 index 51770bb..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/DefaultOutputHandlers.java +++ /dev/null @@ -1,139 +0,0 @@ -package org.ical4j.command; - -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.PropertyName; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; -import net.fortuna.ical4j.data.CalendarOutputter; -import net.fortuna.ical4j.model.Calendar; -import net.fortuna.ical4j.validate.ValidationReport; -import net.fortuna.ical4j.validate.ValidationResult; -import net.fortuna.ical4j.vcard.VCard; -import org.mnode.ical4j.serializer.JCalSerializer; -import org.mnode.ical4j.serializer.XCalSerializer; - -import java.io.IOException; -import java.io.Writer; -import java.util.Collection; -import java.util.List; -import java.util.function.Consumer; - -/** - * Default command consumer implementations. - */ -public interface DefaultOutputHandlers { - - /** - * Writes command result to stdout. - * @return a consumer instance - * @param command result type - */ - static Consumer STDOUT_PRINTER() { - return System.out::println; - } - - /** - * Write command result to the specified writer after validation. - * @param out a writer use to output the result after validation - * @return a consumer instance - */ - static Consumer VALIDATING_CALENDAR_PRINTER(Writer out) { - return calendar -> { - try { - new CalendarOutputter(true).output(calendar, out); - } catch (IOException e) { - throw new RuntimeException(e); - } - }; - } - - static Consumer VALIDATING_VCARD_PRINTER(Writer out) { - return card -> { - try { - out.write(card.toString()); - out.flush(); - } catch (IOException e) { - throw new RuntimeException(e); - } - }; - } - - /** - * Write command result as text to the specified writer. - * @param out a writer use to output the result - * @return a consumer instance - */ - static Consumer STDOUT_REPORT_PRINTER(Writer out) { - return validationResult -> { - try { - new ValidationReport(ValidationReport.Format.TEXT).output(validationResult, out); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - try { - out.flush(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - }; - } - - /** - * Writes command result to stdout. - * @return a consumer instance - * @param command result type - */ - static > Consumer STDOUT_LIST_PRINTER() { - List ignoredFiles = List.of(".DS_Store"); - return (T objects) -> objects.stream().filter(o -> !ignoredFiles.contains(o)) - .forEach(System.out::println); - } - - /** - * Writes command result to stdout as JSON. - * @return a consumer instance - * @param command result type - */ - static Consumer STDOUT_JCAL_PRINTER() { - return (t) -> { - SimpleModule module = new SimpleModule(); - module.addSerializer(Calendar.class, new JCalSerializer(null)); - - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(module); - - try { - mapper.writeValue(System.out, t); - } catch (IOException e) { - throw new RuntimeException(e); - } - }; - } - - /** - * Writes command result to stdout as XML. - * @return a consumer instance - * @param command result type - */ - static Consumer STDOUT_XCAL_PRINTER() { - return (t) -> { - SimpleModule module = new SimpleModule(); - module.addSerializer(Calendar.class, new XCalSerializer(null)); - - XmlMapper mapper = XmlMapper.builder().defaultUseWrapper(true).build(); - mapper.setConfig(mapper.getSerializationConfig().withRootName( - PropertyName.construct("icalendar", "urn:ietf:params:xml:ns:icalendar-2.0")) - .with(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME)); - - mapper.registerModule(module); - - try { - mapper.writeValue(System.out, t); - } catch (IOException e) { - throw new RuntimeException(e); - } - }; - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/GlobalOptions.java b/ical4j-command-cli/src/main/java/org/ical4j/command/GlobalOptions.java deleted file mode 100644 index 3dfc104..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/GlobalOptions.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.ical4j.command; - -import net.fortuna.ical4j.util.CompatibilityHints; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.core.config.Configurator; -import picocli.CommandLine; - -import static org.apache.logging.log4j.Level.*; - -public class GlobalOptions { - - @CommandLine.Option(names = "-lenient", description = "Enable lenient parsing", scope = CommandLine.ScopeType.INHERIT) - public void setRelaxedParsing(boolean relaxedParsing) { - CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); - CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true); - } - - @CommandLine.Option(names = {"-v", "--verbose"}, scope = CommandLine.ScopeType.INHERIT, - description = "Increase logging verbosity") - public void setVerbose(boolean[] verbose) { - Configurator.setAllLevels(LogManager.getRootLogger().getName(), - verbose.length > 2 ? TRACE : verbose.length > 1 ? DEBUG : INFO); - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/ListCommand.java b/ical4j-command-cli/src/main/java/org/ical4j/command/ListCommand.java deleted file mode 100644 index 5ce1d6b..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/ListCommand.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.ical4j.command; - -import net.fortuna.ical4j.filter.ComponentFilter; -import net.fortuna.ical4j.filter.FilterExpressionParser; -import net.fortuna.ical4j.model.Calendar; -import net.fortuna.ical4j.model.component.CalendarComponent; -import org.ical4j.command.config.CommandConfig; -import org.ical4j.connector.CalendarCollection; -import org.ical4j.connector.CardCollection; -import org.ical4j.connector.ObjectNotFoundException; -import org.ical4j.connector.ObjectStoreException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Predicate; - -@CommandLine.Command(name = "list", aliases = {"ls"}, description = "List objects in a collection") -public class ListCommand extends AbstractCommand> { - - private static final Logger LOGGER = LoggerFactory.getLogger(ListCommand.class); - - @CommandLine.Parameters(index = "0", description = "List context specification", arity = "0..1", split = ":") - private String[] spec; - - @CommandLine.Option(names = "--filter", description = "Filter expression") - private String filter; - - private final CommandConfig config; - - public ListCommand() { - super(DefaultOutputHandlers.STDOUT_LIST_PRINTER()); - config = CommandConfig.INSTANCE; - } - - public ListCommand(Consumer> outputHandler) { - this(outputHandler, CommandConfig.INSTANCE); - } - - public ListCommand(Consumer> outputHandler, CommandConfig config) { - super(outputHandler); - this.config = config; - } - - @Override - public Integer call() { - try { - List result = new ArrayList<>(); - if (spec == null) { - List calendarCollections = config.getCalendarStore() - .getCollections(config.getActiveWorkspace()); - List cardCollections = config.getCardStore() - .getCollections(config.getActiveWorkspace()); - Set names = new HashSet<>(); - for (CalendarCollection collection : calendarCollections) { - names.add(collection.getDisplayName()); - } - for (CardCollection collection : cardCollections) { - names.add(collection.getDisplayName()); - } - result.addAll(names); - } else { - List calendars = config.getCalendarStore().getCollection(spec[0], - config.getActiveWorkspace()).getAll(); - - List components; - if (spec.length > 1) { - String uid = spec[1]; - components = calendars.stream().filter( - c -> c.getUid() != null && c.getUid().getValue().equals(uid)).findFirst().get().getComponents(); - components.forEach(c -> result.add(printComponent(c))); - } else { - if (filter != null) { - Predicate filterPredicate = new ComponentFilter<>().predicate( - new FilterExpressionParser().parse(filter)); - calendars = calendars.stream().filter( - c -> c.getComponents().stream().anyMatch(filterPredicate)).toList(); - } - for (Calendar calendar : calendars) { - result.add(printCalendar(calendar)); - } - } - } - getOutputHandler().accept(result); - } catch (ObjectStoreException | ObjectNotFoundException e) { - LOGGER.error("Unexpected error", e); - return 1; - } - return 0; - } - - private String printCalendar(Calendar calendar) { - StringBuilder sb = new StringBuilder(); - sb.append(calendar.getUid().getValue()); - sb.append(" | "); - sb.append(calendar.getComponents().get(0).getRequiredProperty("SUMMARY").getValue()); - sb.append(" | "); - sb.append(calendar.getComponents().get(0).getRequiredProperty("DTSTART").getValue()); - return sb.toString(); - } - - private String printComponent(CalendarComponent component) { - StringBuilder sb = new StringBuilder(); - sb.append(component.getUid().get().getValue()); - sb.append(" | "); - sb.append(component.getProperty("SUMMARY")); - sb.append(" | "); - sb.append(component.getProperty("DTSTART") ); - return sb.toString(); - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/VersionProvider.java b/ical4j-command-cli/src/main/java/org/ical4j/command/VersionProvider.java deleted file mode 100644 index 7e3581b..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/VersionProvider.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.ical4j.command; - -import net.fortuna.ical4j.model.Calendar; -import picocli.CommandLine; - -public class VersionProvider implements CommandLine.IVersionProvider { - - private final String commandVersion; - - private final String ical4jVersion; - - private final String javaVersion; - - public VersionProvider() { - commandVersion = getClass().getPackage().getImplementationVersion(); - ical4jVersion = Calendar.class.getPackage().getImplementationVersion(); - javaVersion = System.getProperty("java.version"); - } - - @Override - public String[] getVersion() { - return new String[] {String.format("iCal4j Command-line Tool %s (ical4j=%s, java=%s)", - commandVersion, ical4jVersion, javaVersion) - }; - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/DeleteCalendar.java b/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/DeleteCalendar.java deleted file mode 100644 index 61bfd90..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/DeleteCalendar.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.ical4j.command.calendar; - -import net.fortuna.ical4j.model.Calendar; -import org.ical4j.command.collection.AbstractCollectionCommand; -import org.ical4j.connector.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; - -import java.util.function.Consumer; - -import static org.ical4j.connector.ObjectCollection.DEFAULT_COLLECTION; - -@CommandLine.Command(name = "remove-calendar", description = "Remove an existing calendar") -public class DeleteCalendar extends AbstractCollectionCommand { - - private static final Logger LOGGER = LoggerFactory.getLogger(DeleteCalendar.class); - - @CommandLine.Option(names = {"-uid"}) - private String calendarUid; - - public DeleteCalendar() { - super(); - } - - public DeleteCalendar(String collectionName, Consumer consumer) { - super(collectionName, consumer); - } - - public DeleteCalendar(ObjectStore store) { - super(DEFAULT_COLLECTION, store); - } - - public DeleteCalendar(String collectionName, ObjectStore store) { - super(collectionName, store); - } - - public DeleteCalendar withCalendarUid(String calendarUid) { - this.calendarUid = calendarUid; - return this; - } - - @Override - public Integer call() { - try { - getOutputHandler().accept(getCollection().removeCalendar(calendarUid)); - } catch (ObjectStoreException | FailedOperationException | ObjectNotFoundException e) { - LOGGER.error("Unexpected error", e); - return 1; - } - return 0; - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/GetCalendar.java b/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/GetCalendar.java deleted file mode 100644 index fa0b5df..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/GetCalendar.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.ical4j.command.calendar; - -import net.fortuna.ical4j.model.Calendar; -import org.ical4j.command.collection.AbstractCollectionCommand; -import org.ical4j.connector.CalendarCollection; -import org.ical4j.connector.ObjectNotFoundException; -import org.ical4j.connector.ObjectStore; -import org.ical4j.connector.ObjectStoreException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; - -import java.util.function.Consumer; - -@CommandLine.Command(name = "export-calendar", description = "Export a calendar from a collection") -public class GetCalendar extends AbstractCollectionCommand { - - private static final Logger LOGGER = LoggerFactory.getLogger(GetCalendar.class); - - @CommandLine.Option(names = {"-uid"}) - private String calendarUid; - - public GetCalendar() { - super(); - } - - public GetCalendar(String collectionName, Consumer consumer) { - super(collectionName, consumer); - } - - public GetCalendar(String collectionName, Consumer consumer, ObjectStore store) { - super(collectionName, consumer, store); - } - - public GetCalendar withCalendarUid(String calendarUid) { - this.calendarUid = calendarUid; - return this; - } - - @Override - public Integer call() { - try { - getOutputHandler().accept(getCollection().getCalendar(calendarUid)); - } catch (ObjectNotFoundException | ObjectStoreException e) { - LOGGER.error("Unexpected error", e); - return 1; - } - return 0; - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/UpdateCalendar.java b/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/UpdateCalendar.java deleted file mode 100644 index 67eb9b4..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/UpdateCalendar.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.ical4j.command.calendar; - -import net.fortuna.ical4j.data.ParserException; -import net.fortuna.ical4j.model.Calendar; -import net.fortuna.ical4j.model.property.Uid; -import org.ical4j.command.InputOptions; -import org.ical4j.command.collection.AbstractCollectionCommand; -import org.ical4j.connector.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; - -import java.io.IOException; -import java.util.function.Consumer; - -import static org.ical4j.connector.ObjectCollection.DEFAULT_COLLECTION; - -@CommandLine.Command(name = "import-calendar", description = "Import a calendar into a collection") -public class UpdateCalendar extends AbstractCollectionCommand { - - private static final Logger LOGGER = LoggerFactory.getLogger(UpdateCalendar.class); - - @CommandLine.ArgGroup(multiplicity = "1") - protected InputOptions input; - - private Calendar calendar; - - public UpdateCalendar() { - super(); - } - - public UpdateCalendar(String collectionName, Consumer consumer) { - super(collectionName, consumer); - } - - public UpdateCalendar(ObjectStore store) { - super(DEFAULT_COLLECTION, store); - } - - public UpdateCalendar(String collectionName, ObjectStore store) { - super(collectionName, store); - } - - public UpdateCalendar withCalendar(Calendar calendar) { - this.calendar = calendar; - return this; - } - - public Calendar getCalendar() throws ParserException, IOException, ObjectStoreException, ObjectNotFoundException { - if (calendar == null) { - calendar = input.toCalendar(); - } - return calendar; - } - - @Override - public Integer call() { - try { - getCollection().merge(getCalendar()); - } catch (ObjectStoreException | FailedOperationException | ObjectNotFoundException | ParserException | - IOException e) { - LOGGER.error("Unexpected error", e); - return 1; - } - return 0; - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/card/DeleteCard.java b/ical4j-command-cli/src/main/java/org/ical4j/command/card/DeleteCard.java deleted file mode 100644 index eb0fc4d..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/card/DeleteCard.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.ical4j.command.card; - -import net.fortuna.ical4j.vcard.VCard; -import org.ical4j.command.collection.AbstractCollectionCommand; -import org.ical4j.connector.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; - -import java.util.function.Consumer; - -@CommandLine.Command(name = "remove-card", description = "Remove an existing card") -public class DeleteCard extends AbstractCollectionCommand { - - private static final Logger LOGGER = LoggerFactory.getLogger(DeleteCard.class); - - @CommandLine.Option(names = {"-uid"}) - private String cardUid; - - public DeleteCard() { - super(); - } - - public DeleteCard(String collectionName, Consumer consumer) { - super(collectionName, consumer); - } - - public DeleteCard(String collectionName, Consumer consumer, ObjectStore store) { - super(collectionName, consumer, store); - } - - public DeleteCard withCardUid(String cardUid) { - this.cardUid = cardUid; - return this; - } - - @Override - public Integer call() { - try { - getOutputHandler().accept(getCollection().removeCard(cardUid)); - } catch (FailedOperationException | ObjectNotFoundException | ObjectStoreException e) { - LOGGER.error("Unexpected error", e); - return 1; - } - return 0; - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/card/GetCard.java b/ical4j-command-cli/src/main/java/org/ical4j/command/card/GetCard.java deleted file mode 100644 index 08923a5..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/card/GetCard.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.ical4j.command.card; - -import net.fortuna.ical4j.vcard.VCard; -import org.ical4j.command.collection.AbstractCollectionCommand; -import org.ical4j.connector.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; - -import java.util.function.Consumer; - -@CommandLine.Command(name = "export-card", description = "Export a card from a collection") -public class GetCard extends AbstractCollectionCommand { - - private static final Logger LOGGER = LoggerFactory.getLogger(GetCard.class); - - @CommandLine.Option(names = {"-uid"}) - private String cardUid; - - public GetCard() { - super(); - } - - public GetCard(String collectionName, Consumer consumer) { - super(collectionName, consumer); - } - - public GetCard(String collectionName, Consumer consumer, ObjectStore store) { - super(collectionName, consumer, store); - } - - public GetCard withCardUid(String cardUid) { - this.cardUid = cardUid; - return this; - } - - @Override - public Integer call() { - try { - getOutputHandler().accept(getCollection().getCard(cardUid)); - } catch (FailedOperationException | ObjectNotFoundException | ObjectStoreException e) { - LOGGER.error("Unexpected error", e); - return 1; - } - return 0; - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/card/UpdateCard.java b/ical4j-command-cli/src/main/java/org/ical4j/command/card/UpdateCard.java deleted file mode 100644 index 34e6d21..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/card/UpdateCard.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.ical4j.command.card; - -import net.fortuna.ical4j.data.ParserException; -import net.fortuna.ical4j.model.ConstraintViolationException; -import net.fortuna.ical4j.vcard.VCard; -import net.fortuna.ical4j.vcard.property.Uid; -import org.ical4j.command.InputOptions; -import org.ical4j.command.collection.AbstractCollectionCommand; -import org.ical4j.connector.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; - -import java.io.IOException; -import java.util.function.Consumer; - -@CommandLine.Command(name = "import-card", description = "Import a card into a collection") -public class UpdateCard extends AbstractCollectionCommand { - - private static final Logger LOGGER = LoggerFactory.getLogger(UpdateCard.class); - - @CommandLine.ArgGroup(multiplicity = "1") - protected InputOptions input; - - private VCard card; - - public UpdateCard() { - super(); - } - - public UpdateCard(String collectionName, Consumer consumer) { - super(collectionName, consumer); - } - - public UpdateCard(String collectionName, ObjectStore store) { - super(collectionName, store); - } - - public UpdateCard withCard(VCard card) { - this.card = card; - return this; - } - - public VCard getCard() throws ParserException, IOException, ObjectStoreException, ObjectNotFoundException { - if (card == null) { - card = input.toVCard(); - } - return card; - } - - @Override - public Integer call() { - try { - getOutputHandler().accept(getCollection().merge(getCard())); - } catch (ObjectStoreException | ConstraintViolationException | ObjectNotFoundException | IOException | - ParserException | FailedOperationException e) { - LOGGER.error("Unexpected error", e); - return 1; - } - return 0; - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/AddCollection.java b/ical4j-command-cli/src/main/java/org/ical4j/command/collection/AddCollection.java deleted file mode 100644 index 604109b..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/AddCollection.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.ical4j.command.collection; - -import org.ical4j.command.config.CommandConfig; -import org.ical4j.command.workspace.AbstractWorkspaceCommand; -import org.ical4j.connector.ObjectCollection; -import org.ical4j.connector.ObjectNotFoundException; -import org.ical4j.connector.ObjectStore; -import org.ical4j.connector.ObjectStoreException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; - -import java.util.function.Consumer; - -/** - * A command to create a new collection for a specified object store. - */ -@CommandLine.Command(name = "mkcol", description = "Add a new collection") -public class AddCollection extends AbstractWorkspaceCommand, String> { - - public enum CollectionType { - CALENDAR, - CARD - } - - private static final Logger LOGGER = LoggerFactory.getLogger(AddCollection.class); - - @CommandLine.Parameters(index = "0", description = "Name of the collection to create") - private String collectionName; - - @CommandLine.Option(names = "--type", - description = "Valid values: ${COMPLETION-CANDIDATES}", defaultValue = "CALENDAR") - private CollectionType collectionType; - - public AddCollection() { - } - - public AddCollection(Consumer outputHandler, ObjectStore> store) { - super(outputHandler); - setStore(store); - } - - public AddCollection withCollectionName(String collectionName) { - this.collectionName = collectionName; - return this; - } - - @Override - public Integer call() { - try { - // Injected store: add directly to the supplied store. - if (getStore() != null) { - getStore().addCollection(collectionName); - getOutputHandler().accept("Collection '" + collectionName + "' created successfully"); - return 0; - } - - // CLI path: resolve the appropriate store from configuration by type. - ObjectCollection collection = null; - if (collectionType == CollectionType.CALENDAR) { - try { - CommandConfig.INSTANCE.getCalendarStore().getCollection(collectionName, - CommandConfig.INSTANCE.getActiveWorkspace()); - getOutputHandler().accept("Collection with name '" + collectionName + "' already exists"); - return 1; - } catch (ObjectNotFoundException e) { - } - collection = CommandConfig.INSTANCE.getCalendarStore().addCollection(collectionName, - CommandConfig.INSTANCE.getActiveWorkspace()); - } else if (collectionType == CollectionType.CARD) { - try { - CommandConfig.INSTANCE.getCardStore().getCollection(collectionName, - CommandConfig.INSTANCE.getActiveWorkspace()); - getOutputHandler().accept("Collection with name '" + collectionName + "' already exists"); - return 1; - } catch (ObjectNotFoundException e) { - } - collection = CommandConfig.INSTANCE.getCardStore().addCollection(collectionName, - CommandConfig.INSTANCE.getActiveWorkspace()); - } - if (collection != null) { - getOutputHandler().accept("Collection '" + collectionName + "' created successfully"); - } - } catch (ObjectStoreException e) { - LOGGER.error("Unexpected error", e); - return 1; - } - return 0; - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/GetCollectionDetails.java b/ical4j-command-cli/src/main/java/org/ical4j/command/collection/GetCollectionDetails.java deleted file mode 100644 index b66f36f..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/GetCollectionDetails.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.ical4j.command.collection; - -import org.ical4j.command.workspace.AbstractWorkspaceCommand; -import org.ical4j.connector.ObjectCollection; -import org.ical4j.connector.ObjectNotFoundException; -import org.ical4j.connector.ObjectStore; -import org.ical4j.connector.ObjectStoreException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; - -import java.util.function.Consumer; - -@CommandLine.Command(name = "get-collection-details", description = "Retrieve a collection") -public class GetCollectionDetails extends AbstractWorkspaceCommand, ObjectCollection> { - - private static final Logger LOGGER = LoggerFactory.getLogger(GetCollectionDetails.class); - - @CommandLine.Option(names = {"-name"}) - private String collectionName; - - public GetCollectionDetails() { - } - - public GetCollectionDetails(Consumer> consumer) { - super(consumer); - } - - public GetCollectionDetails(Consumer> consumer, ObjectStore> store) { - super(consumer); - setStore(store); - } - - public GetCollectionDetails withCollectionName(String collectionName) { - this.collectionName = collectionName; - return this; - } - - @Override - public Integer call() { - try { - getOutputHandler().accept(getStore().getCollection(collectionName)); - } catch (ObjectStoreException | ObjectNotFoundException e) { - LOGGER.error("Unexpected error", e); - return 1; - } - return 0; - } -} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/RemoveCollection.java b/ical4j-command-cli/src/main/java/org/ical4j/command/collection/RemoveCollection.java deleted file mode 100644 index fdb5298..0000000 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/RemoveCollection.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.ical4j.command.collection; - -import org.ical4j.command.config.CommandConfig; -import org.ical4j.command.workspace.AbstractWorkspaceCommand; -import org.ical4j.connector.ObjectCollection; -import org.ical4j.connector.ObjectNotFoundException; -import org.ical4j.connector.ObjectStore; -import org.ical4j.connector.ObjectStoreException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import picocli.CommandLine; - -import java.util.function.Consumer; - -/** - * A command to delete an existing collection from an object store. - */ -@CommandLine.Command(name = "rmcol", description = "Purge a collection") -public class RemoveCollection extends AbstractWorkspaceCommand, String> { - - private static final Logger LOGGER = LoggerFactory.getLogger(RemoveCollection.class); - - @CommandLine.Parameters(index = "0", description = "Name of the collection to remove") - private String collectionName; - - @CommandLine.Option(names = "--type", - description = "Valid values: ${COMPLETION-CANDIDATES}", defaultValue = "CALENDAR") - private AddCollection.CollectionType collectionType; - - public RemoveCollection() { - } - - public RemoveCollection(Consumer outputHandler, ObjectStore> store) { - super(outputHandler); - setStore(store); - } - - public RemoveCollection withCollectionName(String collectionName) { - this.collectionName = collectionName; - return this; - } - - @Override - public Integer call() { - try { - // Injected store: remove directly from the supplied store. - if (getStore() != null) { - ObjectCollection collection = getStore().getCollection(collectionName); - collection.delete(); - getOutputHandler().accept("Collection '" + collectionName + "' deleted"); - return 0; - } - - // CLI path: resolve the appropriate store from configuration by type. - ObjectCollection collection; - if (collectionType == AddCollection.CollectionType.CARD) { - collection = CommandConfig.INSTANCE.getCardStore().getCollection(collectionName, - CommandConfig.INSTANCE.getActiveWorkspace()); - } else { - collection = CommandConfig.INSTANCE.getCalendarStore().getCollection(collectionName, - CommandConfig.INSTANCE.getActiveWorkspace()); - } - collection.delete(); - getOutputHandler().accept("Collection '" + collectionName + "' deleted"); - } catch (ObjectStoreException | ObjectNotFoundException e) { - LOGGER.error("Unexpected error", e); - return 1; - } - return 0; - } -} diff --git a/ical4j-command-cli/src/main/resources/config.default.toml b/ical4j-command-cli/src/main/resources/config.default.toml deleted file mode 100644 index 534b8e7..0000000 --- a/ical4j-command-cli/src/main/resources/config.default.toml +++ /dev/null @@ -1,10 +0,0 @@ -[user] - agent = "ical4j-command-tool/1.0" - -[workpace] - active = "default" - -[contentType] - default = "text/plain" - -[filters] \ No newline at end of file diff --git a/ical4j-command-cli/src/main/resources/log4j2.properties b/ical4j-command-cli/src/main/resources/log4j2.properties deleted file mode 100644 index b64523c..0000000 --- a/ical4j-command-cli/src/main/resources/log4j2.properties +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2024 Ben Fortuna -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# - -## set root logging preferences.. -rootLogger=warn, stderr -#log4j.logger.net.fortuna.ical4j=warn, stderr - -## appender: stderr.. -appender.stderr.name=stderr -appender.stderr.type=Console -appender.stderr.target=System.err -appender.stderr.layout.type=PatternLayout -appender.stderr.layout.pattern=%d | %-5p [%t] %c{1} - %m%n diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/DefaultOutputHandlersTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/DefaultOutputHandlersTest.groovy deleted file mode 100644 index 3e25174..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/DefaultOutputHandlersTest.groovy +++ /dev/null @@ -1,20 +0,0 @@ -package org.ical4j.command - -import net.fortuna.ical4j.validate.ValidationEntry -import net.fortuna.ical4j.validate.ValidationResult -import spock.lang.Specification - -class DefaultOutputHandlersTest extends Specification { - - def 'test stdout report handler'() { - given: 'a validation result' - ValidationResult result = [new ValidationEntry('message', ValidationEntry.Severity.WARNING, 'context')] - - when: 'stdout report handler is called' - StringWriter writer = [] - DefaultOutputHandlers.STDOUT_REPORT_PRINTER(writer).accept(result) - - then: 'result is rendered correctly' - writer as String == '- WARNING: context - message\n' - } -} diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/ListCommandTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/ListCommandTest.groovy deleted file mode 100644 index fb8364c..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/ListCommandTest.groovy +++ /dev/null @@ -1,73 +0,0 @@ -package org.ical4j.command - -import org.ical4j.command.config.CommandConfig -import org.ical4j.connector.CalendarCollection -import org.ical4j.connector.CardCollection -import org.ical4j.connector.ObjectStore -import spock.lang.Specification - -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -class ListCommandTest extends Specification { - - def 'test list command lists collection names from the active workspace'() { - given: 'mock calendar and card stores' - ObjectStore calendarStore = Mock() - ObjectStore cardStore = Mock() - CalendarCollection calendarCollection = Mock() - CardCollection cardCollection = Mock() - - calendarStore.getCollections('default') >> [calendarCollection] - cardStore.getCollections('default') >> [cardCollection] - calendarCollection.getDisplayName() >> 'My Calendar' - cardCollection.getDisplayName() >> 'My Contacts' - - and: 'a config exposing those stores for the active workspace' - CommandConfig config = new CommandConfig(null) { - @Override String getActiveWorkspace() { 'default' } - @Override ObjectStore getCalendarStore() { calendarStore } - @Override ObjectStore getCardStore() { cardStore } - } - - and: 'a list command capturing its output' - def output - def command = new ListCommand((o) -> output = o, config) - - when: 'the command is executed' - def result = command.call() - - then: 'it succeeds and reports both collection names' - result == 0 - output as Set == ['My Calendar', 'My Contacts'] as Set - } -} diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/DeleteCalendarTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/DeleteCalendarTest.groovy deleted file mode 100644 index a82a4e4..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/DeleteCalendarTest.groovy +++ /dev/null @@ -1,22 +0,0 @@ -package org.ical4j.command.calendar - - -import org.ical4j.connector.CalendarCollection -import org.ical4j.connector.ObjectStore -import spock.lang.Specification - -class DeleteCalendarTest extends Specification { - - def 'test delete calendar'() { - given: 'a mock calendar collection' - ObjectStore store = Mock() - CalendarCollection collection = Mock() - store.getCollection(_) >> collection - - when: 'a delete calendar command is run' - new DeleteCalendar('testCollection', store).withCalendarUid('1234').call() - - then: 'collection remove calendar is invoked' - 1 * collection.removeCalendar('1234') - } -} diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/GetCalendarTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/GetCalendarTest.groovy deleted file mode 100644 index 28b514a..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/GetCalendarTest.groovy +++ /dev/null @@ -1,22 +0,0 @@ -package org.ical4j.command.calendar - - -import org.ical4j.connector.CalendarCollection -import org.ical4j.connector.ObjectStore -import spock.lang.Specification - -class GetCalendarTest extends Specification { - - def 'test get calendar'() { - given: 'a mock calendar collection' - ObjectStore store = Mock() - CalendarCollection collection = Mock() - - when: 'a get calendar command is run' - new GetCalendar('default', (calendar) -> {}, store).withCalendarUid('1234').call() - - then: 'collection get calendar is invoked' - 1 * store.getCollection('default') >> collection - 1 * collection.getCalendar('1234') - } -} diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/UpdateCalendarTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/UpdateCalendarTest.groovy deleted file mode 100644 index b1c6622..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/UpdateCalendarTest.groovy +++ /dev/null @@ -1,25 +0,0 @@ -package org.ical4j.command.calendar - -import net.fortuna.ical4j.model.Calendar -import org.ical4j.connector.CalendarCollection -import org.ical4j.connector.ObjectStore -import spock.lang.Specification - -class UpdateCalendarTest extends Specification { - - def 'test update calendar'() { - given: 'a mock calendar collection' - ObjectStore store = Mock() - CalendarCollection collection = Mock() - store.getCollection(_) >> collection - - and: 'a calendar instance' - Calendar calendar = [] - - when: 'a update calendar command is run' - new UpdateCalendar('testCollection', store).withCalendar(calendar).call() - - then: 'collection merge is invoked' - 1 * collection.merge(calendar) - } -} diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/card/DeleteCardTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/card/DeleteCardTest.groovy deleted file mode 100644 index a07df30..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/card/DeleteCardTest.groovy +++ /dev/null @@ -1,22 +0,0 @@ -package org.ical4j.command.card - - -import org.ical4j.connector.CardCollection -import org.ical4j.connector.ObjectStore -import spock.lang.Specification - -class DeleteCardTest extends Specification { - - def 'test delete card'() { - given: 'a mock card collection' - ObjectStore store = Mock() - CardCollection collection = Mock() - - when: 'a delete card command is run' - new DeleteCard('default', (card) -> {}, store).withCardUid('1234').call() - - then: 'collection remove card is invoked' - 1 * store.getCollection('default') >> collection - 1 * collection.removeCard('1234') - } -} diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/card/GetCardTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/card/GetCardTest.groovy deleted file mode 100644 index a276808..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/card/GetCardTest.groovy +++ /dev/null @@ -1,22 +0,0 @@ -package org.ical4j.command.card - - -import org.ical4j.connector.CardCollection -import org.ical4j.connector.ObjectStore -import spock.lang.Specification - -class GetCardTest extends Specification { - - def 'test get card'() { - given: 'a mock card collection' - ObjectStore store = Mock() - CardCollection collection = Mock() - - when: 'a get card command is run' - new GetCard('default', (card) -> {}, store).withCardUid('1234').call() - - then: 'collection get card is invoked' - 1 * store.getCollection('default') >> collection - 1 * collection.getCard('1234') - } -} diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/card/UpdateCardTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/card/UpdateCardTest.groovy deleted file mode 100644 index d5e8b47..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/card/UpdateCardTest.groovy +++ /dev/null @@ -1,26 +0,0 @@ -package org.ical4j.command.card - - -import net.fortuna.ical4j.vcard.VCard -import org.ical4j.connector.CardCollection -import org.ical4j.connector.ObjectStore -import spock.lang.Specification - -class UpdateCardTest extends Specification { - - def 'test update card'() { - given: 'a mock card collection' - ObjectStore store = Mock() - CardCollection collection = Mock() - - and: 'a vcard instance' - VCard card = [] - - when: 'an update card command is run' - new UpdateCard('default', store).withCard(card).call() - - then: 'collection merge is invoked' - 1 * store.getCollection('default') >> collection - 1 * collection.merge(card) - } -} diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/collection/AddCollectionTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/collection/AddCollectionTest.groovy deleted file mode 100644 index 7912942..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/collection/AddCollectionTest.groovy +++ /dev/null @@ -1,19 +0,0 @@ -package org.ical4j.command.collection - - -import org.ical4j.connector.ObjectStore -import spock.lang.Specification - -class AddCollectionTest extends Specification { - - def 'test create collection'() { - given: 'a mock card store' - ObjectStore store = Mock() - - when: 'a create collection command is run' - new AddCollection((collection) -> {}, store).withCollectionName('testCollection').call() - - then: 'store add collection is invoked' - 1 * store.addCollection('testCollection') - } -} diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/collection/GetCollectionDetailsTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/collection/GetCollectionDetailsTest.groovy deleted file mode 100644 index d770feb..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/collection/GetCollectionDetailsTest.groovy +++ /dev/null @@ -1,19 +0,0 @@ -package org.ical4j.command.collection - - -import org.ical4j.connector.ObjectStore -import spock.lang.Specification - -class GetCollectionDetailsTest extends Specification { - - def 'test get collection'() { - given: 'a mock card store' - ObjectStore store = Mock() - - when: 'a get collection command is run' - new GetCollectionDetails((collection) -> {}, store).withCollectionName('testCollection').call() - - then: 'store get collection is invoked' - 1 * store.getCollection('testCollection') - } -} diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/collection/RemoveCollectionTest.groovy b/ical4j-command-cli/src/test/groovy/org/ical4j/command/collection/RemoveCollectionTest.groovy deleted file mode 100644 index 96da3c8..0000000 --- a/ical4j-command-cli/src/test/groovy/org/ical4j/command/collection/RemoveCollectionTest.groovy +++ /dev/null @@ -1,22 +0,0 @@ -package org.ical4j.command.collection - - -import org.ical4j.connector.ObjectCollection -import org.ical4j.connector.ObjectStore -import spock.lang.Specification - -class RemoveCollectionTest extends Specification { - - def 'test delete collection'() { - given: 'a mock card store' - ObjectStore store = Mock() - ObjectCollection collection = Mock() - - when: 'a delete collection command is run' - new RemoveCollection((c) -> {}, store).withCollectionName('testCollection').call() - - then: 'store remove collection is invoked' - 1 * store.getCollection('testCollection') >> collection - 1 * collection.delete() - } -} diff --git a/ical4j-command-core/build.gradle b/ical4j-command-core/build.gradle deleted file mode 100644 index 3330fa7..0000000 --- a/ical4j-command-core/build.gradle +++ /dev/null @@ -1,12 +0,0 @@ -// Shared command vocabulary module: vocabulary definitions only, no dispatch/execution. -// Plugins and common dependencies are applied by the root `configure(subprojects)` block. - -jar { - manifest { - attributes( - 'Implementation-Title': 'iCal4j Command Core', - 'Implementation-Version': version, - 'Implementation-Vendor': 'Ben Fortuna' - ) - } -} diff --git a/ical4j-command-core/src/main/java/module-info.java b/ical4j-command-core/src/main/java/module-info.java deleted file mode 100644 index 37d5462..0000000 --- a/ical4j-command-core/src/main/java/module-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Shared command vocabulary (verbs, entity types, loci, serialization families). This - * module contains vocabulary definitions only - no command dispatch or execution logic - - * preserving the "shared names, separate dispatch" model. - */ -module ical4j.command.core { - requires java.base; - - exports org.ical4j.command.core; -} diff --git a/ical4j-command-mcp/build.gradle b/ical4j-command-mcp/build.gradle deleted file mode 100644 index 92dde41..0000000 --- a/ical4j-command-mcp/build.gradle +++ /dev/null @@ -1,17 +0,0 @@ -plugins { - id 'org.springframework.boot' version '3.5.7' -} - -apply plugin: 'application' - -dependencies { - api project(':ical4j-command-core') - api project(':ical4j-command-cli') - - implementation libs.spring.ai, libs.spring.boot.web -} - -application { - mainClass = 'org.ical4j.command.mcp.iCal4jMcpServerMain' - applicationName = 'ical4j-command-mcp-server' -} diff --git a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/CalendarService.java b/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/CalendarService.java deleted file mode 100644 index 6e6ce05..0000000 --- a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/CalendarService.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.ical4j.command.mcp; - -import org.springframework.stereotype.Service; - -@Service -public class CalendarService { -} diff --git a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/ChannelService.java b/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/ChannelService.java deleted file mode 100644 index d1de5b1..0000000 --- a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/ChannelService.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.ical4j.command.mcp; - -import org.springframework.stereotype.Service; - -@Service -public class ChannelService { -} diff --git a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/CollectionService.java b/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/CollectionService.java deleted file mode 100644 index 69b4e24..0000000 --- a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/CollectionService.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.ical4j.command.mcp; - -import org.springframework.ai.tool.annotation.Tool; -import org.springframework.stereotype.Service; - -@Service -public class CollectionService { - - @Tool(description = "List all actions in the collection.") - public String listActions(String collectionName) { - return "List of actions"; - } - - @Tool(description = "List all availability in the collection.") - public String listAvailability(String collectionName) { - return "List of availability"; - } - - @Tool(description = "List all entities in the collection.") - public String listEntities(String collectionName) { - return "List of entities"; - } - - @Tool(description = "List all events in the collection.") - public String listEvents(String collectionName) { - return "List of events"; - } - - @Tool(description = "List all issues in the collection.") - public String listIssues(String collectionName) { - return "List of issues"; - } - - @Tool(description = "List all notes in the collection.") - public String listNotes(String collectionName) { - return "List of notes"; - } - - @Tool(description = "List all observances in the collection.") - public String listObservances(String collectionName) { - return "List of observances"; - } - - @Tool(description = "List all reports in the collection.") - public String listReports(String collectionName) { - return "List of reports"; - } - - @Tool(description = "List all resources in the collection.") - public String listResources(String collectionName) { - return "List of resources"; - } - - public String importCalendar(String name) { - return "Imported calendar: " + name; - } - - public String importCard(String name) { - return "Imported card: " + name; - } - - public String removeCalendar(String name) { - return "Removed calendar: " + name; - } - public String removeCard(String name) { - return "Removed card: " + name; - } - - public String updateCalendar(String name) { - return "Updated calendar: " + name; - } - - public String updateCard(String name) { - return "Updated card: " + name; - } - - public String getCalendar(String name) { - return "Info for calendar: " + name; - } - - public String getCard(String name) { - return "Info for card: " + name; - } -} diff --git a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/EntityService.java b/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/EntityService.java deleted file mode 100644 index e051b18..0000000 --- a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/EntityService.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.ical4j.command.mcp; - -import net.fortuna.ical4j.vcard.Entity; -import net.fortuna.ical4j.vcard.property.Fn; -import net.fortuna.ical4j.vcard.property.immutable.ImmutableKind; -import org.springframework.ai.tool.annotation.Tool; -import org.springframework.stereotype.Service; - -@Service -public class EntityService { - - @Tool(description = "Creates a new vCard individual entity.") - public String newIndividual(String name) { - return new Entity().add(ImmutableKind.INDIVIDUAL).add(new Fn(name)).toString(); - } -} diff --git a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/StoreService.java b/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/StoreService.java deleted file mode 100644 index 7d5c59d..0000000 --- a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/StoreService.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.ical4j.command.mcp; - -import org.springframework.ai.tool.annotation.Tool; -import org.springframework.stereotype.Service; - -@Service -public class StoreService { - - @Tool(description = "List all workspaces in the store") - public String listWorkspaces() { - // Placeholder implementation - return "List of workspaces"; - } - - @Tool(description = "Add a workspace to the store") - public String addWorkspace(String id) { - // Placeholder implementation - return "Workspace added"; - } - - @Tool(description = "Remove a workspace from the store") - public String removeWorkspace(String id) { - // Placeholder implementation - return "Workspace removed"; - } -} diff --git a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/WorkspaceService.java b/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/WorkspaceService.java deleted file mode 100644 index 1df18c4..0000000 --- a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/WorkspaceService.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.ical4j.command.mcp; - -import org.springframework.ai.tool.annotation.Tool; -import org.springframework.stereotype.Service; - -@Service -public class WorkspaceService { - - @Tool(description = "List all collections in the workspace") - public String listCollections(String workspace) { - // Placeholder implementation - return "List of collections"; - } - - @Tool(description = "Add a collection to the workspace") - public String addCollection(String name, String workspace) { - return "Added collection: " + name; - } - - @Tool(description = "Remove a collection from the workspace") - public String removeCollection(String name, String workspace) { - return "Removed collection: " + name; - } - - @Tool(description = "Update a collection in the workspace") - public String updateCollection(String name, String workspace) { - return "Updated collection: " + name; - } - - @Tool(description = "Get information about a collection in the workspace") - public String getCollection(String name, String workspace) { - return "Info for collection: " + name; - } -} diff --git a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/iCal4jMcpServerMain.java b/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/iCal4jMcpServerMain.java deleted file mode 100644 index b2fa9bb..0000000 --- a/ical4j-command-mcp/src/main/java/org/ical4j/command/mcp/iCal4jMcpServerMain.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2025, Ben Fortuna - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * o Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * o Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * o Neither the name of Ben Fortuna nor the names of any other contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.ical4j.command.mcp; - -import org.springframework.ai.tool.ToolCallbackProvider; -import org.springframework.ai.tool.method.MethodToolCallbackProvider; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; - -@SpringBootApplication -public class iCal4jMcpServerMain { - - public static void main(String[] args) { - SpringApplication.run(iCal4jMcpServerMain.class, args); - } - - @Bean - public ToolCallbackProvider ical4jTools(WorkspaceService workspaceService, CollectionService collectionService) { - return MethodToolCallbackProvider.builder() - .toolObjects(workspaceService, collectionService).build(); - } -} diff --git a/ical4j-command-mcp/src/main/resources/application.properties b/ical4j-command-mcp/src/main/resources/application.properties deleted file mode 100644 index 1e35a97..0000000 --- a/ical4j-command-mcp/src/main/resources/application.properties +++ /dev/null @@ -1,11 +0,0 @@ -spring.main.web-application-type=none - -# NOTE: You must disable the banner and the console logging -# to allow the STDIO transport to work !!! -spring.main.banner-mode=off -logging.pattern.console= - -spring.ai.mcp.server.name=ical4j-command-server -spring.ai.mcp.server.version=0.0.1 - -logging.file.name=./model-context-protocol/weather/starter-stdio-server/target/mcp-weather-stdio-server.log diff --git a/openspec/changes/archive/2026-10-11-single-native-binary/.openspec.yaml b/openspec/changes/archive/2026-10-11-single-native-binary/.openspec.yaml new file mode 100644 index 0000000..34f54d2 --- /dev/null +++ b/openspec/changes/archive/2026-10-11-single-native-binary/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-05 diff --git a/openspec/changes/archive/2026-10-11-single-native-binary/README.md b/openspec/changes/archive/2026-10-11-single-native-binary/README.md new file mode 100644 index 0000000..b9731b7 --- /dev/null +++ b/openspec/changes/archive/2026-10-11-single-native-binary/README.md @@ -0,0 +1,3 @@ +# single-native-binary + +Collapse the repo into a single GraalVM native binary (ict) with CLI and MCP surfaces driven by one operation registry diff --git a/openspec/changes/archive/2026-10-11-single-native-binary/design.md b/openspec/changes/archive/2026-10-11-single-native-binary/design.md new file mode 100644 index 0000000..8e5d216 --- /dev/null +++ b/openspec/changes/archive/2026-10-11-single-native-binary/design.md @@ -0,0 +1,134 @@ +# Design — single-native-binary + +## Context + +The repo today: + +| Module | Content | Tests | +|---|---|---| +| ical4j-command-core | 5 vocabulary enums | none | +| ical4j-command-cli | 82 files, 64 picocli commands, pre-vocabulary names | 13 Spock specs, all pass, 12 commands covered | +| ical4j-command-mcp | Spring Boot + Spring AI, 18 tools returning literal strings | none | +| ical4j-command-agent | 4 files, excluded from `settings.gradle` | 1 | + +The user wants one native executable, `ict`, with MCP served by `ict mcp`. Native-image difficulty lives in dependencies, not in this code, so the repo-shape question and the native question are decided separately here. + +Constraints: +- ical4j 4.x is non-negotiable and uses `ServiceLoader` for factories plus classpath resources for timezones. +- MCP stdio transport owns stdout; any stray write corrupts the protocol. +- The build and publishing infrastructure (Gradle 9, axion-release, vanniktech, CodeQL, scorecards) was modernised in August 2026 and is worth keeping. + +## Goals / Non-Goals + +**Goals** +- One Gradle module, one binary, sub-100ms startup for `ict --help`. +- CLI and MCP defined once via an operation registry. +- Every operation in the new tree has a test and passes a native smoke run. +- Keep git history, CI, and publishing infrastructure. + +**Non-Goals** +- Preserving current command names or the agent module. +- MCP transports other than stdio (HTTP/SSE can come later as `ict mcp --transport http`). +- A Homebrew tap, SDKMAN candidate or signed installers. GitHub Releases is enough for this change. +- Native metadata contributions upstream to ical4j. Metadata lives in this repo under `META-INF/native-image` until proven stable. + +## Decisions + +### D1 — Restructure in place, with fresh-start discipline +Work on a branch in this repo. Delete the mcp, agent and core modules rather than migrating them. Existing CLI command classes are moved into the new tree one at a time, each with a test. + +- **Why:** a fresh repo only buys permission to delete, which a branch grants too. A fresh repo loses the August build and publishing work, CI, history and the repo identity, and leaves the old repo half-alive. +- **Alternative rejected:** fresh repository. Also rejected: keeping all 64 commands and retrofitting names, which would carry 52 untested commands into the native build. + +### D2 — One operation registry, two views (reverses spec Option B) +Each operation is a single `Operation` value: `(Verb, EntityType, Locus)`, a parameter descriptor list, a handler `(Context, Params) -> Result`, and a result type. The CLI view turns each operation into a picocli subcommand and each parameter into an option or positional. The MCP view turns each operation into a tool with a JSON schema generated from the same descriptors. + +- **Why:** in one binary two dispatch paths for the same tuple is duplication with drift risk. The spec's Option B was justified by picocli and Spring AI having incompatible dispatch models; Spring AI is gone. +- **Consequence:** the `command-vocabulary` spec's "dispatch independently" requirement is removed and the "shared core module" requirement is rewritten. +- **Alternative rejected:** keep picocli classes as the source of truth and reflect over their annotations to build MCP tools. Reflection is what native image punishes, and picocli's model is CLI-specific. +- **Vocabulary settled in task 2.1** (from the gaps in `docs/dropped-commands.md`): the type axis is a `Subject` interface implemented by `EntityType`, `SerializationFamily` and `Locus`, so `list collection in workspace` and `import calendar in collection` are ordinary tuples. `Locus` gains `NONE` for stream, file and `generate` operations and `CHANNEL` for `send`/`receive`; neither may be a subject and `OperationId` rejects them. The containment hierarchy is unchanged at two levels. + +### D3 — Handlers return structured results; surfaces render +Handlers return domain objects (`Calendar`, `VCard`, lists of `Uid`, collection descriptors, plain status records), never formatted strings. The CLI renders to iCalendar/vCard text or a table; MCP renders to text or JSON content blocks. This generalises the existing `AbstractCommand` output-handler idea. + +- **Why:** the same operation must serve a terminal and a model. Formatting inside the handler forces one of them to parse the other's output. + +### D4 — Verb-first CLI syntax +`ict [--workspace W] [--collection C] [args]`. Loci are options, not positionals. `generate ` takes no locus. `import|export ` and `send|receive` follow the same pattern. Locus management stays as `ict add collection`, `ict list workspace` and so on, since workspace and collection are also types the vocabulary already names. + +- **Why:** matches the spec tuple order and the user's choice. Help output groups by verb. +- **As built (task 3.x):** `--workspace`, `--format`, `--verbose`, `--quiet` and `--lenient` are inherited global options. `--collection` is not global: it is the shared `collection` parameter that every collection-locus operation declares, including those whose subject is the collection itself (`ict get collection --collection work`), so it appears, with the right required-ness, only on commands that use it. A parameter may not reuse a global option's name, and two operations may not share a verb and subject, since the CLI omits the locus; both fail at startup. +- **Alternative considered:** type-first (`ict event list`), which groups help by type. Purely UX; both derive from the registry. + +### D5 — MCP via the MCP Java SDK, programmatic registration, stdio +Use `io.modelcontextprotocol.sdk:mcp` with `McpServer.sync(...)` and `SyncToolSpecification` built from the registry. Tool names are `_` (for example `list_event`). No annotation-driven tool discovery. + +- **Why:** the SDK tracks the protocol; programmatic registration keeps reflection out; Jackson is already on the classpath through ical4j-serializer. +- **As built (task 4.x):** SDK 2.0.1, as `mcp-core` plus `mcp-json-jackson2` rather than the `mcp` aggregate, which binds Jackson 3 and would put a second Jackson into the image. The stdio transport gives no end-of-stream signal, so `ict mcp` wraps stdin and returns when it reads EOF; the transport drops responses still queued at that moment, so clients must read each response before closing. Tool handlers get an empty stdin, so `import_*` over MCP needs the `file` argument. Tools carry `readOnlyHint`/`destructiveHint` annotations from their verb. +- **Alternatives rejected:** Spring AI (Spring Boot runtime, AOT complexity, 100MB+ binaries); Quarkus mcp-server-stdio (absorbs native metadata pain but brings a full framework into a CLI; the T0 spike showed the metadata burden is 13 entries, so the fallback is not needed); hand-rolled JSON-RPC (protocol drifts). + +### D6 — GraalVM native via `org.graalvm.buildtools.native`, decided by the T0 spike +**Decision (task 0.4, 2026-09-05): proceed with plain GraalVM. Quarkus is not needed.** The spike (`docs/native-spike.md`) compiled the current cli module on GraalVM CE 25.3.4 and found the whole dependency set needs 13 hand-written metadata entries: one type for night-config's `TomlFormat`, two constructors for ical4j's timezone registry and cache, one constructor for Jackson, and resource globs for ical4j's zoneinfo trees and alias files. The result is a single 51 MB file with 30 ms startup against 350 ms on the JVM. + +Concrete choices carried forward from the spike: +- **GraalVM CE for JDK 25 or later.** The plugin's shared reachability-metadata repository refuses GraalVM for JDK 21. Toolchain detection is off; the build reads `GRAALVM_HOME`. +- **`sharedLibrary = false` set explicitly.** Plugin 1.1.12 passed `--shared` otherwise and produced a dylib. +- **picocli's runtime generators, not the annotation processor.** picocli-codegen's processor fails on `@ArgGroup` fields in abstract superclasses. `ReflectionConfigGenerator`, `ResourceConfigGenerator` and `DynamicProxyConfigGenerator` build the model the way the app does. For the registry-driven tree they remain the right tool because commands are not annotated classes. +- **Never register a JDK type wholesale.** picocli registers every option type with all public methods; a `java.net.URL` option made `URL.getContent()` a reflective root, whose JDK content handlers for images and audio live in `java.desktop`, dragging AWT and `javax.sound` into the image and 11 dylibs next to the binary. The generated config strips that entry. Registry parameter types are string, path, integer, boolean and enum, converted inside handlers, so this cannot recur. +- **Metadata sources.** A small hand-written base file under `src/main/resources/META-INF/native-image/org.ical4j/ict/reachability-metadata.json` holds the 13 entries. The tracing agent is driven from the native smoke suite's command list on the JVM build, not from the Spock run, which drowns the signal in Groovy introspection and test-framework service lookups. Agent output merges on top of the base file and is reviewed before commit. +- **The JVM `installDist` path stays buildable** for debugging, for the agent run, and for platforms without a native runner. +- **As built (task 5.x, 2026-10-11, GraalVM CE 25.3.4, macOS arm64):** one 37 MiB file with no dylibs, built in 45 s; median `ict --help` 9 ms. The checked-in metadata is the spike's base file (minus night-config's `TomlFormat`, made unnecessary by passing `TomlFormat.instance()`, plus `version.properties`) merged with a `traceSmoke` capture: 133 reflection entries, mostly MCP SDK `McpSchema` records for Jackson and reactor field updaters, and 25 resource globs including the JSON-schema validator's `draft/2020-12` meta-schemas. `mergeTracedMetadata` drops probes for absent optional classes (Groovy, JDBC, Micrometer, other night-config formats). The smoke suite (`src/smoke`) runs against any `ict` command prefix and refuses to start if an operation lacks a step; `SmokeSuiteTest` checks the same on the JVM. `export calendar` now emits a VTIMEZONE for each referenced TZID from ical4j's registry, and `import calendar` completes time zones before merging to avoid an NPE in the connector's split-by-UID on multi-object input. + +- **Why:** standard, supported path; picocli is native-first; the measured cost is small. +- **Alternative rejected:** Quarkus with its picocli and mcp-server-stdio extensions. It would absorb the metadata work, but that work turned out to be 13 lines, and Quarkus adds a build-time framework and a much larger dependency surface to a CLI. + +### D7 — Logging: drop log4j2, everything to stderr +Replace log4j-core and the slf4j bridge with `slf4j-simple` configured to stderr, level controlled by `--verbose`/`--quiet` and `ICT_LOG_LEVEL`. picocli's out/err are set explicitly per subcommand; `ict mcp` binds picocli's out to stderr. + +- **Why:** stdout exclusivity for MCP; log4j is heavy for a CLI and its native metadata is one more thing to own. + +### D8 — Admission bar +An operation enters `ops/` only with: a Spock spec against an injected in-memory or temp-dir store, and inclusion in the native smoke test that runs `ict --help` and one real invocation. First cohort: the operations behind the 13 green specs. + +- **Why:** this is the mechanism that gives the fresh-start effect without a fresh repo. + +### D9 — Distribution +GitHub Releases carry `ict---` binaries from a CI matrix: ubuntu x64, ubuntu arm64, macOS arm64, windows x64. The single jar continues to publish to Maven Central with the existing vanniktech config, so an embedding consumer remains possible without extra work. + +- **Why:** the binary is the product; keeping the jar costs nothing now that publishing is configured. + +### D10 — Package layout +``` +src/main/java/org/ical4j/command/ + vocab/ Verb, EntityType, Locus, SerializationFamily, SendMethod (moved from core) + ops/ Operation, Param, Result, Registry, handlers by type + cli/ Main (ict), picocli view builder, renderers + mcp/ McpCommand, tool builder, content renderers + config/ CommandConfig (night-config TOML), Filesystem +``` + +## Risks / Trade-offs + +- [ical4j needs extensive resource and service metadata] → measured in T0: two constructor entries and resource globs; ServiceLoader factories resolve automatically. Contribute the entries upstream to ical4j's bundled `META-INF/native-image`. +- [Jackson XML via ical4j-serializer drags woodstox and reflective types into the image] → measured in T0: XML and JSON conversion work with one Jackson entry plus the plugin's metadata repository. Keep the formats. +- [MCP SDK pulls reactor-core, which has its own native quirks] → not exercised by the spike; covered by the tracing agent in task 4/5; SDK is used by Spring AI native builds so metadata exists upstream. +- [Pre-existing JVM bugs hide behind untested commands] → the spike found `ict list` and `print-workspace` failing to initialise collection config, vCard JSON export cycling in Jackson, and the filter grammar rejecting a basic expression. The admission bar (D8) keeps these out until each has a test. +- [Native CI matrix is slow and runner-expensive] → run native builds on tags and a nightly schedule only; PR builds run JVM tests plus a single linux native smoke. +- [Dropping 52 commands loses in-progress ideas] → they stay in git history and are listed in `docs/dropped-commands.md` with their intended vocabulary tuple so they can be re-admitted. +- [Removing JPMS `module-info` breaks nothing today but the bnd/OSGi packaging goes with it] → accepted; OSGi bundles were never a stated goal of the tool. + +## Migration Plan + +1. Done: T0 spike on the current `ical4j-command-cli` module (branch `spike/native-cli`), findings in `docs/native-spike.md`, decision recorded in D6. +2. Collapse modules and dependencies (T1). Build stays green with zero operations registered. +3. Registry, CLI view, first cohort of operations with tests (T2, T3). +4. `ict mcp` (T4). Verified with a scripted stdio client in tests. +5. Native build and metadata (T5). Smoke test in CI. +6. Release matrix and docs (T6, T7). Tag the first release. + +Rollback is a branch delete; `develop` is untouched until merge. + +## Open Questions + +- Should `ict mcp` expose every registered operation, or an allowlist? Default: every operation with a `mcp: true` flag on the descriptor, so destructive operations can be held back initially. +- Does `generate` belong in the first release, or wait until the strategy classes get tests? diff --git a/openspec/changes/archive/2026-10-11-single-native-binary/proposal.md b/openspec/changes/archive/2026-10-11-single-native-binary/proposal.md new file mode 100644 index 0000000..ac28b1d --- /dev/null +++ b/openspec/changes/archive/2026-10-11-single-native-binary/proposal.md @@ -0,0 +1,33 @@ +## Why + +`ict` is meant to be a tool people run, not a framework people embed, yet the repo is shaped as four Maven artifacts (core, cli, mcp, agent) with a Spring Boot MCP server that returns placeholder strings and an agent module excluded from the build. A single GraalVM native binary with `mcp` as a subcommand gives instant startup, one install, and one place where CLI and MCP tools are defined. The June 2026 vocabulary change deliberately kept CLI and MCP dispatch separate because they were separate deployables; in one binary that separation is pure duplication and needs to be reversed. + +## What Changes + +- **BREAKING** Collapse the four Gradle modules into a single module producing one executable, `ict`, built as a GraalVM native image. The `ical4j-command-core`, `ical4j-command-cli`, `ical4j-command-mcp` and `ical4j-command-agent` artifacts stop existing. +- **BREAKING** Reverse the vocabulary spec's "shared names, separate dispatch" rule (Option B). CLI subcommands and MCP tools become two views over one **operation registry** keyed by (verb, type, locus). Each operation is defined once with its parameters and handler. +- **BREAKING** Redesign the CLI syntax as verb-first: `ict [locus options]`, for example `ict list event --collection work`. Pre-vocabulary names (`mkcol`, `rmcol`, `import-calendar`, `validator`, `serialize`, `freebusy`, ...) are removed. +- Add `ict mcp` as a subcommand that serves the same registry over MCP stdio transport, using the MCP Java SDK with programmatic tool registration. Spring Boot and Spring AI are removed. +- Replace log4j2 with a minimal logger writing to stderr, so no code path can write to stdout while MCP owns it. +- Adopt an admission bar for migrating existing commands: an operation enters the new registry only with a passing test and a passing native-image smoke run. The 13 currently green Spock specs (collection, calendar and card CRUD, list, output handlers) define the first cohort. Untested channel, revision, metadata and strategy commands are dropped from the tree and remain in git history. +- Distribute native binaries per platform via GitHub Releases. Maven Central publishing continues for the single jar using the existing vanniktech configuration, but the binary is the primary deliverable. + +## Capabilities + +### New Capabilities +- `operation-registry`: one definition per (verb, type, locus) operation, with parameters, handler and structured result, from which every surface derives its interface. +- `cli-surface`: the verb-first `ict` command tree, locus options, rendering of results to the terminal, exit codes. +- `mcp-surface`: the `ict mcp` subcommand, tool derivation from the registry, stdio transport discipline. +- `native-binary`: the GraalVM native build, reachability metadata handling, JVM fallback, release packaging. + +### Modified Capabilities +- `command-vocabulary`: remove the "dispatch independently" requirement and replace the "shared core module" requirement with the vocabulary living in the single module's operations package. Verbs, types, loci and families are unchanged. + +## Impact + +- **Repo layout**: `settings.gradle` drops all includes; one `build.gradle` with `application`, `org.graalvm.buildtools.native` and picocli-codegen. `ical4j-command-mcp`, `ical4j-command-agent` and `model-context-protocol` directories are deleted. `module-info.java` files are removed (native-image ignores JPMS and `requires java.desktop` is unexplained). +- **Dependencies removed**: spring-boot, spring-ai, langchain4j, log4j-core, log4j-slf4j2-impl, bnd/OSGi annotation processors. **Added**: `io.modelcontextprotocol.sdk:mcp`, `info.picocli:picocli-codegen`, `org.graalvm.buildtools.native`, an slf4j binding that writes to stderr. +- **Dependencies kept but needing native metadata**: ical4j (ServiceLoader factories, zoneinfo resources), jackson via ical4j-serializer and the MCP SDK, night-config, reactor-core via the MCP SDK. +- **CI**: build workflow gains a native build matrix (linux x64 and arm64, macOS arm64, windows x64). Snapshot publishing shrinks to one artifact. Release workflow uploads binaries to GitHub Releases. +- **Docs**: README and `docs/command-protocols.md` rewritten around the verb-first syntax and `ict mcp`. +- **Users**: anyone scripting the current `ict` command names must migrate. Given the tool has no tagged release, this is accepted without a compatibility shim. diff --git a/openspec/changes/archive/2026-10-11-single-native-binary/specs/cli-surface/spec.md b/openspec/changes/archive/2026-10-11-single-native-binary/specs/cli-surface/spec.md new file mode 100644 index 0000000..97cb423 --- /dev/null +++ b/openspec/changes/archive/2026-10-11-single-native-binary/specs/cli-surface/spec.md @@ -0,0 +1,52 @@ +## ADDED Requirements + +### Requirement: Command tree is verb-first +The `ict` executable SHALL expose each registered operation as `ict ` where `verb` and `type` are the lowercase vocabulary names. Loci SHALL be supplied as options (`--workspace`, `--collection`), never as positionals. Operations whose locus is `none` (for example `generate`) SHALL accept no locus option. + +#### Scenario: Listing events in a collection +- **WHEN** the user runs `ict list event --collection work` +- **THEN** the (`list`, `event`, `collection`) operation runs against the collection named `work` in the active workspace + +#### Scenario: Locus option missing falls back to configuration +- **WHEN** the user runs `ict list collection` without `--workspace` +- **THEN** the active workspace from configuration is used + +#### Scenario: Help groups by verb +- **WHEN** the user runs `ict --help` +- **THEN** the usage lists one subcommand per verb, and `ict list --help` lists the types available under `list` + +### Requirement: The CLI is generated from the registry +The picocli command tree SHALL be built from the operation registry at startup. There MUST NOT be a hand-written picocli command class per operation. + +#### Scenario: New operation appears without CLI code +- **WHEN** an operation for (`validate`, `event`, `collection`) is added to the registry +- **THEN** `ict validate event` exists with options derived from its parameter descriptors and no CLI-specific class was added + +### Requirement: Results render per output format +The CLI SHALL render structured results to stdout. Calendars and cards SHALL render as iCalendar or vCard text by default. Lists and descriptors SHALL render as plain lines by default. A global `--format` option SHALL select `text`, `json` or, where the serializer supports it, `xml`. + +#### Scenario: Default calendar output +- **WHEN** `ict export calendar --collection work` succeeds +- **THEN** stdout contains an iCalendar stream beginning with `BEGIN:VCALENDAR` + +#### Scenario: JSON list output +- **WHEN** `ict list collection --format json` succeeds +- **THEN** stdout contains a JSON array of collection descriptors and nothing else + +### Requirement: Exit codes and diagnostics +The CLI SHALL exit 0 on success, 1 on an operation failure (not found, validation failure, store error), and 2 on usage errors. Diagnostics and logs SHALL go to stderr only. + +#### Scenario: Not found +- **WHEN** `ict get collection --collection missing` is run and no such collection exists +- **THEN** the process exits 1, stderr names the collection, and stdout is empty + +#### Scenario: Usage error +- **WHEN** `ict list` is run with no type +- **THEN** the process exits 2 and stderr shows the usage for `list` + +### Requirement: Version and configuration commands +`ict --version` SHALL print the release version derived from the build. `ict config` SHALL read and write the TOML configuration in the user's data directory as today. + +#### Scenario: Version +- **WHEN** the user runs `ict --version` +- **THEN** stdout contains the version string embedded at build time diff --git a/openspec/changes/archive/2026-10-11-single-native-binary/specs/command-vocabulary/spec.md b/openspec/changes/archive/2026-10-11-single-native-binary/specs/command-vocabulary/spec.md new file mode 100644 index 0000000..f29ee2a --- /dev/null +++ b/openspec/changes/archive/2026-10-11-single-native-binary/specs/command-vocabulary/spec.md @@ -0,0 +1,19 @@ +## MODIFIED Requirements + +### Requirement: The vocabulary lives in a shared core module +The canonical verbs, entity types, loci, serialization families and send methods SHALL be defined as enums in the `vocab` package of the single `ict` module. The operation registry and every surface SHALL reference these enums rather than declaring their own string literals. The `vocab` package SHALL contain vocabulary definitions only and MUST NOT contain dispatch or execution logic; dispatch lives in the operation registry. + +#### Scenario: Surfaces reference vocabulary constants +- **WHEN** a surface names an operation +- **THEN** it derives the verb, type and locus names from the `vocab` enums via the operation's registry entry rather than declaring its own string literals + +#### Scenario: Vocabulary package carries no dispatch +- **WHEN** the `vocab` package is inspected +- **THEN** it contains only vocabulary definitions (verbs, types, loci, families, send methods) and no command-execution or dispatch code + +## REMOVED Requirements + +### Requirement: Surfaces share vocabulary but dispatch independently +**Reason**: This requirement existed because the CLI (picocli) and MCP (Spring AI) surfaces were separate deployables with incompatible dispatch models. In a single binary, separate dispatch means every (verb, type, locus) operation is implemented twice with drift risk. Spring AI is removed by this change, so the incompatibility no longer exists. + +**Migration**: Surfaces become views over the operation registry defined in the `operation-registry` capability. The scenario "No cross-surface execution coupling" is superseded by "Surfaces do not call each other" in that spec, which still forbids the MCP view calling CLI classes, but requires both to call the registry. diff --git a/openspec/changes/archive/2026-10-11-single-native-binary/specs/mcp-surface/spec.md b/openspec/changes/archive/2026-10-11-single-native-binary/specs/mcp-surface/spec.md new file mode 100644 index 0000000..c75bd91 --- /dev/null +++ b/openspec/changes/archive/2026-10-11-single-native-binary/specs/mcp-surface/spec.md @@ -0,0 +1,37 @@ +## ADDED Requirements + +### Requirement: `ict mcp` serves the registry over stdio +The `mcp` subcommand SHALL start a Model Context Protocol server on the stdio transport and SHALL block until the client closes the stream. It SHALL be implemented with the MCP Java SDK using programmatic tool registration, not annotation scanning. + +#### Scenario: Initialize handshake +- **WHEN** a client writes an `initialize` request to the process's stdin +- **THEN** the process answers with server name `ict`, the build version, and a `tools` capability + +#### Scenario: Clean shutdown +- **WHEN** the client closes stdin +- **THEN** the process exits 0 without writing further bytes to stdout + +### Requirement: Tools are derived from the registry +Each registry operation flagged for MCP exposure SHALL become one tool named `_` with an input schema generated from the operation's parameter descriptors and a description taken from the operation. There MUST NOT be a hand-written tool per operation. + +#### Scenario: Tool listing +- **WHEN** a client calls `tools/list` +- **THEN** the response includes `list_event` with a `collection` string property, and no tool exists for an operation not flagged for MCP + +#### Scenario: Tool call maps to the handler +- **WHEN** a client calls `list_event` with `{"collection":"work"}` +- **THEN** the (`list`, `event`, `collection`) handler runs and its result is returned as content + +### Requirement: Results render as MCP content +Calendars and cards SHALL be returned as text content in iCalendar or vCard form. Lists and descriptors SHALL be returned as JSON text content. Handler errors SHALL be returned as tool results with `isError` set, not as protocol errors. + +#### Scenario: Not found via MCP +- **WHEN** `get_collection` is called for a collection that does not exist +- **THEN** the tool result has `isError` true and a message naming the collection, and the server keeps running + +### Requirement: stdout is reserved for the protocol +While `ict mcp` runs, nothing other than the MCP transport SHALL write to stdout. Logging, picocli output and library warnings SHALL be routed to stderr. The build SHALL include a test that runs the server with verbose logging enabled and asserts every stdout line is a valid JSON-RPC message. + +#### Scenario: Verbose logging during MCP +- **WHEN** `ict mcp --verbose` handles a `tools/call` that logs at debug level +- **THEN** the log line appears on stderr and stdout contains only JSON-RPC frames diff --git a/openspec/changes/archive/2026-10-11-single-native-binary/specs/native-binary/spec.md b/openspec/changes/archive/2026-10-11-single-native-binary/specs/native-binary/spec.md new file mode 100644 index 0000000..d0b1583 --- /dev/null +++ b/openspec/changes/archive/2026-10-11-single-native-binary/specs/native-binary/spec.md @@ -0,0 +1,44 @@ +## ADDED Requirements + +### Requirement: The build produces a native executable +The Gradle build SHALL produce a GraalVM native executable named `ict` via the `nativeCompile` task. The JVM distribution (`installDist`) SHALL remain buildable from the same module for debugging and for platforms without a native toolchain. + +#### Scenario: Native compile succeeds +- **WHEN** `./gradlew nativeCompile` runs on a supported platform with GraalVM installed +- **THEN** `build/native/nativeCompile/ict` exists and `ict --version` prints the build version + +#### Scenario: JVM fallback +- **WHEN** `./gradlew installDist` runs +- **THEN** `build/install/ict/bin/ict --version` prints the same version + +### Requirement: Reachability metadata is versioned in the repo +Reflection, resource, serialization and proxy metadata required by dependencies SHALL be checked in under `src/main/resources/META-INF/native-image/org.ical4j/ict/`. picocli command metadata SHALL be generated by picocli-codegen at compile time. Metadata for ical4j, Jackson and the MCP SDK SHALL be captured with the tracing agent and reviewed before commit. + +#### Scenario: Timezone resources reachable +- **WHEN** the native `ict export calendar` runs for a collection whose events use `Australia/Melbourne` +- **THEN** the VTIMEZONE is emitted correctly and no missing-resource error occurs + +#### Scenario: ServiceLoader factories reachable +- **WHEN** the native binary parses an iCalendar stream containing an `X-` property and an extension component +- **THEN** ical4j's factories resolve them as they do on the JVM + +### Requirement: Native smoke suite gates the registry +A smoke suite SHALL run against the native binary in CI and SHALL invoke `--help` plus one real invocation for every registered operation, and one `ict mcp` handshake. A registered operation absent from the suite MUST fail the build. + +#### Scenario: Smoke run +- **WHEN** the native smoke suite runs +- **THEN** every operation in the registry has been executed at least once against the binary and all exits match the CLI exit-code contract + +### Requirement: Startup time +`ict --help` on the native binary SHALL complete in under 100 ms on the CI linux x64 runner, measured as wall-clock over ten runs and reported in the build log. + +#### Scenario: Startup measurement +- **WHEN** the CI native job finishes +- **THEN** the log reports the median `ict --help` wall time and the job fails if it exceeds 100 ms + +### Requirement: Release artifacts +On a version tag, CI SHALL build native executables for linux x64, linux arm64, macOS arm64 and windows x64 and attach them to a GitHub Release as `ict---` (with `.exe` on windows) together with SHA-256 checksums. The single jar SHALL continue to publish to Maven Central. + +#### Scenario: Tagged release +- **WHEN** the tag `ict-1.0.0` is pushed +- **THEN** the GitHub Release for that tag carries four executables and a checksum file, and Maven Central receives `org.ical4j:ict:1.0.0` diff --git a/openspec/changes/archive/2026-10-11-single-native-binary/specs/operation-registry/spec.md b/openspec/changes/archive/2026-10-11-single-native-binary/specs/operation-registry/spec.md new file mode 100644 index 0000000..aad3f92 --- /dev/null +++ b/openspec/changes/archive/2026-10-11-single-native-binary/specs/operation-registry/spec.md @@ -0,0 +1,59 @@ +## ADDED Requirements + +### Requirement: Every operation is defined exactly once in the registry +The system SHALL hold a single registry of operations. Each operation SHALL be identified by its (verb, type, locus) tuple from the command vocabulary and SHALL carry: an ordered list of parameter descriptors, a handler, a result type, and a per-surface exposure flag. The registry MUST reject a second registration of the same tuple. + +#### Scenario: Registering an operation +- **WHEN** the operation (`list`, `event`, `collection`) is registered with a `collection` parameter and a handler +- **THEN** the registry exposes exactly one entry for that tuple with that parameter list + +#### Scenario: Duplicate tuple is rejected +- **WHEN** a second operation with the tuple (`list`, `event`, `collection`) is registered +- **THEN** registration fails at startup with an error naming the tuple + +### Requirement: Parameter descriptors are surface-neutral +Each parameter descriptor SHALL declare a name, a value type (string, integer, boolean, enum, path, or a list thereof), whether it is required, a default, and a description. Descriptors MUST NOT reference picocli, MCP or JSON schema types directly; each surface derives its own representation. + +#### Scenario: Deriving a CLI option +- **WHEN** an operation declares an optional string parameter `collection` with description "Collection name" +- **THEN** the CLI view exposes `--collection ` with that description + +#### Scenario: Deriving an MCP input schema +- **WHEN** the same operation is exposed to MCP +- **THEN** the tool's input schema declares a `collection` property of type `string` with that description and it is absent from the schema's `required` list + +### Requirement: Handlers return structured results, not formatted text +A handler SHALL return a typed result (a calendar, a card, a list of identifiers, a collection descriptor, or a status record). A handler MUST NOT write to stdout or stderr and MUST NOT return pre-formatted text intended for a specific surface. + +#### Scenario: List handler returns identifiers +- **WHEN** the (`list`, `event`, `collection`) handler runs against a collection containing two events +- **THEN** it returns a list of two identifiers and writes nothing to any stream + +#### Scenario: Failure is a typed error +- **WHEN** a handler is invoked for a collection that does not exist +- **THEN** it throws or returns a typed not-found error, and each surface maps it to its own convention (a non-zero exit code, an MCP error result) + +### Requirement: Handlers receive a store through a context, never via a global +A handler SHALL obtain object stores, the active workspace and configuration from a context argument supplied by the surface. Handlers MUST NOT read the static configuration singleton directly. + +#### Scenario: Test injects a store +- **WHEN** a Spock spec invokes a handler with a context holding an in-memory store +- **THEN** the handler operates on that store and touches no files under the user's data directory + +### Requirement: Surfaces do not call each other +The CLI view and the MCP view SHALL each invoke operations only through the registry. The MCP view MUST NOT invoke CLI command classes and the CLI view MUST NOT invoke MCP tool classes. + +#### Scenario: MCP executes a list +- **WHEN** an MCP client calls the `list_event` tool +- **THEN** the MCP view resolves (`list`, `event`, `collection`) from the registry and invokes its handler directly + +### Requirement: Admission requires a test and a native smoke run +An operation SHALL be added to the registry only together with a Spock specification exercising its handler against an injected store, and its inclusion in the native smoke test suite. The build MUST fail if a registered operation has no corresponding specification. + +#### Scenario: Operation without a spec +- **WHEN** an operation is registered and no specification references its tuple +- **THEN** the registry conformance test fails naming the tuple + +#### Scenario: First cohort +- **WHEN** the registry is first populated +- **THEN** it contains exactly the operations covered by the existing green specifications: add/get/remove collection, list collections, import/export/remove calendar, import/export/remove card, and list within a collection diff --git a/openspec/changes/archive/2026-10-11-single-native-binary/tasks.md b/openspec/changes/archive/2026-10-11-single-native-binary/tasks.md new file mode 100644 index 0000000..50d31ee --- /dev/null +++ b/openspec/changes/archive/2026-10-11-single-native-binary/tasks.md @@ -0,0 +1,66 @@ +## 0. Native spike (before restructuring) + +- [x] 0.1 On a throwaway branch add `org.graalvm.buildtools.native` and picocli-codegen to the current `ical4j-command-cli` module +- [x] 0.2 Run the tracing agent through the 13 Spock specs and a handful of manual `ict` invocations; collect metadata +- [x] 0.3 Attempt `nativeCompile`; record every failing dependency (ical4j, jackson, woodstox, log4j, night-config) and the fix or workaround in `docs/native-spike.md` +- [x] 0.4 Decide from the findings: proceed with plain GraalVM (D6) or switch to Quarkus (D5 fallback); record the decision in `design.md` + +## 1. Collapse the repo + +- [x] 1.1 Branch `single-native-binary` from `develop` +- [x] 1.2 Delete `ical4j-command-mcp`, `ical4j-command-agent`, `model-context-protocol`; remove Spring, Spring AI, langchain4j from `libs.versions.toml` +- [x] 1.3 Move `ical4j-command-core` enums into `src/main/java/org/ical4j/command/vocab`; delete the core module +- [x] 1.4 Move `ical4j-command-cli` sources to the root module; `settings.gradle` includes nothing; single `build.gradle` with `application`, native plugin (`sharedLibrary = false`, `toolchainDetection = false`), picocli runtime generators from the spike branch, vanniktech coordinates `org.ical4j:ict` +- [x] 1.5 Remove `module-info.java` files and the bnd/OSGi plugin and annotation processors +- [x] 1.6 Replace log4j-core and log4j-slf4j2 with slf4j-simple to stderr; delete `log4j2.properties` +- [x] 1.7 Quarantine every existing command class under `src/legacy/` (excluded from compilation) so they can be re-admitted one by one; build is green with an empty registry +- [x] 1.8 Write `docs/dropped-commands.md` listing each quarantined command with its intended (verb, type, locus) + +## 2. Operation registry + +- [x] 2.1 Define `Operation`, `Param`, `ParamType`, `Result` and `Context` in `ops/`; settle the vocabulary gaps listed at the end of `docs/dropped-commands.md` (no-locus form, `channel` locus, workspace/collection as listable types) +- [x] 2.2 Implement `Registry` with duplicate-tuple rejection and a per-surface exposure flag +- [x] 2.3 Implement `Context` construction from `CommandConfig`: active workspace, calendar store, card store +- [x] 2.4 Registry conformance test: every registered tuple has a Spock spec referencing it +- [x] 2.5 Port first cohort handlers with their existing specs: add/get/remove collection, list collections, import/export/remove calendar, import/export/remove card, list in collection +- [x] 2.6 Port `DefaultOutputHandlers` logic into surface-neutral renderers (`text`, `json`, `ical`, `vcard`) + +## 3. CLI surface + +- [x] 3.1 Implement the picocli tree builder: one subcommand per verb, one per (verb, type) under it, options from `Param` descriptors +- [x] 3.2 Global options: `--workspace`, `--collection`, `--format`, `--verbose`, `--quiet`, `--version`; picocli out/err wired explicitly +- [x] 3.3 Exit-code mapping: 0 success, 1 operation failure, 2 usage error +- [x] 3.4 `ict config` command ported from `ConfigureCommand` +- [x] 3.5 Spock specs for the tree builder: help grouping, option derivation, exit codes, stdout/stderr separation +- [x] 3.6 End-to-end spec running `Main` in-process against a temp-dir store for each first-cohort operation + +## 4. MCP surface + +- [x] 4.1 Add `io.modelcontextprotocol.sdk:mcp`; implement `ict mcp` with `McpServer.sync` on stdio +- [x] 4.2 Tool builder: `_` name, JSON schema from `Param` descriptors, exposure flag respected +- [x] 4.3 Content renderers: calendar/card as text, lists and descriptors as JSON text, handler errors as `isError` results +- [x] 4.4 Route picocli output and logging to stderr while `mcp` runs +- [x] 4.5 Spec with a scripted stdio client: initialize, tools/list, tools/call for a first-cohort tool, clean shutdown on EOF +- [x] 4.6 Spec asserting every stdout line is valid JSON-RPC while verbose logging is on + +## 5. Native build + +- [x] 5.1 Configure `org.graalvm.buildtools.native` and the picocli runtime generators (with the `java.net.URL` strip) in the single module; `nativeCompile` produces a single-file `ict` with no dylibs +- [x] 5.2 Seed `META-INF/native-image/org.ical4j/ict/reachability-metadata.json` with the 13-entry base file from the spike (`simplelogger.properties` replaces the `log4j2.properties` glob); drive the tracing agent from the smoke suite's command list on the JVM build, review, and merge on top +- [x] 5.3 Native smoke suite: `--help` plus one invocation per registered operation and one `ict mcp` handshake; fails on an operation missing from the suite +- [x] 5.4 Verify timezone resources and ServiceLoader factories in the native binary (export with `Australia/Melbourne`, parse `X-` property) +- [x] 5.5 Startup measurement script reporting median `ict --help` time, failing over 100 ms + +## 6. CI and distribution + +- [x] 6.1 `build.yml`: JVM tests on PRs plus a single linux x64 native smoke job +- [x] 6.2 `release.yml`: on `ict-*` tags, native matrix (linux x64, linux arm64, macOS arm64, windows x64), checksums, GitHub Release upload +- [x] 6.3 `publish-snapshots.yml`: publish the single `org.ical4j:ict` jar; drop the multi-module assumptions +- [x] 6.4 Update `Makefile` targets (`native`, `smoke`, `release`) and remove the S3 `uploadDist` target +- [x] 6.5 Update axion-release tag prefix to `ict-` + +## 7. Docs + +- [x] 7.1 Rewrite `README.md` around install, verb-first usage, `--format`, and `ict mcp` client configuration +- [x] 7.2 Rewrite `docs/command-protocols.md` to describe the registry and the two views; remove per-class listings +- [x] 7.3 Archive: update `openspec/specs/command-vocabulary/spec.md` via `openspec archive` once tasks are done diff --git a/openspec/specs/cli-surface/spec.md b/openspec/specs/cli-surface/spec.md new file mode 100644 index 0000000..92e1fb0 --- /dev/null +++ b/openspec/specs/cli-surface/spec.md @@ -0,0 +1,57 @@ +# cli-surface Specification + +## Purpose +The `ict` command line: a verb-first picocli tree generated from the operation registry at +startup, with global options, per-format rendering, exit codes and stderr-only diagnostics. +## Requirements +### Requirement: Command tree is verb-first +The `ict` executable SHALL expose each registered operation as `ict ` where `verb` and `type` are the lowercase vocabulary names. Loci SHALL be supplied as options (`--workspace`, `--collection`), never as positionals. Operations whose locus is `none` (for example `generate`) SHALL accept no locus option. + +#### Scenario: Listing events in a collection +- **WHEN** the user runs `ict list event --collection work` +- **THEN** the (`list`, `event`, `collection`) operation runs against the collection named `work` in the active workspace + +#### Scenario: Locus option missing falls back to configuration +- **WHEN** the user runs `ict list collection` without `--workspace` +- **THEN** the active workspace from configuration is used + +#### Scenario: Help groups by verb +- **WHEN** the user runs `ict --help` +- **THEN** the usage lists one subcommand per verb, and `ict list --help` lists the types available under `list` + +### Requirement: The CLI is generated from the registry +The picocli command tree SHALL be built from the operation registry at startup. There MUST NOT be a hand-written picocli command class per operation. + +#### Scenario: New operation appears without CLI code +- **WHEN** an operation for (`validate`, `event`, `collection`) is added to the registry +- **THEN** `ict validate event` exists with options derived from its parameter descriptors and no CLI-specific class was added + +### Requirement: Results render per output format +The CLI SHALL render structured results to stdout. Calendars and cards SHALL render as iCalendar or vCard text by default. Lists and descriptors SHALL render as plain lines by default. A global `--format` option SHALL select `text`, `json` or, where the serializer supports it, `xml`. + +#### Scenario: Default calendar output +- **WHEN** `ict export calendar --collection work` succeeds +- **THEN** stdout contains an iCalendar stream beginning with `BEGIN:VCALENDAR` + +#### Scenario: JSON list output +- **WHEN** `ict list collection --format json` succeeds +- **THEN** stdout contains a JSON array of collection descriptors and nothing else + +### Requirement: Exit codes and diagnostics +The CLI SHALL exit 0 on success, 1 on an operation failure (not found, validation failure, store error), and 2 on usage errors. Diagnostics and logs SHALL go to stderr only. + +#### Scenario: Not found +- **WHEN** `ict get collection --collection missing` is run and no such collection exists +- **THEN** the process exits 1, stderr names the collection, and stdout is empty + +#### Scenario: Usage error +- **WHEN** `ict list` is run with no type +- **THEN** the process exits 2 and stderr shows the usage for `list` + +### Requirement: Version and configuration commands +`ict --version` SHALL print the release version derived from the build. `ict config` SHALL read and write the TOML configuration in the user's data directory as today. + +#### Scenario: Version +- **WHEN** the user runs `ict --version` +- **THEN** stdout contains the version string embedded at build time + diff --git a/openspec/specs/command-vocabulary/spec.md b/openspec/specs/command-vocabulary/spec.md index d8575a7..7b050c6 100644 --- a/openspec/specs/command-vocabulary/spec.md +++ b/openspec/specs/command-vocabulary/spec.md @@ -2,13 +2,12 @@ ## Purpose -Define a single controlled vocabulary — canonical verbs, entity types, and loci — that all -command surfaces (CLI, MCP, agent) name operations from. Surfaces share these names but -dispatch independently (Option B: shared names, separate dispatch). The vocabulary is -defined in the `ical4j-command-core` module. +Define a single controlled vocabulary — canonical verbs, entity types, and loci — that every +operation in the registry is named from, and so every surface (CLI, MCP) exposes. The +vocabulary is defined in the `vocab` package of the single `ict` module; dispatch lives in the +operation registry. ## Requirements - ### Requirement: Operation identity is (verb, type, locus) Every operation exposed by any surface (CLI, MCP, agent) SHALL be identified by a tuple of exactly three axes: a **verb** (the action), an **entity type** (what is acted on), and a **locus** (the container the action acts within). Surface-specific naming SHALL be derivable from this tuple. @@ -98,24 +97,14 @@ The system SHALL treat the calendar messaging methods `publish`, `request`, and - **WHEN** `request` and `reply` are mapped to the vocabulary - **THEN** both resolve to `send` specialised with their respective iTIP methods, and neither introduces a new top-level verb -### Requirement: Surfaces share vocabulary but dispatch independently -Each surface (CLI, MCP, agent) SHALL name its operations from the shared vocabulary, but SHALL retain its own dispatch and execution. There SHALL NOT be a shared command-execution core that surfaces delegate into; conformance is enforced by naming rules, not by a common dispatcher. - -#### Scenario: No cross-surface execution coupling -- **WHEN** the MCP layer exposes a `list` operation -- **THEN** it implements its own dispatch and does not call the CLI's command classes to execute the operation - -#### Scenario: Adding a verb to the vocabulary -- **WHEN** a new canonical verb is added to the vocabulary -- **THEN** each surface may adopt it independently using the shared name, with no shared dispatcher required to change - ### Requirement: The vocabulary lives in a shared core module -The canonical verbs, entity types, and loci SHALL be defined as constants/enums in a new shared **core module**. Each surface module (CLI, MCP, agent) SHALL depend on the core module for these names. The core module SHALL contain vocabulary definitions only — it MUST NOT contain command dispatch or execution logic, preserving Option B (shared names, separate dispatch). +The canonical verbs, entity types, loci, serialization families and send methods SHALL be defined as enums in the `vocab` package of the single `ict` module. The operation registry and every surface SHALL reference these enums rather than declaring their own string literals. The `vocab` package SHALL contain vocabulary definitions only and MUST NOT contain dispatch or execution logic; dispatch lives in the operation registry. -#### Scenario: Surfaces reference core vocabulary constants +#### Scenario: Surfaces reference vocabulary constants - **WHEN** a surface names an operation -- **THEN** it derives the verb, type, and locus names from the core module's definitions rather than declaring its own string literals +- **THEN** it derives the verb, type and locus names from the `vocab` enums via the operation's registry entry rather than declaring its own string literals + +#### Scenario: Vocabulary package carries no dispatch +- **WHEN** the `vocab` package is inspected +- **THEN** it contains only vocabulary definitions (verbs, types, loci, families, send methods) and no command-execution or dispatch code -#### Scenario: Core module carries no dispatch -- **WHEN** the core module is inspected -- **THEN** it contains only vocabulary definitions (verbs, types, loci) and no command-execution or dispatch code diff --git a/openspec/specs/mcp-surface/spec.md b/openspec/specs/mcp-surface/spec.md new file mode 100644 index 0000000..17840a9 --- /dev/null +++ b/openspec/specs/mcp-surface/spec.md @@ -0,0 +1,42 @@ +# mcp-surface Specification + +## Purpose +The `ict mcp` server: the operation registry served as Model Context Protocol tools over stdio, +with input schemas derived from parameter descriptors and stdout reserved for the protocol. +## Requirements +### Requirement: `ict mcp` serves the registry over stdio +The `mcp` subcommand SHALL start a Model Context Protocol server on the stdio transport and SHALL block until the client closes the stream. It SHALL be implemented with the MCP Java SDK using programmatic tool registration, not annotation scanning. + +#### Scenario: Initialize handshake +- **WHEN** a client writes an `initialize` request to the process's stdin +- **THEN** the process answers with server name `ict`, the build version, and a `tools` capability + +#### Scenario: Clean shutdown +- **WHEN** the client closes stdin +- **THEN** the process exits 0 without writing further bytes to stdout + +### Requirement: Tools are derived from the registry +Each registry operation flagged for MCP exposure SHALL become one tool named `_` with an input schema generated from the operation's parameter descriptors and a description taken from the operation. There MUST NOT be a hand-written tool per operation. + +#### Scenario: Tool listing +- **WHEN** a client calls `tools/list` +- **THEN** the response includes `list_event` with a `collection` string property, and no tool exists for an operation not flagged for MCP + +#### Scenario: Tool call maps to the handler +- **WHEN** a client calls `list_event` with `{"collection":"work"}` +- **THEN** the (`list`, `event`, `collection`) handler runs and its result is returned as content + +### Requirement: Results render as MCP content +Calendars and cards SHALL be returned as text content in iCalendar or vCard form. Lists and descriptors SHALL be returned as JSON text content. Handler errors SHALL be returned as tool results with `isError` set, not as protocol errors. + +#### Scenario: Not found via MCP +- **WHEN** `get_collection` is called for a collection that does not exist +- **THEN** the tool result has `isError` true and a message naming the collection, and the server keeps running + +### Requirement: stdout is reserved for the protocol +While `ict mcp` runs, nothing other than the MCP transport SHALL write to stdout. Logging, picocli output and library warnings SHALL be routed to stderr. The build SHALL include a test that runs the server with verbose logging enabled and asserts every stdout line is a valid JSON-RPC message. + +#### Scenario: Verbose logging during MCP +- **WHEN** `ict mcp --verbose` handles a `tools/call` that logs at debug level +- **THEN** the log line appears on stderr and stdout contains only JSON-RPC frames + diff --git a/openspec/specs/native-binary/spec.md b/openspec/specs/native-binary/spec.md new file mode 100644 index 0000000..1318755 --- /dev/null +++ b/openspec/specs/native-binary/spec.md @@ -0,0 +1,49 @@ +# native-binary Specification + +## Purpose +How `ict` is built and released as a single native executable: versioned reachability +metadata, the native smoke suite that gates the registry, startup time, and release artifacts. +## Requirements +### Requirement: The build produces a native executable +The Gradle build SHALL produce a GraalVM native executable named `ict` via the `nativeCompile` task. The JVM distribution (`installDist`) SHALL remain buildable from the same module for debugging and for platforms without a native toolchain. + +#### Scenario: Native compile succeeds +- **WHEN** `./gradlew nativeCompile` runs on a supported platform with GraalVM installed +- **THEN** `build/native/nativeCompile/ict` exists and `ict --version` prints the build version + +#### Scenario: JVM fallback +- **WHEN** `./gradlew installDist` runs +- **THEN** `build/install/ict/bin/ict --version` prints the same version + +### Requirement: Reachability metadata is versioned in the repo +Reflection, resource, serialization and proxy metadata required by dependencies SHALL be checked in under `src/main/resources/META-INF/native-image/org.ical4j/ict/`. picocli command metadata SHALL be generated by picocli-codegen at compile time. Metadata for ical4j, Jackson and the MCP SDK SHALL be captured with the tracing agent and reviewed before commit. + +#### Scenario: Timezone resources reachable +- **WHEN** the native `ict export calendar` runs for a collection whose events use `Australia/Melbourne` +- **THEN** the VTIMEZONE is emitted correctly and no missing-resource error occurs + +#### Scenario: ServiceLoader factories reachable +- **WHEN** the native binary parses an iCalendar stream containing an `X-` property and an extension component +- **THEN** ical4j's factories resolve them as they do on the JVM + +### Requirement: Native smoke suite gates the registry +A smoke suite SHALL run against the native binary in CI and SHALL invoke `--help` plus one real invocation for every registered operation, and one `ict mcp` handshake. A registered operation absent from the suite MUST fail the build. + +#### Scenario: Smoke run +- **WHEN** the native smoke suite runs +- **THEN** every operation in the registry has been executed at least once against the binary and all exits match the CLI exit-code contract + +### Requirement: Startup time +`ict --help` on the native binary SHALL complete in under 100 ms on the CI linux x64 runner, measured as wall-clock over ten runs and reported in the build log. + +#### Scenario: Startup measurement +- **WHEN** the CI native job finishes +- **THEN** the log reports the median `ict --help` wall time and the job fails if it exceeds 100 ms + +### Requirement: Release artifacts +On a version tag, CI SHALL build native executables for linux x64, linux arm64, macOS arm64 and windows x64 and attach them to a GitHub Release as `ict---` (with `.exe` on windows) together with SHA-256 checksums. The single jar SHALL continue to publish to Maven Central. + +#### Scenario: Tagged release +- **WHEN** the tag `ict-1.0.0` is pushed +- **THEN** the GitHub Release for that tag carries four executables and a checksum file, and Maven Central receives `org.ical4j:ict:1.0.0` + diff --git a/openspec/specs/operation-registry/spec.md b/openspec/specs/operation-registry/spec.md new file mode 100644 index 0000000..0e2bd9d --- /dev/null +++ b/openspec/specs/operation-registry/spec.md @@ -0,0 +1,64 @@ +# operation-registry Specification + +## Purpose +The single table of operations that every surface derives from: identity, surface-neutral +parameter descriptors, structured results, context-supplied stores, and the admission bar. +## Requirements +### Requirement: Every operation is defined exactly once in the registry +The system SHALL hold a single registry of operations. Each operation SHALL be identified by its (verb, type, locus) tuple from the command vocabulary and SHALL carry: an ordered list of parameter descriptors, a handler, a result type, and a per-surface exposure flag. The registry MUST reject a second registration of the same tuple. + +#### Scenario: Registering an operation +- **WHEN** the operation (`list`, `event`, `collection`) is registered with a `collection` parameter and a handler +- **THEN** the registry exposes exactly one entry for that tuple with that parameter list + +#### Scenario: Duplicate tuple is rejected +- **WHEN** a second operation with the tuple (`list`, `event`, `collection`) is registered +- **THEN** registration fails at startup with an error naming the tuple + +### Requirement: Parameter descriptors are surface-neutral +Each parameter descriptor SHALL declare a name, a value type (string, integer, boolean, enum, path, or a list thereof), whether it is required, a default, and a description. Descriptors MUST NOT reference picocli, MCP or JSON schema types directly; each surface derives its own representation. + +#### Scenario: Deriving a CLI option +- **WHEN** an operation declares an optional string parameter `collection` with description "Collection name" +- **THEN** the CLI view exposes `--collection ` with that description + +#### Scenario: Deriving an MCP input schema +- **WHEN** the same operation is exposed to MCP +- **THEN** the tool's input schema declares a `collection` property of type `string` with that description and it is absent from the schema's `required` list + +### Requirement: Handlers return structured results, not formatted text +A handler SHALL return a typed result (a calendar, a card, a list of identifiers, a collection descriptor, or a status record). A handler MUST NOT write to stdout or stderr and MUST NOT return pre-formatted text intended for a specific surface. + +#### Scenario: List handler returns identifiers +- **WHEN** the (`list`, `event`, `collection`) handler runs against a collection containing two events +- **THEN** it returns a list of two identifiers and writes nothing to any stream + +#### Scenario: Failure is a typed error +- **WHEN** a handler is invoked for a collection that does not exist +- **THEN** it throws or returns a typed not-found error, and each surface maps it to its own convention (a non-zero exit code, an MCP error result) + +### Requirement: Handlers receive a store through a context, never via a global +A handler SHALL obtain object stores, the active workspace and configuration from a context argument supplied by the surface. Handlers MUST NOT read the static configuration singleton directly. + +#### Scenario: Test injects a store +- **WHEN** a Spock spec invokes a handler with a context holding an in-memory store +- **THEN** the handler operates on that store and touches no files under the user's data directory + +### Requirement: Surfaces do not call each other +The CLI view and the MCP view SHALL each invoke operations only through the registry. The MCP view MUST NOT invoke CLI command classes and the CLI view MUST NOT invoke MCP tool classes. + +#### Scenario: MCP executes a list +- **WHEN** an MCP client calls the `list_event` tool +- **THEN** the MCP view resolves (`list`, `event`, `collection`) from the registry and invokes its handler directly + +### Requirement: Admission requires a test and a native smoke run +An operation SHALL be added to the registry only together with a Spock specification exercising its handler against an injected store, and its inclusion in the native smoke test suite. The build MUST fail if a registered operation has no corresponding specification. + +#### Scenario: Operation without a spec +- **WHEN** an operation is registered and no specification references its tuple +- **THEN** the registry conformance test fails naming the tuple + +#### Scenario: First cohort +- **WHEN** the registry is first populated +- **THEN** it contains exactly the operations covered by the existing green specifications: add/get/remove collection, list collections, import/export/remove calendar, import/export/remove card, and list within a collection + diff --git a/settings.gradle b/settings.gradle index b0d493a..167d03a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,6 +1 @@ -rootProject.name = 'ical4j-command' - -include "ical4j-command-core" -include "ical4j-command-cli" -//include "ical4j-command-agent" -include "ical4j-command-mcp" +rootProject.name = 'ict' diff --git a/src/legacy/README.md b/src/legacy/README.md new file mode 100644 index 0000000..feca104 --- /dev/null +++ b/src/legacy/README.md @@ -0,0 +1,11 @@ +# Legacy command tree (quarantined) + +Nothing under `src/legacy` is compiled. These are the picocli command classes, their support +classes and Spock specs from before the `single-native-binary` change, kept in place so each +operation can be re-admitted into the operation registry one at a time under the admission +bar in `openspec/changes/single-native-binary/design.md` (D8): a spec against an injected +store and a place in the native smoke suite. + +Package paths are unchanged, so re-admitting a class is a `git mv` back under `src/main` +followed by the rewrite onto the registry. `docs/dropped-commands.md` lists every command +here with its intended (verb, type, locus). diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/AbstractCommand.java b/src/legacy/main/java/org/ical4j/command/AbstractCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/AbstractCommand.java rename to src/legacy/main/java/org/ical4j/command/AbstractCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/ConverterCommand.java b/src/legacy/main/java/org/ical4j/command/ConverterCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/ConverterCommand.java rename to src/legacy/main/java/org/ical4j/command/ConverterCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/CopyCommand.java b/src/legacy/main/java/org/ical4j/command/CopyCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/CopyCommand.java rename to src/legacy/main/java/org/ical4j/command/CopyCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/DeleteCommand.java b/src/legacy/main/java/org/ical4j/command/DeleteCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/DeleteCommand.java rename to src/legacy/main/java/org/ical4j/command/DeleteCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/EditCommand.java b/src/legacy/main/java/org/ical4j/command/EditCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/EditCommand.java rename to src/legacy/main/java/org/ical4j/command/EditCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/ExportCommand.java b/src/legacy/main/java/org/ical4j/command/ExportCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/ExportCommand.java rename to src/legacy/main/java/org/ical4j/command/ExportCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/FilterCommand.java b/src/legacy/main/java/org/ical4j/command/FilterCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/FilterCommand.java rename to src/legacy/main/java/org/ical4j/command/FilterCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/ImportCalendars.java b/src/legacy/main/java/org/ical4j/command/ImportCalendars.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/ImportCalendars.java rename to src/legacy/main/java/org/ical4j/command/ImportCalendars.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/ImportCards.java b/src/legacy/main/java/org/ical4j/command/ImportCards.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/ImportCards.java rename to src/legacy/main/java/org/ical4j/command/ImportCards.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/InputHandler.java b/src/legacy/main/java/org/ical4j/command/InputHandler.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/InputHandler.java rename to src/legacy/main/java/org/ical4j/command/InputHandler.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/InputOptions.java b/src/legacy/main/java/org/ical4j/command/InputOptions.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/InputOptions.java rename to src/legacy/main/java/org/ical4j/command/InputOptions.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/MoveCommand.java b/src/legacy/main/java/org/ical4j/command/MoveCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/MoveCommand.java rename to src/legacy/main/java/org/ical4j/command/MoveCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/OutputOptions.java b/src/legacy/main/java/org/ical4j/command/OutputOptions.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/OutputOptions.java rename to src/legacy/main/java/org/ical4j/command/OutputOptions.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/PrintCommand.java b/src/legacy/main/java/org/ical4j/command/PrintCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/PrintCommand.java rename to src/legacy/main/java/org/ical4j/command/PrintCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/ValidatorCommand.java b/src/legacy/main/java/org/ical4j/command/ValidatorCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/ValidatorCommand.java rename to src/legacy/main/java/org/ical4j/command/ValidatorCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/AbstractCalendarCommand.java b/src/legacy/main/java/org/ical4j/command/calendar/AbstractCalendarCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/calendar/AbstractCalendarCommand.java rename to src/legacy/main/java/org/ical4j/command/calendar/AbstractCalendarCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/CalendarCommandGroup.java b/src/legacy/main/java/org/ical4j/command/calendar/CalendarCommandGroup.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/calendar/CalendarCommandGroup.java rename to src/legacy/main/java/org/ical4j/command/calendar/CalendarCommandGroup.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/FilterCalendar.java b/src/legacy/main/java/org/ical4j/command/calendar/FilterCalendar.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/calendar/FilterCalendar.java rename to src/legacy/main/java/org/ical4j/command/calendar/FilterCalendar.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/FreeBusy.java b/src/legacy/main/java/org/ical4j/command/calendar/FreeBusy.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/calendar/FreeBusy.java rename to src/legacy/main/java/org/ical4j/command/calendar/FreeBusy.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/ReplaceUids.java b/src/legacy/main/java/org/ical4j/command/calendar/ReplaceUids.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/calendar/ReplaceUids.java rename to src/legacy/main/java/org/ical4j/command/calendar/ReplaceUids.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/Serializer.java b/src/legacy/main/java/org/ical4j/command/calendar/Serializer.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/calendar/Serializer.java rename to src/legacy/main/java/org/ical4j/command/calendar/Serializer.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/calendar/Validator.java b/src/legacy/main/java/org/ical4j/command/calendar/Validator.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/calendar/Validator.java rename to src/legacy/main/java/org/ical4j/command/calendar/Validator.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/card/AbstractEntityCommand.java b/src/legacy/main/java/org/ical4j/command/card/AbstractEntityCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/card/AbstractEntityCommand.java rename to src/legacy/main/java/org/ical4j/command/card/AbstractEntityCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/card/CardCommandGroup.java b/src/legacy/main/java/org/ical4j/command/card/CardCommandGroup.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/card/CardCommandGroup.java rename to src/legacy/main/java/org/ical4j/command/card/CardCommandGroup.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/card/Serializer.java b/src/legacy/main/java/org/ical4j/command/card/Serializer.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/card/Serializer.java rename to src/legacy/main/java/org/ical4j/command/card/Serializer.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/channel/AbstractEgressChannelCommand.java b/src/legacy/main/java/org/ical4j/command/channel/AbstractEgressChannelCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/channel/AbstractEgressChannelCommand.java rename to src/legacy/main/java/org/ical4j/command/channel/AbstractEgressChannelCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/channel/AbstractIngressChannelCommand.java b/src/legacy/main/java/org/ical4j/command/channel/AbstractIngressChannelCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/channel/AbstractIngressChannelCommand.java rename to src/legacy/main/java/org/ical4j/command/channel/AbstractIngressChannelCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/channel/ChannelCommandGroup.java b/src/legacy/main/java/org/ical4j/command/channel/ChannelCommandGroup.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/channel/ChannelCommandGroup.java rename to src/legacy/main/java/org/ical4j/command/channel/ChannelCommandGroup.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/channel/ReceiveCalendarCommand.java b/src/legacy/main/java/org/ical4j/command/channel/ReceiveCalendarCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/channel/ReceiveCalendarCommand.java rename to src/legacy/main/java/org/ical4j/command/channel/ReceiveCalendarCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/channel/ReceiveVCardCommand.java b/src/legacy/main/java/org/ical4j/command/channel/ReceiveVCardCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/channel/ReceiveVCardCommand.java rename to src/legacy/main/java/org/ical4j/command/channel/ReceiveVCardCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/channel/SendCalendarCommand.java b/src/legacy/main/java/org/ical4j/command/channel/SendCalendarCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/channel/SendCalendarCommand.java rename to src/legacy/main/java/org/ical4j/command/channel/SendCalendarCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/channel/SendVCardCommand.java b/src/legacy/main/java/org/ical4j/command/channel/SendVCardCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/channel/SendVCardCommand.java rename to src/legacy/main/java/org/ical4j/command/channel/SendVCardCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/AbstractCollectionCommand.java b/src/legacy/main/java/org/ical4j/command/collection/AbstractCollectionCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/collection/AbstractCollectionCommand.java rename to src/legacy/main/java/org/ical4j/command/collection/AbstractCollectionCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/CollectionCommandGroup.java b/src/legacy/main/java/org/ical4j/command/collection/CollectionCommandGroup.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/collection/CollectionCommandGroup.java rename to src/legacy/main/java/org/ical4j/command/collection/CollectionCommandGroup.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/ListCards.java b/src/legacy/main/java/org/ical4j/command/collection/ListCards.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/collection/ListCards.java rename to src/legacy/main/java/org/ical4j/command/collection/ListCards.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/ListObjectUids.java b/src/legacy/main/java/org/ical4j/command/collection/ListObjectUids.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/collection/ListObjectUids.java rename to src/legacy/main/java/org/ical4j/command/collection/ListObjectUids.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/collection/UpdateCollection.java b/src/legacy/main/java/org/ical4j/command/collection/UpdateCollection.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/collection/UpdateCollection.java rename to src/legacy/main/java/org/ical4j/command/collection/UpdateCollection.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/config/ConfigureCommand.java b/src/legacy/main/java/org/ical4j/command/config/ConfigureCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/config/ConfigureCommand.java rename to src/legacy/main/java/org/ical4j/command/config/ConfigureCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/metadata/AddAttachment.java b/src/legacy/main/java/org/ical4j/command/metadata/AddAttachment.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/metadata/AddAttachment.java rename to src/legacy/main/java/org/ical4j/command/metadata/AddAttachment.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/metadata/AddCategories.java b/src/legacy/main/java/org/ical4j/command/metadata/AddCategories.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/metadata/AddCategories.java rename to src/legacy/main/java/org/ical4j/command/metadata/AddCategories.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/metadata/AddCommandGroup.java b/src/legacy/main/java/org/ical4j/command/metadata/AddCommandGroup.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/metadata/AddCommandGroup.java rename to src/legacy/main/java/org/ical4j/command/metadata/AddCommandGroup.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/metadata/AddComment.java b/src/legacy/main/java/org/ical4j/command/metadata/AddComment.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/metadata/AddComment.java rename to src/legacy/main/java/org/ical4j/command/metadata/AddComment.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/metadata/AddRelated.java b/src/legacy/main/java/org/ical4j/command/metadata/AddRelated.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/metadata/AddRelated.java rename to src/legacy/main/java/org/ical4j/command/metadata/AddRelated.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/metadata/GetProperty.java b/src/legacy/main/java/org/ical4j/command/metadata/GetProperty.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/metadata/GetProperty.java rename to src/legacy/main/java/org/ical4j/command/metadata/GetProperty.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/metadata/PropertyCommandGroup.java b/src/legacy/main/java/org/ical4j/command/metadata/PropertyCommandGroup.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/metadata/PropertyCommandGroup.java rename to src/legacy/main/java/org/ical4j/command/metadata/PropertyCommandGroup.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/metadata/SetCommandGroup.java b/src/legacy/main/java/org/ical4j/command/metadata/SetCommandGroup.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/metadata/SetCommandGroup.java rename to src/legacy/main/java/org/ical4j/command/metadata/SetCommandGroup.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/metadata/UnsetProperty.java b/src/legacy/main/java/org/ical4j/command/metadata/UnsetProperty.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/metadata/UnsetProperty.java rename to src/legacy/main/java/org/ical4j/command/metadata/UnsetProperty.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/revisions/ListRevisions.java b/src/legacy/main/java/org/ical4j/command/revisions/ListRevisions.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/revisions/ListRevisions.java rename to src/legacy/main/java/org/ical4j/command/revisions/ListRevisions.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/revisions/RevertRevision.java b/src/legacy/main/java/org/ical4j/command/revisions/RevertRevision.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/revisions/RevertRevision.java rename to src/legacy/main/java/org/ical4j/command/revisions/RevertRevision.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/revisions/UndoRevisions.java b/src/legacy/main/java/org/ical4j/command/revisions/UndoRevisions.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/revisions/UndoRevisions.java rename to src/legacy/main/java/org/ical4j/command/revisions/UndoRevisions.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateAction.java b/src/legacy/main/java/org/ical4j/command/strategy/CreateAction.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateAction.java rename to src/legacy/main/java/org/ical4j/command/strategy/CreateAction.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateCalendar.java b/src/legacy/main/java/org/ical4j/command/strategy/CreateCalendar.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateCalendar.java rename to src/legacy/main/java/org/ical4j/command/strategy/CreateCalendar.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateCard.java b/src/legacy/main/java/org/ical4j/command/strategy/CreateCard.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateCard.java rename to src/legacy/main/java/org/ical4j/command/strategy/CreateCard.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateEntity.java b/src/legacy/main/java/org/ical4j/command/strategy/CreateEntity.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateEntity.java rename to src/legacy/main/java/org/ical4j/command/strategy/CreateEntity.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateEvent.java b/src/legacy/main/java/org/ical4j/command/strategy/CreateEvent.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateEvent.java rename to src/legacy/main/java/org/ical4j/command/strategy/CreateEvent.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateIssue.java b/src/legacy/main/java/org/ical4j/command/strategy/CreateIssue.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateIssue.java rename to src/legacy/main/java/org/ical4j/command/strategy/CreateIssue.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateNote.java b/src/legacy/main/java/org/ical4j/command/strategy/CreateNote.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateNote.java rename to src/legacy/main/java/org/ical4j/command/strategy/CreateNote.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateObservance.java b/src/legacy/main/java/org/ical4j/command/strategy/CreateObservance.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/strategy/CreateObservance.java rename to src/legacy/main/java/org/ical4j/command/strategy/CreateObservance.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/strategy/StrategyCommandGroup.java b/src/legacy/main/java/org/ical4j/command/strategy/StrategyCommandGroup.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/strategy/StrategyCommandGroup.java rename to src/legacy/main/java/org/ical4j/command/strategy/StrategyCommandGroup.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/strategy/StrategyInfo.java b/src/legacy/main/java/org/ical4j/command/strategy/StrategyInfo.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/strategy/StrategyInfo.java rename to src/legacy/main/java/org/ical4j/command/strategy/StrategyInfo.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/workspace/AbstractWorkspaceCommand.java b/src/legacy/main/java/org/ical4j/command/workspace/AbstractWorkspaceCommand.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/workspace/AbstractWorkspaceCommand.java rename to src/legacy/main/java/org/ical4j/command/workspace/AbstractWorkspaceCommand.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/workspace/ActivateWorkspace.java b/src/legacy/main/java/org/ical4j/command/workspace/ActivateWorkspace.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/workspace/ActivateWorkspace.java rename to src/legacy/main/java/org/ical4j/command/workspace/ActivateWorkspace.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/workspace/ListWorkspaces.java b/src/legacy/main/java/org/ical4j/command/workspace/ListWorkspaces.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/workspace/ListWorkspaces.java rename to src/legacy/main/java/org/ical4j/command/workspace/ListWorkspaces.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/workspace/PrintWorkspace.java b/src/legacy/main/java/org/ical4j/command/workspace/PrintWorkspace.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/workspace/PrintWorkspace.java rename to src/legacy/main/java/org/ical4j/command/workspace/PrintWorkspace.java diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/workspace/WorkspaceCommandGroup.java b/src/legacy/main/java/org/ical4j/command/workspace/WorkspaceCommandGroup.java similarity index 100% rename from ical4j-command-cli/src/main/java/org/ical4j/command/workspace/WorkspaceCommandGroup.java rename to src/legacy/main/java/org/ical4j/command/workspace/WorkspaceCommandGroup.java diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/CreateCalendarTest.groovy b/src/legacy/test/groovy/org/ical4j/command/calendar/CreateCalendarTest.groovy similarity index 100% rename from ical4j-command-cli/src/test/groovy/org/ical4j/command/calendar/CreateCalendarTest.groovy rename to src/legacy/test/groovy/org/ical4j/command/calendar/CreateCalendarTest.groovy diff --git a/ical4j-command-cli/src/test/groovy/org/ical4j/command/card/CreateCardTest.groovy b/src/legacy/test/groovy/org/ical4j/command/card/CreateCardTest.groovy similarity index 100% rename from ical4j-command-cli/src/test/groovy/org/ical4j/command/card/CreateCardTest.groovy rename to src/legacy/test/groovy/org/ical4j/command/card/CreateCardTest.groovy diff --git a/ical4j-command-cli/src/test/resources/geo.ics b/src/legacy/test/resources/geo.ics similarity index 100% rename from ical4j-command-cli/src/test/resources/geo.ics rename to src/legacy/test/resources/geo.ics diff --git a/src/main/java/org/ical4j/command/Version.java b/src/main/java/org/ical4j/command/Version.java new file mode 100644 index 0000000..8418c12 --- /dev/null +++ b/src/main/java/org/ical4j/command/Version.java @@ -0,0 +1,33 @@ +package org.ical4j.command; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.Properties; + +/** + * The {@code ict} version embedded at build time in {@code org/ical4j/command/version.properties}. + * A resource rather than the jar manifest, because a native image and an in-process test run + * have no manifest to read. Shared by both surfaces: {@code ict --version} and the MCP server info. + */ +public final class Version { + + static final String RESOURCE = "/org/ical4j/command/version.properties"; + + private Version() { + } + + /** The {@code ict} version, or {@code unknown} if the resource was not built. */ + public static String get() { + try (InputStream in = Version.class.getResourceAsStream(RESOURCE)) { + if (in == null) { + return "unknown"; + } + Properties p = new Properties(); + p.load(in); + return p.getProperty("version", "unknown"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/src/main/java/org/ical4j/command/cli/CommandTree.java b/src/main/java/org/ical4j/command/cli/CommandTree.java new file mode 100644 index 0000000..0eb01fb --- /dev/null +++ b/src/main/java/org/ical4j/command/cli/CommandTree.java @@ -0,0 +1,169 @@ +package org.ical4j.command.cli; + +import org.ical4j.command.ops.Operation; +import org.ical4j.command.ops.Param; +import org.ical4j.command.ops.ParamType; +import org.ical4j.command.ops.Params; +import org.ical4j.command.ops.Registry; +import org.ical4j.command.ops.Surface; +import org.ical4j.command.vocab.Verb; +import picocli.CommandLine; +import picocli.CommandLine.Model.CommandSpec; +import picocli.CommandLine.Model.OptionSpec; + +import java.util.EnumMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.IntStream; + +/** + * The CLI view of the registry: {@code ict [--param value ...]}. + *

+ * One subcommand per verb that has CLI-exposed operations, and under it one subcommand per + * operation, named by its subject. Every parameter becomes a {@code --name} option; loci such + * as {@code --collection} are ordinary parameters of the operations that act within them. The + * tree is built with picocli's programmatic API, so no class here is annotated and none needs + * reflection metadata in the native image. + */ +final class CommandTree { + + /** Runs an operation with parsed parameters and returns the exit code. */ + @FunctionalInterface + interface Invoker { + int invoke(Operation operation, Params params); + } + + private static final Map VERB_DESCRIPTIONS = new EnumMap<>(Map.ofEntries( + Map.entry(Verb.LIST, "List the items of a type within a locus"), + Map.entry(Verb.GET, "Return one item of a type"), + Map.entry(Verb.GENERATE, "Synthesise a new item from a strategy or template"), + Map.entry(Verb.ADD, "Place an item into a locus"), + Map.entry(Verb.UPDATE, "Modify an existing item in place"), + Map.entry(Verb.REMOVE, "Take an item out of a locus"), + Map.entry(Verb.COPY, "Duplicate an item into a locus"), + Map.entry(Verb.MOVE, "Relocate an item from one locus to another"), + Map.entry(Verb.FILTER, "Derive a subset of a type by expression"), + Map.entry(Verb.VALIDATE, "Check an item or locus for conformance"), + Map.entry(Verb.IMPORT, "Read calendar or card data into a locus"), + Map.entry(Verb.EXPORT, "Write calendar or card data out of a locus"), + Map.entry(Verb.SEND, "Transmit items over a channel"), + Map.entry(Verb.RECEIVE, "Accept incoming items over a channel"))); + + private CommandTree() { + } + + /** + * Adds a verb subcommand to {@code root} for each verb with CLI operations, in vocabulary + * order. + * + * @throws IllegalStateException if two operations share a verb and subject (the CLI names + * operations without their locus), or a parameter name clashes + * with a global option + */ + static void attach(CommandLine root, Registry registry, Invoker invoker) { + Set reserved = new HashSet<>(); + root.getCommandSpec().options().forEach(o -> reserved.addAll(List.of(o.names()))); + + for (Map.Entry> entry : registry.byVerb(Surface.CLI).entrySet()) { + Verb verb = entry.getKey(); + String verbKey = verb.name().toLowerCase(Locale.ROOT); + CommandSpec verbSpec = CommandSpec.create().name(verbKey); + verbSpec.usageMessage().description(VERB_DESCRIPTIONS.get(verb)).commandListHeading("%nTypes:%n"); + CommandLine verbCommand = new CommandLine(verbSpec); + // Attach before adding leaves so that inherited options flow root -> verb -> type. + root.addSubcommand(verbKey, verbCommand); + + Map bySubject = new LinkedHashMap<>(); + for (Operation op : entry.getValue()) { + Operation clash = bySubject.putIfAbsent(op.id().subjectKey(), op); + if (clash != null) { + throw new IllegalStateException("CLI cannot distinguish '" + clash.id() + "' from '" + op.id() + + "': both are 'ict " + verbKey + " " + op.id().subjectKey() + "'"); + } + verbCommand.addSubcommand(op.id().subjectKey(), leaf(op, reserved, invoker)); + } + } + } + + private static CommandLine leaf(Operation op, Set reserved, Invoker invoker) { + OperationCommand command = new OperationCommand(op, invoker); + CommandSpec spec = CommandSpec.wrapWithoutInspection(command).name(op.id().subjectKey()); + spec.usageMessage().description(op.description()); + for (Param p : op.params()) { + String name = "--" + p.name(); + if (reserved.contains(name)) { + throw new IllegalStateException("Parameter '" + p.name() + "' of '" + op.id() + + "' clashes with the global option " + name); + } + spec.addOption(option(p)); + } + command.spec = spec; + return new CommandLine(spec); + } + + /** Derives a picocli option from a descriptor. Defaults and choices are enforced by {@link Params#resolve}. */ + static OptionSpec option(Param p) { + StringBuilder description = new StringBuilder(p.description()); + if (!p.choices().isEmpty()) { + description.append(" (one of: ").append(String.join(", ", p.choices())).append(')'); + } + if (p.defaultValue() != null && p.type() != ParamType.BOOLEAN) { + description.append(" (default: ").append(p.defaultValue()).append(')'); + } + OptionSpec.Builder b = OptionSpec.builder("--" + p.name()) + .description(description.toString()) + .required(p.required()); + switch (p.type()) { + case BOOLEAN: + b.type(p.multiple() ? boolean[].class : boolean.class).arity("0..1"); + break; + case ENUM: + b.completionCandidates(p.choices()); + // fall through: enum values travel as strings + default: + b.type(p.multiple() ? String[].class : String.class).paramLabel("<" + p.name() + ">"); + } + return b.build(); + } + + /** The executable leaf: collects matched options into {@link Params} and hands off. */ + private static final class OperationCommand implements Callable { + + private final Operation operation; + private final Invoker invoker; + private CommandSpec spec; + + OperationCommand(Operation operation, Invoker invoker) { + this.operation = operation; + this.invoker = invoker; + } + + @Override + public Integer call() { + CommandLine.ParseResult parsed = spec.commandLine().getParseResult(); + Map values = new LinkedHashMap<>(); + for (Param p : operation.params()) { + OptionSpec option = spec.findOption("--" + p.name()); + if (parsed.hasMatchedOption(option)) { + values.put(p.name(), asValue(option.getValue())); + } + } + return invoker.invoke(operation, Params.of(values)); + } + + private static Object asValue(Object value) { + if (value instanceof String[] strings) { + return List.of(strings); + } + if (value instanceof boolean[] flags) { + return IntStream.range(0, flags.length).mapToObj(i -> String.valueOf(flags[i])).toList(); + } + return value; + } + } +} diff --git a/src/main/java/org/ical4j/command/cli/ConfigCommand.java b/src/main/java/org/ical4j/command/cli/ConfigCommand.java new file mode 100644 index 0000000..7d1e43b --- /dev/null +++ b/src/main/java/org/ical4j/command/cli/ConfigCommand.java @@ -0,0 +1,76 @@ +package org.ical4j.command.cli; + +import org.ical4j.command.config.CommandConfig; +import org.ical4j.command.ops.OperationException; +import picocli.CommandLine; +import picocli.CommandLine.Model.CommandSpec; +import picocli.CommandLine.Model.PositionalParamSpec; + +import java.io.PrintWriter; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.function.Supplier; + +/** + * {@code ict config [ [...]]}: show all settings, show one, or set one. Not a + * registry operation; it edits the configuration the registry's context is built from. + */ +final class ConfigCommand implements Callable { + + /** Top-level TOML sections a setting may be written to. */ + static final List SECTIONS = List.of("user", "workspace", "store", "contentType"); + + private final Supplier config; + + private CommandSpec spec; + + private ConfigCommand(Supplier config) { + this.config = config; + } + + static CommandLine create(Supplier config) { + ConfigCommand command = new ConfigCommand(config); + CommandSpec spec = CommandSpec.wrapWithoutInspection(command).name("config"); + spec.usageMessage().description("Show or change settings in the configuration file", + "With no arguments, list every setting; with a key, show it; with a key and value, set it."); + spec.addPositional(PositionalParamSpec.builder().index("0").arity("0..1").paramLabel("") + .type(String.class).description("Setting, as section.name (sections: " + String.join(", ", SECTIONS) + ")") + .build()); + spec.addPositional(PositionalParamSpec.builder().index("1..*").arity("0..*").paramLabel("") + .type(String[].class).description("New value; several words are joined with spaces").build()); + command.spec = spec; + return new CommandLine(spec); + } + + @Override + public Integer call() { + PrintWriter out = spec.commandLine().getOut(); + String key = spec.positionalParameters().get(0).getValue(); + String[] value = spec.positionalParameters().get(1).getValue(); + CommandConfig cfg = config.get(); + + if (key == null) { + for (Map.Entry e : cfg.entries().entrySet()) { + out.println(e.getKey() + " = " + e.getValue()); + } + } else if (value == null || value.length == 0) { + String current = cfg.get(key, null); + if (current == null) { + throw new OperationException.NotFound("No such setting: " + key); + } + out.println(current); + } else { + if (!SECTIONS.contains(key.split("\\.")[0]) || !key.contains(".")) { + throw new OperationException.NotFound("Unknown setting: " + key + " (sections: " + + String.join(", ", SECTIONS) + ")"); + } + String joined = String.join(" ", value); + String previous = cfg.set(key, joined); + out.println(previous == null ? "Set '" + key + "' to '" + joined + "'" + : "Updated '" + key + "' from '" + previous + "' to '" + joined + "'"); + } + out.flush(); + return 0; + } +} diff --git a/src/main/java/org/ical4j/command/cli/GlobalOptions.java b/src/main/java/org/ical4j/command/cli/GlobalOptions.java new file mode 100644 index 0000000..762fcd5 --- /dev/null +++ b/src/main/java/org/ical4j/command/cli/GlobalOptions.java @@ -0,0 +1,67 @@ +package org.ical4j.command.cli; + +import net.fortuna.ical4j.util.CompatibilityHints; +import org.ical4j.command.ops.Format; +import picocli.CommandLine; + +/** + * Options accepted by every command in the tree. They are inherited, so they may appear before + * or after the verb and type: {@code ict --format json list collection} and + * {@code ict list collection --format json} are the same. + */ +public class GlobalOptions { + + private String workspace; + + private Format format = Format.TEXT; + + private int verbosity; + + @CommandLine.Option(names = "--workspace", paramLabel = "", scope = CommandLine.ScopeType.INHERIT, + description = "Workspace to act in (default: the active workspace from configuration)") + public void setWorkspace(String workspace) { + this.workspace = workspace; + } + + @CommandLine.Option(names = "--format", paramLabel = "", scope = CommandLine.ScopeType.INHERIT, + description = "Output format: text, json or xml (default: text)") + public void setFormat(Format format) { + this.format = format; + } + + @CommandLine.Option(names = "--lenient", description = "Enable lenient parsing", scope = CommandLine.ScopeType.INHERIT) + public void setRelaxedParsing(boolean relaxedParsing) { + CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, relaxedParsing); + CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, relaxedParsing); + } + + /** + * Declared so that the flag appears in usage help and is accepted by the parser. The level + * itself is applied earlier, from the raw arguments, by {@link LogLevel#configure(String[])}. + */ + @CommandLine.Option(names = {"-v", "--verbose"}, scope = CommandLine.ScopeType.INHERIT, + description = "Increase logging verbosity (-v info, -vv debug, -vvv trace)") + public void setVerbose(boolean[] verbose) { + this.verbosity = verbose.length; + } + + /** As {@link #setVerbose(boolean[])}: accepted here, applied by {@link LogLevel}. */ + @CommandLine.Option(names = {"-q", "--quiet"}, scope = CommandLine.ScopeType.INHERIT, + description = "Log errors only") + public void setQuiet(boolean quiet) { + // handled by LogLevel before parsing + } + + /** The {@code --workspace} value, or {@code null} to use the configured active workspace. */ + public String workspace() { + return workspace; + } + + public Format format() { + return format; + } + + public int verbosity() { + return verbosity; + } +} diff --git a/src/main/java/org/ical4j/command/cli/LogLevel.java b/src/main/java/org/ical4j/command/cli/LogLevel.java new file mode 100644 index 0000000..3b61871 --- /dev/null +++ b/src/main/java/org/ical4j/command/cli/LogLevel.java @@ -0,0 +1,78 @@ +package org.ical4j.command.cli; + +import java.util.Locale; + +/** + * Chooses the slf4j-simple log level before any logger exists. + *

+ * slf4j-simple reads its configuration once, when the first logger is created, and offers no + * API to change levels afterwards. Command classes create loggers in static initialisers as + * picocli instantiates them, which happens before picocli has parsed {@code --verbose}. So the + * level is decided here from the raw arguments and the environment, and published as a system + * property that overrides {@code simplelogger.properties}. + *

+ * Precedence: {@code ICT_LOG_LEVEL} (trace, debug, info, warn, error, off) wins over the flags; + * {@code -v} selects info, {@code -vv} debug, {@code -vvv} trace; {@code -q} selects error; + * otherwise the default from {@code simplelogger.properties} applies. + */ +final class LogLevel { + + static final String ENV_VAR = "ICT_LOG_LEVEL"; + + private static final String PROPERTY = "org.slf4j.simpleLogger.defaultLogLevel"; + + private LogLevel() { + } + + static void configure(String[] args) { + configure(args, System.getenv(ENV_VAR)); + } + + static void configure(String[] args, String envLevel) { + String level = envLevel != null && !envLevel.isBlank() ? envLevel.trim().toLowerCase(Locale.ROOT) + : fromVerbosity(countVerbose(args)); + if (level == null && isQuiet(args)) { + level = "error"; + } + if (level != null) { + System.setProperty(PROPERTY, level); + } + } + + static int countVerbose(String[] args) { + int count = 0; + for (String arg : args) { + if ("--".equals(arg)) { + break; + } + if ("--verbose".equals(arg)) { + count++; + } else if (arg.length() > 1 && arg.charAt(0) == '-' && arg.charAt(1) != '-' + && arg.chars().skip(1).allMatch(c -> c == 'v')) { + count += arg.length() - 1; + } + } + return count; + } + + static boolean isQuiet(String[] args) { + for (String arg : args) { + if ("--".equals(arg)) { + break; + } + if ("-q".equals(arg) || "--quiet".equals(arg)) { + return true; + } + } + return false; + } + + static String fromVerbosity(int count) { + switch (count) { + case 0: return null; + case 1: return "info"; + case 2: return "debug"; + default: return "trace"; + } + } +} diff --git a/src/main/java/org/ical4j/command/cli/Main.java b/src/main/java/org/ical4j/command/cli/Main.java new file mode 100644 index 0000000..6a98c85 --- /dev/null +++ b/src/main/java/org/ical4j/command/cli/Main.java @@ -0,0 +1,122 @@ +package org.ical4j.command.cli; + +import org.ical4j.command.config.CommandConfig; +import org.ical4j.command.mcp.McpCommand; +import org.ical4j.command.ops.Context; +import org.ical4j.command.ops.OperationException; +import org.ical4j.command.ops.Operations; +import org.ical4j.command.ops.Registry; +import org.ical4j.command.ops.Renderer; +import org.ical4j.command.ops.Result; +import picocli.CommandLine; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.util.function.Supplier; + +/** + * The {@code ict} executable. The root command carries the global options; everything under it + * is derived from the operation registry by {@link CommandTree}, apart from {@code config} and + * {@code mcp}, which serves the same registry over MCP. + *

+ * Exit codes: 0 success, 1 operation failure (not found, invalid data, store error), 2 usage + * error. Results go to stdout; diagnostics go to stderr. + */ +@CommandLine.Command(name = "ict", description = "@|bold,fg(104) iCal4j Command-line Tool|@", + scope = CommandLine.ScopeType.INHERIT, mixinStandardHelpOptions = true, versionProvider = VersionProvider.class, + commandListHeading = "%n@|bold,fg(104) Commands:|@%n", + footer = "@|yellow Copyright (c) Ben Fortuna |@", showAtFileInUsageHelp = true) +public class Main extends GlobalOptions { + + static final int OK = 0; + static final int FAILURE = 1; + static final int USAGE = 2; + + public static void main(String[] args) { + LogLevel.configure(args); + System.exit(run(args, System.out, System.err, System.in, CommandConfig::new)); + } + + /** + * Builds the standard tree and runs it. The seam for in-process specs: streams and + * configuration are supplied rather than taken from {@link System}. + */ + public static int run(String[] args, OutputStream out, OutputStream err, InputStream in, + Supplier config) { + return commandLine(Operations.standard(), out, err, in, config).execute(args); + } + + /** + * The command tree for a registry, with output, error and input bound explicitly. + * Configuration is opened on first use, so {@code --help} and {@code --version} touch no files. + */ + public static CommandLine commandLine(Registry registry, OutputStream out, OutputStream err, InputStream in, + Supplier config) { + Main main = new Main(); + Supplier lazyConfig = memoize(config); + CommandLine cli = new CommandLine(main); + CommandTree.attach(cli, registry, (operation, params) -> { + Result result = registry.execute(operation.id(), main.context(lazyConfig, in), params); + cli.getOut().print(new Renderer(true).render(result, main.format())); + cli.getOut().flush(); + return OK; + }); + cli.addSubcommand("config", ConfigCommand.create(lazyConfig)); + // MCP owns stdin, so its handlers get an empty one. + cli.addSubcommand("mcp", McpCommand.create(registry, + () -> main.context(lazyConfig, InputStream.nullInputStream()), in, out)); + // After the subcommands exist: these setters propagate to the whole tree. + cli.setOut(writer(out)); + cli.setErr(writer(err)); + cli.setCaseInsensitiveEnumValuesAllowed(true); + cli.setExecutionExceptionHandler(main::failure); + return cli; + } + + /** The handler context: configuration, with {@code --workspace} applied. */ + private Context context(Supplier config, InputStream in) { + Context.Builder context = config.get().contextBuilder().stdin(() -> in); + if (workspace() != null) { + context.activeWorkspace(workspace()); + } + return context.build(); + } + + /** Maps a failure to an exit code and a stderr diagnostic. stdout is left untouched. */ + private int failure(Exception e, CommandLine command, CommandLine.ParseResult parsed) { + PrintWriter err = command.getErr(); + String message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); + err.println("ict: " + message); + if (verbosity() > 0 || !(e instanceof OperationException)) { + e.printStackTrace(err); + } + if (e instanceof OperationException.Usage) { + err.println("Try '" + command.getCommandSpec().qualifiedName() + " --help' for more information."); + err.flush(); + return USAGE; + } + err.flush(); + return FAILURE; + } + + private static PrintWriter writer(OutputStream stream) { + return new PrintWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8), true); + } + + private static Supplier memoize(Supplier supplier) { + return new Supplier<>() { + private T value; + + @Override + public synchronized T get() { + if (value == null) { + value = supplier.get(); + } + return value; + } + }; + } +} diff --git a/src/main/java/org/ical4j/command/cli/VersionProvider.java b/src/main/java/org/ical4j/command/cli/VersionProvider.java new file mode 100644 index 0000000..47a8982 --- /dev/null +++ b/src/main/java/org/ical4j/command/cli/VersionProvider.java @@ -0,0 +1,16 @@ +package org.ical4j.command.cli; + +import net.fortuna.ical4j.model.Calendar; +import org.ical4j.command.Version; +import picocli.CommandLine; + +public class VersionProvider implements CommandLine.IVersionProvider { + + @Override + public String[] getVersion() { + String ical4jVersion = Calendar.class.getPackage().getImplementationVersion(); + return new String[] {String.format("ict %s (ical4j=%s, java=%s)", Version.get(), + ical4jVersion == null ? "unknown" : ical4jVersion, System.getProperty("java.version")) + }; + } +} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/config/CommandConfig.java b/src/main/java/org/ical4j/command/config/CommandConfig.java similarity index 52% rename from ical4j-command-cli/src/main/java/org/ical4j/command/config/CommandConfig.java rename to src/main/java/org/ical4j/command/config/CommandConfig.java index f81198e..421c06b 100644 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/config/CommandConfig.java +++ b/src/main/java/org/ical4j/command/config/CommandConfig.java @@ -32,7 +32,10 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +import com.electronwill.nightconfig.core.UnmodifiableConfig; import com.electronwill.nightconfig.core.file.FileConfig; +import com.electronwill.nightconfig.toml.TomlFormat; +import org.ical4j.command.ops.Context; import org.ical4j.command.util.Filesystem; import org.ical4j.connector.CalendarCollection; import org.ical4j.connector.CardCollection; @@ -41,23 +44,49 @@ import org.ical4j.connector.local.LocalCardStore; import java.io.File; +import java.util.LinkedHashMap; +import java.util.Map; /** - * Persists command configuration. + * Persists command configuration in {@code /iCal4j/ictrc.toml} and builds the + * {@link Context} that handlers receive. Surfaces construct one of these; handlers never do. */ public class CommandConfig { - public static final CommandConfig INSTANCE = new CommandConfig(); + /** Subdirectory of the data directory that holds the config file and the local stores. */ + public static final String APP_DIR = "iCal4j"; + + private final File appDir; private final FileConfig fileConfig; + /** + * Configuration under the platform data directory (or {@code ICT_DATA_DIR}). + */ public CommandConfig() { - this(FileConfig.builder(new File(Filesystem.getDataDirectory(), "iCal4j/ictrc.toml")) - .defaultResource("/ictrc.default").autosave().sync().build()); + this(new File(Filesystem.getDataDirectory())); + } + + /** + * Configuration under an explicit data directory. + */ + public CommandConfig(File dataDirectory) { + this.appDir = new File(dataDirectory, APP_DIR); + if (!appDir.isDirectory() && !appDir.mkdirs()) { + throw new IllegalStateException("Cannot create application directory " + appDir); + } + // The TOML format is passed explicitly: night-config's format detection probes + // TomlFormat with Class.forName, which a native image cannot see without metadata. + this.fileConfig = FileConfig.builder(new File(appDir, "ictrc.toml"), TomlFormat.instance()) + .defaultResource("/ictrc.default.toml").autosave().sync().build(); + } + + public File dataDirectory() { + return appDir.getParentFile(); } - public CommandConfig(FileConfig fileConfig) { - this.fileConfig = fileConfig; + public File configFile() { + return fileConfig.getFile(); } public String get(String key, String defaultValue) { @@ -72,7 +101,7 @@ public String set(String key, String value) { } public String getUserAgent() { - return get("user.agent", "iCal4j-Command-Line/1.0"); + return get("user.agent", "ict/1.0"); } public String getUserEmail() { @@ -99,18 +128,24 @@ public String setActiveWorkspace(String workspaceId) { return set("workspace.active", workspaceId); } + public File calendarStoreDirectory() { + return new File(appDir, get("store.calendar.path", "calendars")); + } + public ObjectStore getCalendarStore() { - return new LocalCalendarStore(new File(Filesystem.getDataDirectory(), - "iCal4j/" + get("store.calendar.path", "calendars"))); + return new LocalCalendarStore(calendarStoreDirectory()); } public String setCalendarStorePath(String path) { return set("store.calendar.path", path); } + public File cardStoreDirectory() { + return new File(appDir, get("store.card.path", "vcards")); + } + public ObjectStore getCardStore() { - return new LocalCardStore(new File(Filesystem.getDataDirectory(), "iCal4j/" + - get("store.card.path", "vcards"))); + return new LocalCardStore(cardStoreDirectory()); } public String setCardStorePath(String path) { @@ -129,4 +164,45 @@ public String setDefaultContentType(String concept, String contentType) { public String setDefaultContentType(String contentType) { return set("contentType.default", contentType); } + + /** + * The handler context for this configuration: the active workspace, lazily opened local + * stores, and standard input. + */ + public Context context() { + return contextBuilder().build(); + } + + /** + * A context builder populated from this configuration, for surfaces that override the + * workspace or standard input. + */ + public Context.Builder contextBuilder() { + return Context.builder() + .activeWorkspace(getActiveWorkspace()) + .calendarStore(this::getCalendarStore) + .cardStore(this::getCardStore) + .stdin(() -> System.in); + } + + /** + * Every setting as a flat {@code section.key} to value map, in file order. + */ + public Map entries() { + fileConfig.load(); + Map entries = new LinkedHashMap<>(); + flatten("", fileConfig, entries); + return entries; + } + + private static void flatten(String prefix, UnmodifiableConfig config, Map into) { + for (UnmodifiableConfig.Entry e : config.entrySet()) { + Object value = e.getValue(); + if (value instanceof UnmodifiableConfig nested) { + flatten(prefix + e.getKey() + ".", nested, into); + } else { + into.put(prefix + e.getKey(), String.valueOf(value)); + } + } + } } diff --git a/src/main/java/org/ical4j/command/mcp/Contents.java b/src/main/java/org/ical4j/command/mcp/Contents.java new file mode 100644 index 0000000..aedc8c5 --- /dev/null +++ b/src/main/java/org/ical4j/command/mcp/Contents.java @@ -0,0 +1,34 @@ +package org.ical4j.command.mcp; + +import io.modelcontextprotocol.spec.McpSchema; +import org.ical4j.command.ops.Format; +import org.ical4j.command.ops.Renderer; +import org.ical4j.command.ops.Result; + +/** + * Renders operation results as MCP tool results: calendars and cards as iCalendar or vCard text, + * everything else as JSON text. Failures are tool results with {@code isError} set, never + * protocol errors, so the model sees the message and the server keeps running. + */ +final class Contents { + + private Contents() { + } + + static McpSchema.CallToolResult result(Result result) { + Format format = result instanceof Result.CalendarData || result instanceof Result.CardData + ? Format.TEXT : Format.JSON; + return McpSchema.CallToolResult.builder() + // A renderer per call: it initialises its mappers lazily and tool calls may run concurrently. + .addTextContent(new Renderer(false).render(result, format)) + .isError(false) + .build(); + } + + static McpSchema.CallToolResult error(String message) { + return McpSchema.CallToolResult.builder() + .addTextContent(message) + .isError(true) + .build(); + } +} diff --git a/src/main/java/org/ical4j/command/mcp/McpCommand.java b/src/main/java/org/ical4j/command/mcp/McpCommand.java new file mode 100644 index 0000000..4f37985 --- /dev/null +++ b/src/main/java/org/ical4j/command/mcp/McpCommand.java @@ -0,0 +1,134 @@ +package org.ical4j.command.mcp; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.modelcontextprotocol.json.McpJsonMapper; +import io.modelcontextprotocol.json.jackson2.JacksonMcpJsonMapper; +import io.modelcontextprotocol.server.McpServer; +import io.modelcontextprotocol.server.McpSyncServer; +import io.modelcontextprotocol.server.transport.StdioServerTransportProvider; +import io.modelcontextprotocol.spec.McpSchema; +import org.ical4j.command.Version; +import org.ical4j.command.ops.Context; +import org.ical4j.command.ops.Registry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import picocli.CommandLine; +import picocli.CommandLine.Model.CommandSpec; + +import java.io.FilterInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.function.Supplier; + +/** + * {@code ict mcp}: serves the registry as MCP tools over stdio until the client closes stdin. + *

+ * stdout belongs to the protocol for the whole run. The transport holds the only reference to + * the real stdout; {@link System#out} and picocli's output are pointed at stderr, and logging + * already goes there, so a stray print cannot corrupt the stream. + */ +public final class McpCommand implements Callable { + + private static final Logger LOG = LoggerFactory.getLogger(McpCommand.class); + + private final Registry registry; + private final Supplier context; + private final InputStream in; + private final OutputStream out; + private CommandSpec spec; + + private McpCommand(Registry registry, Supplier context, InputStream in, OutputStream out) { + this.registry = registry; + this.context = context; + this.in = in; + this.out = out; + } + + /** + * @param context supplies a fresh handler context per tool call; its stdin must not be the + * protocol stream + * @param in the protocol input, normally {@link System#in} + * @param out the protocol output, normally {@link System#out} + */ + public static CommandLine create(Registry registry, Supplier context, InputStream in, OutputStream out) { + McpCommand command = new McpCommand(registry, context, in, out); + CommandSpec spec = CommandSpec.wrapWithoutInspection(command).name("mcp"); + spec.usageMessage().description("Serve ict operations as Model Context Protocol tools over stdio", + "Runs until the client closes standard input. Logs go to standard error."); + command.spec = spec; + return new CommandLine(spec); + } + + @Override + public Integer call() throws InterruptedException { + CommandLine root = spec.root().commandLine(); + root.setOut(root.getErr()); + PrintStream systemOut = System.out; + if (out == systemOut) { + System.setOut(System.err); + } + try { + CountDownLatch closed = new CountDownLatch(1); + McpJsonMapper json = new JacksonMcpJsonMapper(new ObjectMapper()); + StdioServerTransportProvider transport = new StdioServerTransportProvider(json, new EofSignal(in, closed), out); + McpSyncServer server = McpServer.sync(transport) + .serverInfo("ict", Version.get()) + .capabilities(McpSchema.ServerCapabilities.builder().tools(false).build()) + .jsonMapper(json) + .tools(Tools.specifications(registry, context)) + .build(); + LOG.info("MCP server ready with {} tools", server.listTools().size()); + closed.await(); + LOG.info("Client closed the stream; shutting down"); + server.close(); + return 0; + } finally { + if (out == systemOut) { + System.setOut(systemOut); + } + } + } + + /** Counts down when the wrapped stream ends or fails, which is how a stdio client disconnects. */ + private static final class EofSignal extends FilterInputStream { + + private final CountDownLatch closed; + + EofSignal(InputStream in, CountDownLatch closed) { + super(in); + this.closed = closed; + } + + @Override + public int read() throws IOException { + return watch(() -> super.read()); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + return watch(() -> super.read(b, off, len)); + } + + private int watch(Read read) throws IOException { + try { + int n = read.run(); + if (n < 0) { + closed.countDown(); + } + return n; + } catch (IOException e) { + closed.countDown(); + throw e; + } + } + + @FunctionalInterface + private interface Read { + int run() throws IOException; + } + } +} diff --git a/src/main/java/org/ical4j/command/mcp/Tools.java b/src/main/java/org/ical4j/command/mcp/Tools.java new file mode 100644 index 0000000..0ad82c9 --- /dev/null +++ b/src/main/java/org/ical4j/command/mcp/Tools.java @@ -0,0 +1,148 @@ +package org.ical4j.command.mcp; + +import io.modelcontextprotocol.server.McpServerFeatures.SyncToolSpecification; +import io.modelcontextprotocol.spec.McpSchema; +import org.ical4j.command.ops.Context; +import org.ical4j.command.ops.Operation; +import org.ical4j.command.ops.OperationException; +import org.ical4j.command.ops.OperationId; +import org.ical4j.command.ops.Param; +import org.ical4j.command.ops.Params; +import org.ical4j.command.ops.Registry; +import org.ical4j.command.ops.Surface; +import org.ical4j.command.vocab.Verb; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Supplier; + +/** + * The MCP view of the registry: one tool per MCP-exposed operation, named + * {@code _}, with an input schema derived from the parameter descriptors. Tools are + * registered programmatically; nothing is discovered by annotation or reflection. + */ +public final class Tools { + + private static final Logger LOG = LoggerFactory.getLogger(Tools.class); + + private static final Set READ_ONLY = Set.of(Verb.LIST, Verb.GET, Verb.EXPORT, Verb.VALIDATE, Verb.FILTER); + + private static final Set DESTRUCTIVE = Set.of(Verb.REMOVE, Verb.MOVE, Verb.UPDATE); + + private Tools() { + } + + /** The tool name for an operation: {@code list_event}, {@code import_calendar}. */ + public static String name(OperationId id) { + return id.verbKey() + "_" + id.subjectKey(); + } + + /** + * Tool specifications for every MCP-exposed operation, in registry order. Each call builds a + * fresh context and runs the operation through the registry. + * + * @throws IllegalStateException if two exposed operations would share a tool name + */ + public static List specifications(Registry registry, Supplier context) { + Map byName = new LinkedHashMap<>(); + List specs = new ArrayList<>(); + for (Operation op : registry.forSurface(Surface.MCP)) { + String name = name(op.id()); + Operation clash = byName.putIfAbsent(name, op); + if (clash != null) { + throw new IllegalStateException("MCP cannot distinguish '" + clash.id() + "' from '" + op.id() + + "': both are tool " + name); + } + specs.add(SyncToolSpecification.builder() + .tool(tool(op)) + .callHandler((exchange, request) -> call(registry, op, context, request.arguments())) + .build()); + } + return specs; + } + + static McpSchema.Tool tool(Operation op) { + Verb verb = op.id().verb(); + return McpSchema.Tool.builder(name(op.id()), inputSchema(op.params())) + .description(op.description()) + .annotations(McpSchema.ToolAnnotations.builder() + .readOnlyHint(READ_ONLY.contains(verb)) + .destructiveHint(DESTRUCTIVE.contains(verb)) + .openWorldHint(false) + .build()) + .build(); + } + + /** A JSON schema object for the descriptors. Unknown properties are rejected. */ + static Map inputSchema(List params) { + Map properties = new LinkedHashMap<>(); + List required = new ArrayList<>(); + for (Param p : params) { + Map property = new LinkedHashMap<>(valueSchema(p)); + if (p.multiple()) { + property = new LinkedHashMap<>(Map.of("type", "array", "items", property)); + } + property.put("description", p.description()); + if (p.defaultValue() != null) { + Object value = typed(p, p.defaultValue()); + property.put("default", p.multiple() ? List.of(value) : value); + } + properties.put(p.name(), property); + if (p.required()) { + required.add(p.name()); + } + } + Map schema = new LinkedHashMap<>(); + schema.put("type", "object"); + schema.put("properties", properties); + schema.put("required", required); + schema.put("additionalProperties", false); + return schema; + } + + private static Map valueSchema(Param p) { + switch (p.type()) { + case INTEGER: + return Map.of("type", "integer"); + case BOOLEAN: + return Map.of("type", "boolean"); + case ENUM: + return Map.of("type", "string", "enum", p.choices()); + case PATH: + case STRING: + default: + return Map.of("type", "string"); + } + } + + private static Object typed(Param p, String value) { + switch (p.type()) { + case INTEGER: + return Integer.valueOf(value); + case BOOLEAN: + return Boolean.valueOf(value); + default: + return value; + } + } + + private static McpSchema.CallToolResult call(Registry registry, Operation op, Supplier context, + Map arguments) { + try { + Params params = Params.of(arguments == null ? Map.of() : arguments); + LOG.debug("Calling {} with {}", op.id(), params); + return Contents.result(registry.execute(op.id(), context.get(), params)); + } catch (OperationException e) { + LOG.debug("{} failed: {}", op.id(), e.getMessage()); + return Contents.error(e.getMessage()); + } catch (RuntimeException e) { + LOG.error("{} failed unexpectedly", op.id(), e); + return Contents.error(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); + } + } +} diff --git a/src/main/java/org/ical4j/command/ops/CalendarOperations.java b/src/main/java/org/ical4j/command/ops/CalendarOperations.java new file mode 100644 index 0000000..d8d2325 --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/CalendarOperations.java @@ -0,0 +1,127 @@ +package org.ical4j.command.ops; + +import net.fortuna.ical4j.model.Calendar; +import net.fortuna.ical4j.model.Component; +import net.fortuna.ical4j.model.ComponentContainer; +import net.fortuna.ical4j.model.Parameter; +import net.fortuna.ical4j.model.Property; +import net.fortuna.ical4j.model.TimeZone; +import net.fortuna.ical4j.model.TimeZoneRegistry; +import net.fortuna.ical4j.model.TimeZoneRegistryFactory; +import net.fortuna.ical4j.model.component.VTimeZone; +import net.fortuna.ical4j.model.property.Uid; +import org.ical4j.command.vocab.Locus; +import org.ical4j.command.vocab.SerializationFamily; +import org.ical4j.command.vocab.Verb; +import org.ical4j.connector.CalendarCollection; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * Moving iCalendar data into and out of a collection. + */ +final class CalendarOperations { + + private static final Param UID = Param.string("uid", "UID of one stored calendar object"); + + private CalendarOperations() { + } + + static List all() { + return List.of(importCalendar(), exportCalendar(), removeCalendar()); + } + + static Operation importCalendar() { + return Operation.define(Verb.IMPORT, SerializationFamily.CALENDAR, Locus.COLLECTION) + .description("Import iCalendar data into a collection, merging by UID") + .params(Stores.COLLECTION, Inputs.FILE) + .handler((context, params) -> { + CalendarCollection collection = Stores.calendarCollection(context, params.require("collection")); + // The connector's merge splits the calendar by UID and fails with a + // NullPointerException when a component references a TZID the calendar + // carries no VTIMEZONE for, so complete the time zones first. + Calendar calendar = withTimeZones(Inputs.calendar(context, params)); + Uid[] uids = Stores.call(() -> collection.merge(calendar)); + return new Result.Identifiers(Arrays.stream(uids).map(Uid::getValue).toList()); + }) + .build(); + } + + static Operation exportCalendar() { + return Operation.define(Verb.EXPORT, SerializationFamily.CALENDAR, Locus.COLLECTION) + .description("Export one stored calendar object by UID, or the whole collection as one calendar," + + " with a VTIMEZONE for every TZID it references") + .params(Stores.COLLECTION, UID) + .handler((context, params) -> { + CalendarCollection collection = Stores.calendarCollection(context, params.require("collection")); + Calendar calendar = params.string("uid").isPresent() + ? Stores.call(() -> collection.getCalendar(params.require("uid"))) + : Stores.call(collection::export); + if (calendar == null) { + throw new OperationException.NotFound("No such calendar: " + params.string("uid", "")); + } + return new Result.CalendarData(withTimeZones(calendar)); + }) + .build(); + } + + /** + * Adds a VTIMEZONE from ical4j's registry for each TZID referenced without one, so the + * exported stream stands alone. Unknown TZIDs are left as they are. + */ + static Calendar withTimeZones(Calendar calendar) { + Set defined = new HashSet<>(); + Set referenced = new LinkedHashSet<>(); + collectTzIds(calendar.getComponents(), defined, referenced); + referenced.removeAll(defined); + if (referenced.isEmpty()) { + return calendar; + } + TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); + Calendar result = calendar.copy(); + for (String tzid : referenced) { + TimeZone tz = registry.getTimeZone(tzid); + if (tz != null) { + result.add(tz.getVTimeZone()); + } + } + return result; + } + + private static void collectTzIds(List components, Set defined, Set referenced) { + for (Component c : components) { + if (c instanceof VTimeZone) { + c.getProperty(Property.TZID).ifPresent(p -> defined.add(p.getValue())); + continue; + } + for (Property p : c.getProperties()) { + p.getParameter(Parameter.TZID).ifPresent(tzid -> referenced.add(tzid.getValue())); + } + if (c instanceof ComponentContainer container) { + collectTzIds(container.getComponents(), defined, referenced); + } + } + } + + static Operation removeCalendar() { + return Operation.define(Verb.REMOVE, SerializationFamily.CALENDAR, Locus.COLLECTION) + .description("Remove one stored calendar object by UID") + .params(Stores.COLLECTION, UID.asRequired()) + .handler((context, params) -> { + CalendarCollection collection = Stores.calendarCollection(context, params.require("collection")); + String uid = params.require("uid"); + // The connector's removeCalendar(uid) indexes into an empty list when the UID is + // unknown, so remove through removeAll and inspect the result. + List removed = Stores.call(() -> collection.removeAll(uid)); + if (removed.isEmpty()) { + throw new OperationException.NotFound("No such calendar: " + uid); + } + return new Result.Status("Removed calendar '" + uid + "'"); + }) + .build(); + } +} diff --git a/src/main/java/org/ical4j/command/ops/CardOperations.java b/src/main/java/org/ical4j/command/ops/CardOperations.java new file mode 100644 index 0000000..62a57fb --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/CardOperations.java @@ -0,0 +1,74 @@ +package org.ical4j.command.ops; + +import net.fortuna.ical4j.vcard.VCard; +import net.fortuna.ical4j.vcard.property.Uid; +import org.ical4j.command.vocab.Locus; +import org.ical4j.command.vocab.SerializationFamily; +import org.ical4j.command.vocab.Verb; +import org.ical4j.connector.CardCollection; + +import java.util.Arrays; +import java.util.List; + +/** + * Moving vCard data into and out of a collection. + */ +final class CardOperations { + + private static final Param UID = Param.string("uid", "UID of one stored card"); + + private CardOperations() { + } + + static List all() { + return List.of(importCard(), exportCard(), removeCard()); + } + + static Operation importCard() { + return Operation.define(Verb.IMPORT, SerializationFamily.CARD, Locus.COLLECTION) + .description("Import vCard data into a collection, merging by UID") + .params(Stores.COLLECTION, Inputs.FILE) + .handler((context, params) -> { + CardCollection collection = Stores.cardCollection(context, params.require("collection")); + VCard card = Inputs.card(context, params); + Uid[] uids = Stores.call(() -> collection.merge(card)); + return new Result.Identifiers(Arrays.stream(uids).map(Uid::getValue).toList()); + }) + .build(); + } + + static Operation exportCard() { + return Operation.define(Verb.EXPORT, SerializationFamily.CARD, Locus.COLLECTION) + .description("Export one stored card by UID, or the whole collection as one vCard") + .params(Stores.COLLECTION, UID) + .handler((context, params) -> { + CardCollection collection = Stores.cardCollection(context, params.require("collection")); + VCard card = params.string("uid").isPresent() + ? Stores.call(() -> collection.getCard(params.require("uid"))) + : Stores.call(collection::export); + if (card == null) { + throw new OperationException.NotFound("No such card: " + params.string("uid", "")); + } + return new Result.CardData(card); + }) + .build(); + } + + static Operation removeCard() { + return Operation.define(Verb.REMOVE, SerializationFamily.CARD, Locus.COLLECTION) + .description("Remove one stored card by UID") + .params(Stores.COLLECTION, UID.asRequired()) + .handler((context, params) -> { + CardCollection collection = Stores.cardCollection(context, params.require("collection")); + String uid = params.require("uid"); + // The connector's removeCard(uid) indexes into an empty list when the UID is + // unknown, so remove through removeAll and inspect the result. + List removed = Stores.call(() -> collection.removeAll(uid)); + if (removed.isEmpty()) { + throw new OperationException.NotFound("No such card: " + uid); + } + return new Result.Status("Removed card '" + uid + "'"); + }) + .build(); + } +} diff --git a/src/main/java/org/ical4j/command/ops/CollectionOperations.java b/src/main/java/org/ical4j/command/ops/CollectionOperations.java new file mode 100644 index 0000000..15e3585 --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/CollectionOperations.java @@ -0,0 +1,120 @@ +package org.ical4j.command.ops; + +import org.ical4j.command.vocab.Locus; +import org.ical4j.command.vocab.SerializationFamily; +import org.ical4j.command.vocab.Verb; +import org.ical4j.connector.ObjectCollection; +import org.ical4j.connector.ObjectStore; +import org.ical4j.connector.local.LocalCalendarCollection; +import org.ical4j.connector.local.LocalCardCollection; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Operations on collections within the active workspace. + */ +final class CollectionOperations { + + private static final Param DESCRIPTION = Param.string("description", "Description of the collection"); + + private CollectionOperations() { + } + + static List all() { + return List.of(add(), get(), remove(), list()); + } + + static Operation add() { + return Operation.define(Verb.ADD, Locus.COLLECTION, Locus.WORKSPACE) + .description("Add a new collection to the active workspace") + .params(Stores.COLLECTION, Stores.TYPE, DESCRIPTION) + .handler((context, params) -> { + String name = params.require("collection"); + SerializationFamily family = Stores.family(params); + ObjectStore> store = Stores.store(context, family); + if (Stores.exists(store, name, context.activeWorkspace())) { + throw new OperationException.AlreadyExists("Collection already exists: " + name); + } + ObjectCollection created = Stores.call(() -> store.addCollection(name, context.activeWorkspace())); + // The two-argument addCollection leaves the display name unset; local + // collections expose it as a setter, so name them after their directory. + String description = params.string("description", null); + Stores.call(() -> { + if (created instanceof LocalCalendarCollection local) { + local.setDisplayName(name); + if (description != null) { + local.setDescription(description); + } + } else if (created instanceof LocalCardCollection local) { + local.setDisplayName(name); + if (description != null) { + local.setDescription(description); + } + } + return null; + }); + return new Result.Status("Added " + family.key() + " collection '" + name + "'"); + }) + .build(); + } + + static Operation get() { + return Operation.define(Verb.GET, Locus.COLLECTION, Locus.WORKSPACE) + .description("Describe a collection in the active workspace") + .params(Stores.COLLECTION, Stores.TYPE) + .handler((context, params) -> { + String name = params.require("collection"); + SerializationFamily family = Stores.family(params); + ObjectCollection collection = Stores.collection(Stores.store(context, family), name, + context.activeWorkspace()); + return describe(name, family, collection); + }) + .build(); + } + + static Operation remove() { + return Operation.define(Verb.REMOVE, Locus.COLLECTION, Locus.WORKSPACE) + .description("Remove a collection and everything in it from the active workspace") + .params(Stores.COLLECTION, Stores.TYPE) + .handler((context, params) -> { + String name = params.require("collection"); + SerializationFamily family = Stores.family(params); + ObjectCollection collection = Stores.collection(Stores.store(context, family), name, + context.activeWorkspace()); + Stores.call(() -> { + collection.delete(); + return null; + }); + return new Result.Status("Removed " + family.key() + " collection '" + name + "'"); + }) + .build(); + } + + static Operation list() { + return Operation.define(Verb.LIST, Locus.COLLECTION, Locus.WORKSPACE) + .description("List the collections in the active workspace") + .handler((context, params) -> { + List items = new ArrayList<>(); + for (ObjectCollection c : Stores.collections(context.calendarStore(), context.activeWorkspace())) { + items.add(describe(c.getDisplayName(), SerializationFamily.CALENDAR, c)); + } + for (ObjectCollection c : Stores.collections(context.cardStore(), context.activeWorkspace())) { + items.add(describe(c.getDisplayName(), SerializationFamily.CARD, c)); + } + return new Result.Descriptors(items); + }) + .build(); + } + + private static Result.Descriptor describe(String name, SerializationFamily family, ObjectCollection collection) { + Map attributes = new LinkedHashMap<>(); + attributes.put("name", name == null ? "" : name); + attributes.put("type", family.key()); + attributes.put("description", collection.getDescription() == null ? "" : collection.getDescription()); + attributes.put("objects", String.valueOf(Stores.call(() -> collection.listObjectUIDs().size()))); + return new Result.Descriptor(attributes); + } +} diff --git a/src/main/java/org/ical4j/command/ops/Context.java b/src/main/java/org/ical4j/command/ops/Context.java new file mode 100644 index 0000000..284cbea --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Context.java @@ -0,0 +1,96 @@ +package org.ical4j.command.ops; + +import org.ical4j.connector.CalendarCollection; +import org.ical4j.connector.CardCollection; +import org.ical4j.connector.ObjectStore; + +import java.io.InputStream; +import java.util.Objects; +import java.util.function.Supplier; + +/** + * What a handler may touch: the stores, the active workspace and standard input. Surfaces build + * one from configuration; specs build one around in-memory or temp-dir stores. Handlers never + * read the configuration singleton. + */ +public final class Context { + + private final String activeWorkspace; + private final Supplier> calendarStore; + private final Supplier> cardStore; + private final Supplier stdin; + + private Context(Builder b) { + this.activeWorkspace = Objects.requireNonNull(b.activeWorkspace, "activeWorkspace"); + this.calendarStore = b.calendarStore; + this.cardStore = b.cardStore; + this.stdin = b.stdin; + } + + public static Builder builder() { + return new Builder(); + } + + public String activeWorkspace() { + return activeWorkspace; + } + + public ObjectStore calendarStore() { + if (calendarStore == null) { + throw new OperationException("No calendar store is configured"); + } + return calendarStore.get(); + } + + public ObjectStore cardStore() { + if (cardStore == null) { + throw new OperationException("No card store is configured"); + } + return cardStore.get(); + } + + public InputStream stdin() { + return stdin == null ? InputStream.nullInputStream() : stdin.get(); + } + + public static final class Builder { + private String activeWorkspace = "default"; + private Supplier> calendarStore; + private Supplier> cardStore; + private Supplier stdin; + + public Builder activeWorkspace(String workspace) { + this.activeWorkspace = workspace; + return this; + } + + public Builder calendarStore(ObjectStore store) { + this.calendarStore = () -> store; + return this; + } + + public Builder calendarStore(Supplier> store) { + this.calendarStore = store; + return this; + } + + public Builder cardStore(ObjectStore store) { + this.cardStore = () -> store; + return this; + } + + public Builder cardStore(Supplier> store) { + this.cardStore = store; + return this; + } + + public Builder stdin(Supplier stdin) { + this.stdin = stdin; + return this; + } + + public Context build() { + return new Context(this); + } + } +} diff --git a/src/main/java/org/ical4j/command/ops/Format.java b/src/main/java/org/ical4j/command/ops/Format.java new file mode 100644 index 0000000..d71b065 --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Format.java @@ -0,0 +1,13 @@ +package org.ical4j.command.ops; + +/** + * Output representations a surface can ask a {@link Renderer} for. + */ +public enum Format { + /** Human-readable: iCalendar or vCard for data, aligned columns for lists, plain lines otherwise. */ + TEXT, + /** jCal (RFC 7265) and jCard (RFC 7095) for data, plain JSON objects and arrays otherwise. */ + JSON, + /** xCal (RFC 6321) and xCard (RFC 6351) for calendar and card data only. */ + XML +} diff --git a/src/main/java/org/ical4j/command/ops/Handler.java b/src/main/java/org/ical4j/command/ops/Handler.java new file mode 100644 index 0000000..307cde7 --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Handler.java @@ -0,0 +1,11 @@ +package org.ical4j.command.ops; + +/** + * The executable part of an operation. Implementations return a structured result, throw an + * {@link OperationException}, and never write to stdout or stderr. + */ +@FunctionalInterface +public interface Handler { + + Result apply(Context context, Params params); +} diff --git a/src/main/java/org/ical4j/command/ops/Inputs.java b/src/main/java/org/ical4j/command/ops/Inputs.java new file mode 100644 index 0000000..c5bee11 --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Inputs.java @@ -0,0 +1,58 @@ +package org.ical4j.command.ops; + +import net.fortuna.ical4j.data.CalendarBuilder; +import net.fortuna.ical4j.data.ParserException; +import net.fortuna.ical4j.model.Calendar; +import net.fortuna.ical4j.vcard.VCard; +import net.fortuna.ical4j.vcard.VCardBuilder; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.util.Optional; + +/** + * Reads calendar and card input for handlers: from the {@code file} parameter when present, + * otherwise from the context's standard input. + */ +final class Inputs { + + static final Param FILE = Param.path("file", "Read input from this file instead of standard input"); + + private Inputs() { + } + + static Calendar calendar(Context context, Params params) { + try { + Optional file = params.path("file"); + if (file.isPresent()) { + try (InputStream in = Files.newInputStream(file.get())) { + return new CalendarBuilder().build(in); + } + } + return new CalendarBuilder().build(context.stdin()); + } catch (NoSuchFileException e) { + throw new OperationException.NotFound("No such file: " + e.getFile()); + } catch (IOException | ParserException e) { + throw new OperationException.InvalidData("Cannot parse calendar input: " + e.getMessage(), e); + } + } + + static VCard card(Context context, Params params) { + try { + Optional file = params.path("file"); + if (file.isPresent()) { + try (InputStream in = Files.newInputStream(file.get())) { + return new VCardBuilder(in).build(); + } + } + return new VCardBuilder(context.stdin()).build(); + } catch (NoSuchFileException e) { + throw new OperationException.NotFound("No such file: " + e.getFile()); + } catch (IOException | ParserException e) { + throw new OperationException.InvalidData("Cannot parse card input: " + e.getMessage(), e); + } + } +} diff --git a/src/main/java/org/ical4j/command/ops/ListOperations.java b/src/main/java/org/ical4j/command/ops/ListOperations.java new file mode 100644 index 0000000..9993162 --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/ListOperations.java @@ -0,0 +1,98 @@ +package org.ical4j.command.ops; + +import net.fortuna.ical4j.model.Calendar; +import net.fortuna.ical4j.model.Component; +import net.fortuna.ical4j.model.Property; +import net.fortuna.ical4j.model.component.CalendarComponent; +import net.fortuna.ical4j.vcard.VCard; +import org.ical4j.command.vocab.EntityType; +import org.ical4j.command.vocab.Locus; +import org.ical4j.command.vocab.Verb; +import org.ical4j.connector.CalendarCollection; +import org.ical4j.connector.CardCollection; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Listing entities within a collection. Calendar-backed types map to their iCalendar + * component; {@code entity} lists the cards in a card collection. + */ +final class ListOperations { + + /** Entity types listed so far and the component that carries them. */ + static final Map COMPONENTS = Map.of( + EntityType.EVENT, Component.VEVENT, + EntityType.ACTION, Component.VTODO, + EntityType.NOTE, Component.VJOURNAL); + + private ListOperations() { + } + + static List all() { + List ops = new ArrayList<>(); + for (EntityType type : List.of(EntityType.EVENT, EntityType.ACTION, EntityType.NOTE)) { + ops.add(listComponents(type)); + } + ops.add(listEntities()); + return ops; + } + + static Operation listComponents(EntityType type) { + String component = COMPONENTS.get(type); + return Operation.define(Verb.LIST, type, Locus.COLLECTION) + .description("List the " + type.key() + "s in a collection") + .params(Stores.COLLECTION) + .handler((context, params) -> { + CalendarCollection collection = Stores.calendarCollection(context, params.require("collection")); + List calendars = Stores.call(collection::getAll); + List items = new ArrayList<>(); + for (Calendar calendar : calendars) { + for (CalendarComponent c : calendar.getComponents()) { + if (component.equals(c.getName())) { + items.add(describe(c)); + } + } + } + return new Result.Descriptors(items); + }) + .build(); + } + + static Operation listEntities() { + return Operation.define(Verb.LIST, EntityType.ENTITY, Locus.COLLECTION) + .description("List the entities (cards) in a collection") + .params(Stores.COLLECTION) + .handler((context, params) -> { + CardCollection collection = Stores.cardCollection(context, params.require("collection")); + List cards = Stores.call(collection::getAll); + List items = new ArrayList<>(); + for (VCard card : cards) { + Map attributes = new LinkedHashMap<>(); + attributes.put("uid", Stores.call(() -> card.getUid().getValue())); + attributes.put("name", card.getEntities().stream() + .flatMap(e -> e.getProperty("FN").stream()) + .map(Property::getValue).findFirst().orElse("")); + items.add(new Result.Descriptor(attributes)); + } + return new Result.Descriptors(items); + }) + .build(); + } + + private static Result.Descriptor describe(CalendarComponent c) { + Map attributes = new LinkedHashMap<>(); + attributes.put("uid", c.getUid().map(Property::getValue).orElse("")); + attributes.put("summary", value(c, "SUMMARY")); + attributes.put("start", value(c, "DTSTART")); + return new Result.Descriptor(attributes); + } + + private static String value(CalendarComponent c, String property) { + Optional p = c.getProperty(property); + return p.map(Property::getValue).orElse(""); + } +} diff --git a/src/main/java/org/ical4j/command/ops/Operation.java b/src/main/java/org/ical4j/command/ops/Operation.java new file mode 100644 index 0000000..ed002b1 --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Operation.java @@ -0,0 +1,97 @@ +package org.ical4j.command.ops; + +import org.ical4j.command.vocab.Locus; +import org.ical4j.command.vocab.Subject; +import org.ical4j.command.vocab.Verb; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +/** + * One registry entry: identity, parameters, handler, and which surfaces expose it. + * + * @param id the (verb, subject, locus) tuple + * @param description one sentence, used for CLI help and the MCP tool description + * @param params ordered parameter descriptors, names unique + * @param exposure surfaces that expose this operation + * @param handler the implementation + */ +public record Operation(OperationId id, String description, List params, Set exposure, Handler handler) { + + public Operation { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(description, "description"); + Objects.requireNonNull(handler, "handler"); + params = List.copyOf(params); + exposure = exposure.isEmpty() ? EnumSet.noneOf(Surface.class) : EnumSet.copyOf(exposure); + Set names = new HashSet<>(); + for (Param p : params) { + if (!names.add(p.name())) { + throw new IllegalArgumentException("Duplicate parameter '" + p.name() + "' on " + id); + } + } + if (description.isBlank()) { + throw new IllegalArgumentException("Operation " + id + " needs a description"); + } + } + + public static Builder define(Verb verb, Subject subject, Locus locus) { + return new Builder(OperationId.of(verb, subject, locus)); + } + + public boolean exposedTo(Surface surface) { + return exposure.contains(surface); + } + + /** Resolves defaults and required checks, then runs the handler. */ + public Result execute(Context context, Params params) { + return handler.apply(context, params.resolve(this.params)); + } + + public static final class Builder { + private final OperationId id; + private String description = ""; + private final List params = new ArrayList<>(); + private final Set exposure = EnumSet.allOf(Surface.class); + private Handler handler; + + private Builder(OperationId id) { + this.id = id; + } + + public Builder description(String description) { + this.description = description; + return this; + } + + public Builder param(Param param) { + params.add(param); + return this; + } + + public Builder params(Param... params) { + this.params.addAll(List.of(params)); + return this; + } + + /** Restricts exposure; the default is every surface. */ + public Builder only(Surface... surfaces) { + exposure.clear(); + exposure.addAll(List.of(surfaces)); + return this; + } + + public Builder handler(Handler handler) { + this.handler = handler; + return this; + } + + public Operation build() { + return new Operation(id, description, params, exposure, handler); + } + } +} diff --git a/src/main/java/org/ical4j/command/ops/OperationException.java b/src/main/java/org/ical4j/command/ops/OperationException.java new file mode 100644 index 0000000..d50f7c5 --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/OperationException.java @@ -0,0 +1,51 @@ +package org.ical4j.command.ops; + +/** + * Typed failure of an operation. Surfaces map each subclass to their own convention: the CLI to + * an exit code and a stderr line, MCP to an {@code isError} tool result. + */ +public class OperationException extends RuntimeException { + + public OperationException(String message) { + super(message); + } + + public OperationException(String message, Throwable cause) { + super(message, cause); + } + + /** The named item or locus does not exist. */ + public static class NotFound extends OperationException { + public NotFound(String message) { + super(message); + } + } + + /** The item or locus already exists and the operation does not replace. */ + public static class AlreadyExists extends OperationException { + public AlreadyExists(String message) { + super(message); + } + } + + /** Parameters were missing or malformed. Surfaces treat this as a usage error. */ + public static class Usage extends OperationException { + public Usage(String message) { + super(message); + } + } + + /** Input data failed to parse or validate. */ + public static class InvalidData extends OperationException { + public InvalidData(String message, Throwable cause) { + super(message, cause); + } + } + + /** The backing store failed. */ + public static class Store extends OperationException { + public Store(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/src/main/java/org/ical4j/command/ops/OperationId.java b/src/main/java/org/ical4j/command/ops/OperationId.java new file mode 100644 index 0000000..2c536bc --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/OperationId.java @@ -0,0 +1,79 @@ +package org.ical4j.command.ops; + +import org.ical4j.command.vocab.EntityType; +import org.ical4j.command.vocab.Locus; +import org.ical4j.command.vocab.SerializationFamily; +import org.ical4j.command.vocab.Subject; +import org.ical4j.command.vocab.Verb; + +import java.util.Locale; +import java.util.Objects; +import java.util.stream.Stream; + +/** + * The (verb, subject, locus) identity of an operation. + */ +public record OperationId(Verb verb, Subject subject, Locus locus) { + + public OperationId { + Objects.requireNonNull(verb, "verb"); + Objects.requireNonNull(subject, "subject"); + Objects.requireNonNull(locus, "locus"); + if (subject instanceof Locus l && !l.isSubject()) { + throw new IllegalArgumentException("Locus " + l + " cannot be the subject of an operation"); + } + } + + public static OperationId of(Verb verb, Subject subject, Locus locus) { + return new OperationId(verb, subject, locus); + } + + /** + * Parses the {@link #toString()} form: {@code "list event in collection"} or + * {@code "generate event"} (locus {@link Locus#NONE}). + * + * @throws IllegalArgumentException if any word is not in the vocabulary + */ + public static OperationId parse(String text) { + String[] words = text.trim().split("\\s+"); + if (words.length != 2 && !(words.length == 4 && "in".equals(words[2]))) { + throw new IllegalArgumentException("Expected ' [in ]': " + text); + } + Verb verb = enumFor(Verb.class, words[0]); + Subject subject = subjectFor(words[1]); + Locus locus = words.length == 4 ? enumFor(Locus.class, words[3]) : Locus.NONE; + return new OperationId(verb, subject, locus); + } + + /** Resolves a subject key across entity types, serialization families and container loci. */ + public static Subject subjectFor(String key) { + return Stream.concat(Stream.concat(Stream.of(EntityType.values()), Stream.of(SerializationFamily.values())), + Stream.of(Locus.values()).filter(Locus::isSubject)) + .filter(s -> s.key().equals(key)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Unknown subject: " + key)); + } + + private static > E enumFor(Class type, String key) { + try { + return Enum.valueOf(type, key.toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Unknown " + type.getSimpleName().toLowerCase(Locale.ROOT) + ": " + key); + } + } + + public String verbKey() { + return verb.name().toLowerCase(Locale.ROOT); + } + + public String subjectKey() { + return subject.key(); + } + + /** CLI-style rendering: {@code list event in collection}. */ + @Override + public String toString() { + return locus == Locus.NONE ? verbKey() + " " + subjectKey() + : verbKey() + " " + subjectKey() + " in " + locus.key(); + } +} diff --git a/src/main/java/org/ical4j/command/ops/Operations.java b/src/main/java/org/ical4j/command/ops/Operations.java new file mode 100644 index 0000000..812ece3 --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Operations.java @@ -0,0 +1,22 @@ +package org.ical4j.command.ops; + +/** + * Assembles the standard registry: every admitted operation, in the order the surfaces list + * them. Handlers are contributed per subject from the {@code ops} subpackages as they are + * re-admitted (see {@code docs/dropped-commands.md}); each contribution arrives with a Spock + * spec that names its tuple, which {@code RegistryConformanceTest} enforces. + */ +public final class Operations { + + private Operations() { + } + + public static Registry standard() { + return Registry.builder() + .addAll(CollectionOperations.all()) + .addAll(CalendarOperations.all()) + .addAll(CardOperations.all()) + .addAll(ListOperations.all()) + .build(); + } +} diff --git a/src/main/java/org/ical4j/command/ops/Param.java b/src/main/java/org/ical4j/command/ops/Param.java new file mode 100644 index 0000000..7909365 --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Param.java @@ -0,0 +1,78 @@ +package org.ical4j.command.ops; + +import java.util.List; +import java.util.Objects; + +/** + * A surface-neutral parameter descriptor. + * + * @param name the parameter name; the CLI exposes {@code --name}, MCP a property {@code name} + * @param type the value type + * @param required whether a value must be supplied when no default exists + * @param defaultValue the default as a string, or {@code null} + * @param description help text + * @param multiple whether the parameter accepts a list of values + * @param choices the permitted values for {@link ParamType#ENUM}, otherwise empty + */ +public record Param(String name, ParamType type, boolean required, String defaultValue, String description, + boolean multiple, List choices) { + + public Param { + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(description, "description"); + choices = choices == null ? List.of() : List.copyOf(choices); + if (!name.matches("[a-z][a-z0-9-]*")) { + throw new IllegalArgumentException("Parameter name must be lowercase kebab-case: " + name); + } + if (type == ParamType.ENUM && choices.isEmpty()) { + throw new IllegalArgumentException("Enum parameter needs choices: " + name); + } + if (type != ParamType.ENUM && !choices.isEmpty()) { + throw new IllegalArgumentException("Only enum parameters take choices: " + name); + } + if (defaultValue != null && type == ParamType.ENUM && !choices.contains(defaultValue)) { + throw new IllegalArgumentException("Default is not one of the choices: " + name); + } + if (required && defaultValue != null) { + throw new IllegalArgumentException("A parameter with a default is not required: " + name); + } + } + + public static Param string(String name, String description) { + return new Param(name, ParamType.STRING, false, null, description, false, List.of()); + } + + public static Param integer(String name, String description) { + return new Param(name, ParamType.INTEGER, false, null, description, false, List.of()); + } + + public static Param bool(String name, String description) { + return new Param(name, ParamType.BOOLEAN, false, "false", description, false, List.of()); + } + + public static Param path(String name, String description) { + return new Param(name, ParamType.PATH, false, null, description, false, List.of()); + } + + public static Param choice(String name, String description, List choices) { + return new Param(name, ParamType.ENUM, false, null, description, false, choices); + } + + public static Param choice(String name, String description, Class> choices) { + return choice(name, description, java.util.Arrays.stream(choices.getEnumConstants()) + .map(c -> c.name().toLowerCase(java.util.Locale.ROOT)).toList()); + } + + public Param asRequired() { + return new Param(name, type, true, null, description, multiple, choices); + } + + public Param defaultTo(String value) { + return new Param(name, type, false, value, description, multiple, choices); + } + + public Param asMultiple() { + return new Param(name, type, required, defaultValue, description, true, choices); + } +} diff --git a/src/main/java/org/ical4j/command/ops/ParamType.java b/src/main/java/org/ical4j/command/ops/ParamType.java new file mode 100644 index 0000000..bac5fdf --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/ParamType.java @@ -0,0 +1,16 @@ +package org.ical4j.command.ops; + +/** + * Surface-neutral parameter value types. Each surface maps these to its own representation: + * picocli option types on the CLI, JSON schema types for MCP. No JDK type such as + * {@code java.net.URL} appears here, so no surface ever registers one wholesale for reflection. + */ +public enum ParamType { + STRING, + INTEGER, + BOOLEAN, + /** One of a fixed set of lowercase choices, see {@link Param#choices()}. */ + ENUM, + /** A filesystem path, passed as a string and resolved by the handler. */ + PATH +} diff --git a/src/main/java/org/ical4j/command/ops/Params.java b/src/main/java/org/ical4j/command/ops/Params.java new file mode 100644 index 0000000..706455b --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Params.java @@ -0,0 +1,117 @@ +package org.ical4j.command.ops; + +import java.nio.file.Path; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Parsed parameter values handed to a handler, keyed by {@link Param#name()}. + *

+ * Surfaces populate this from their own parse results. Values are stored in their string form + * (or a list of strings for multiple parameters) so the conversion rules live in one place. + */ +public final class Params { + + private final Map values; + + private Params(Map values) { + this.values = Collections.unmodifiableMap(new HashMap<>(values)); + } + + public static Params empty() { + return new Params(Map.of()); + } + + public static Params of(Map values) { + return new Params(new HashMap<>(values)); + } + + /** + * Applies defaults from the descriptors and checks required parameters. + * + * @throws OperationException.Usage if a required parameter is missing or an enum value is not a choice + */ + public Params resolve(List descriptors) { + Map resolved = new HashMap<>(values); + for (Param p : descriptors) { + Object v = resolved.get(p.name()); + if (v == null && p.defaultValue() != null) { + resolved.put(p.name(), p.multiple() ? List.of(p.defaultValue()) : p.defaultValue()); + v = resolved.get(p.name()); + } + if (v == null && p.required()) { + throw new OperationException.Usage("Missing required parameter: " + p.name()); + } + if (v != null && p.type() == ParamType.ENUM) { + for (String s : p.multiple() ? strings(p.name()) : List.of(v.toString())) { + if (!p.choices().contains(s)) { + throw new OperationException.Usage("Invalid value '" + s + "' for " + p.name() + + "; expected one of " + p.choices()); + } + } + } + } + return new Params(resolved); + } + + public boolean has(String name) { + return values.get(name) != null; + } + + public Optional string(String name) { + Object v = values.get(name); + if (v instanceof List l) { + return l.isEmpty() ? Optional.empty() : Optional.of(l.get(0).toString()); + } + return Optional.ofNullable(v).map(Object::toString); + } + + public String string(String name, String fallback) { + return string(name).orElse(fallback); + } + + public String require(String name) { + return string(name).orElseThrow(() -> new OperationException.Usage("Missing required parameter: " + name)); + } + + public List strings(String name) { + Object v = values.get(name); + if (v == null) { + return List.of(); + } + if (v instanceof List l) { + return l.stream().map(Object::toString).toList(); + } + return List.of(v.toString()); + } + + public Optional integer(String name) { + return string(name).map(s -> { + try { + return Integer.valueOf(s.trim()); + } catch (NumberFormatException e) { + throw new OperationException.Usage("Expected an integer for " + name + ": " + s); + } + }); + } + + public boolean bool(String name) { + return string(name).map(s -> s.equalsIgnoreCase("true") || s.equals("1")).orElse(false); + } + + public Optional path(String name) { + return string(name).map(Path::of); + } + + public Map asMap() { + return values; + } + + @Override + public String toString() { + return values.toString(); + } +} diff --git a/src/main/java/org/ical4j/command/ops/Registry.java b/src/main/java/org/ical4j/command/ops/Registry.java new file mode 100644 index 0000000..c36d37d --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Registry.java @@ -0,0 +1,96 @@ +package org.ical4j.command.ops; + +import org.ical4j.command.vocab.Verb; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * The single table of operations. Every surface derives its interface from it and executes + * through it; nothing dispatches around it. + *

+ * Built once at startup. Registering the same (verb, subject, locus) tuple twice fails fast so a + * duplicate can never shadow another definition. + */ +public final class Registry { + + private final Map operations; + + private Registry(Map operations) { + this.operations = Collections.unmodifiableMap(new LinkedHashMap<>(operations)); + } + + public static Builder builder() { + return new Builder(); + } + + public static Registry empty() { + return new Registry(Map.of()); + } + + /** Operations in registration order. */ + public List all() { + return List.copyOf(operations.values()); + } + + public int size() { + return operations.size(); + } + + public Optional find(OperationId id) { + return Optional.ofNullable(operations.get(id)); + } + + public Operation require(OperationId id) { + return find(id).orElseThrow(() -> new OperationException.NotFound("No such operation: " + id)); + } + + /** Operations exposed to the given surface, in registration order. */ + public List forSurface(Surface surface) { + return operations.values().stream().filter(op -> op.exposedTo(surface)).toList(); + } + + /** Operations exposed to the surface, grouped by verb in {@link Verb} declaration order. */ + public Map> byVerb(Surface surface) { + Map> grouped = new EnumMap<>(Verb.class); + for (Operation op : forSurface(surface)) { + grouped.computeIfAbsent(op.id().verb(), v -> new ArrayList<>()).add(op); + } + grouped.replaceAll((v, ops) -> List.copyOf(ops)); + return Collections.unmodifiableMap(grouped); + } + + /** Executes an operation by identity after resolving its parameters. */ + public Result execute(OperationId id, Context context, Params params) { + return require(id).execute(context, params); + } + + public static final class Builder { + private final Map operations = new LinkedHashMap<>(); + + private Builder() { + } + + public Builder add(Operation operation) { + Operation previous = operations.putIfAbsent(operation.id(), operation); + if (previous != null) { + throw new IllegalStateException("Operation already registered: " + operation.id()); + } + return this; + } + + public Builder addAll(Iterable ops) { + ops.forEach(this::add); + return this; + } + + public Registry build() { + return new Registry(operations); + } + } +} diff --git a/src/main/java/org/ical4j/command/ops/Renderer.java b/src/main/java/org/ical4j/command/ops/Renderer.java new file mode 100644 index 0000000..f3fe76c --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Renderer.java @@ -0,0 +1,248 @@ +package org.ical4j.command.ops; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyName; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import net.fortuna.ical4j.data.CalendarOutputter; +import net.fortuna.ical4j.model.Calendar; +import net.fortuna.ical4j.vcard.Entity; +import net.fortuna.ical4j.vcard.VCard; +import net.fortuna.ical4j.vcard.VCardOutputter; +import org.mnode.ical4j.serializer.JCalSerializer; +import org.mnode.ical4j.serializer.JCardSerializer; +import org.mnode.ical4j.serializer.XCalSerializer; +import org.mnode.ical4j.serializer.XCardSerializer; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Turns a structured {@link Result} into text in a {@link Format}. Surface-neutral: the CLI + * writes the string to stdout, MCP wraps it in a content block. Never touches a stream itself. + */ +public final class Renderer { + + private static final String NO_ERRORS = "No errors."; + + private final boolean pretty; + + private ObjectMapper json; + + private XmlMapper xml; + + public Renderer() { + this(false); + } + + public Renderer(boolean pretty) { + this.pretty = pretty; + } + + public String render(Result result, Format format) { + switch (format) { + case TEXT: + return text(result); + case JSON: + return json(result); + case XML: + return xml(result); + default: + throw new IllegalArgumentException("Unsupported format: " + format); + } + } + + // ---- text ------------------------------------------------------------------------------- + + private String text(Result result) { + if (result instanceof Result.Status s) { + return s.message() + "\n"; + } + if (result instanceof Result.Identifiers ids) { + return lines(ids.ids()); + } + if (result instanceof Result.Descriptor d) { + StringBuilder sb = new StringBuilder(); + d.attributes().forEach((k, v) -> sb.append(k).append(": ").append(v).append('\n')); + return sb.toString(); + } + if (result instanceof Result.Descriptors ds) { + return table(ds.items()); + } + if (result instanceof Result.CalendarData c) { + return calendarText(c.calendar()); + } + if (result instanceof Result.CardData c) { + return cardText(c.card()); + } + if (result instanceof Result.Validation v) { + if (v.valid()) { + return NO_ERRORS + "\n"; + } + StringBuilder sb = new StringBuilder(); + for (Result.ValidationEntry e : v.entries()) { + sb.append("- ").append(e.severity()).append(": ").append(e.context()) + .append(" - ").append(e.message()).append('\n'); + } + return sb.toString(); + } + throw new IllegalArgumentException("Unknown result type: " + result.getClass()); + } + + private static String lines(List items) { + StringBuilder sb = new StringBuilder(); + items.forEach(i -> sb.append(i).append('\n')); + return sb.toString(); + } + + /** Aligned columns with a header row; the column set is the ordered union of all keys. */ + static String table(List items) { + if (items.isEmpty()) { + return ""; + } + Set columns = new LinkedHashSet<>(); + items.forEach(i -> columns.addAll(i.attributes().keySet())); + List cols = new ArrayList<>(columns); + int[] widths = new int[cols.size()]; + for (int i = 0; i < cols.size(); i++) { + widths[i] = cols.get(i).length(); + for (Result.Descriptor d : items) { + widths[i] = Math.max(widths[i], d.attributes().getOrDefault(cols.get(i), "").length()); + } + } + StringBuilder sb = new StringBuilder(); + row(sb, cols, widths); + for (Result.Descriptor d : items) { + List values = new ArrayList<>(); + cols.forEach(c -> values.add(d.attributes().getOrDefault(c, ""))); + row(sb, values, widths); + } + return sb.toString(); + } + + private static void row(StringBuilder sb, List cells, int[] widths) { + for (int i = 0; i < cells.size(); i++) { + String cell = cells.get(i); + if (i < cells.size() - 1) { + sb.append(cell).append(" ".repeat(widths[i] - cell.length() + 2)); + } else { + sb.append(cell); + } + } + sb.append('\n'); + } + + private static String calendarText(Calendar calendar) { + try { + StringWriter out = new StringWriter(); + new CalendarOutputter(false).output(calendar, out); + return out.toString(); + } catch (IOException e) { + throw new OperationException("Cannot write calendar", e); + } + } + + private static String cardText(VCard card) { + try { + StringWriter out = new StringWriter(); + new VCardOutputter(false).output(card, out); + return out.toString(); + } catch (IOException e) { + throw new OperationException("Cannot write card", e); + } + } + + // ---- json ------------------------------------------------------------------------------- + + private String json(Result result) { + Object value; + if (result instanceof Result.Status s) { + value = Map.of("status", s.message()); + } else if (result instanceof Result.Identifiers ids) { + value = ids.ids(); + } else if (result instanceof Result.Descriptor d) { + value = new LinkedHashMap<>(d.attributes()); + } else if (result instanceof Result.Descriptors ds) { + List> items = new ArrayList<>(); + ds.items().forEach(d -> items.add(new LinkedHashMap<>(d.attributes()))); + value = items; + } else if (result instanceof Result.CalendarData c) { + value = c.calendar(); + } else if (result instanceof Result.CardData c) { + // jCard is defined per card; a VCard object is a container of entities. + List entities = c.card().getEntities(); + value = entities.size() == 1 ? entities.get(0) : entities; + } else if (result instanceof Result.Validation v) { + List> entries = new ArrayList<>(); + for (Result.ValidationEntry e : v.entries()) { + Map m = new LinkedHashMap<>(); + m.put("severity", e.severity()); + m.put("context", e.context()); + m.put("message", e.message()); + entries.add(m); + } + Map m = new LinkedHashMap<>(); + m.put("valid", v.valid()); + m.put("entries", entries); + value = m; + } else { + throw new IllegalArgumentException("Unknown result type: " + result.getClass()); + } + try { + ObjectMapper mapper = jsonMapper(); + return (pretty ? mapper.writerWithDefaultPrettyPrinter() : mapper.writer()).writeValueAsString(value) + "\n"; + } catch (JsonProcessingException e) { + throw new OperationException("Cannot write JSON", e); + } + } + + private ObjectMapper jsonMapper() { + if (json == null) { + SimpleModule module = new SimpleModule(); + module.addSerializer(Calendar.class, new JCalSerializer(Calendar.class)); + module.addSerializer(Entity.class, new JCardSerializer(Entity.class)); + json = new ObjectMapper().registerModule(module); + } + return json; + } + + // ---- xml -------------------------------------------------------------------------------- + + private String xml(Result result) { + try { + if (result instanceof Result.CalendarData c) { + return xmlMapper("icalendar", "urn:ietf:params:xml:ns:icalendar-2.0") + .writeValueAsString(c.calendar()) + "\n"; + } + if (result instanceof Result.CardData c) { + List entities = c.card().getEntities(); + return xmlMapper("vcards", "urn:ietf:params:xml:ns:vcard-4.0") + .writeValueAsString(entities.size() == 1 ? entities.get(0) : entities) + "\n"; + } + } catch (JsonProcessingException e) { + throw new OperationException("Cannot write XML", e); + } + throw new OperationException.Usage("XML output is only available for calendar and card data"); + } + + private XmlMapper xmlMapper(String rootName, String namespace) { + if (xml == null) { + SimpleModule module = new SimpleModule(); + module.addSerializer(Calendar.class, new XCalSerializer(Calendar.class)); + module.addSerializer(Entity.class, new XCardSerializer(Entity.class)); + xml = XmlMapper.builder().defaultUseWrapper(true).build(); + xml.registerModule(module); + } + xml.setConfig(xml.getSerializationConfig().withRootName(PropertyName.construct(rootName, namespace)) + .with(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME)); + return xml; + } +} diff --git a/src/main/java/org/ical4j/command/ops/Result.java b/src/main/java/org/ical4j/command/ops/Result.java new file mode 100644 index 0000000..7dc0a0e --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Result.java @@ -0,0 +1,69 @@ +package org.ical4j.command.ops; + +import net.fortuna.ical4j.model.Calendar; +import net.fortuna.ical4j.vcard.VCard; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * A structured operation result. Handlers return one of these; surfaces render them. No result + * carries pre-formatted text for a particular surface. + */ +public interface Result { + + /** A short outcome statement, for operations that change state and return nothing else. */ + record Status(String message) implements Result { + } + + /** Identifiers of items, for {@code list}-style operations. */ + record Identifiers(List ids) implements Result { + public Identifiers { + ids = List.copyOf(ids); + } + } + + /** A described item or locus: name/value attributes in insertion order. */ + record Descriptor(Map attributes) implements Result { + public Descriptor { + attributes.forEach((k, v) -> { + if (k == null || v == null) { + throw new NullPointerException("Descriptor attributes cannot be null: " + k); + } + }); + attributes = Collections.unmodifiableMap(new LinkedHashMap<>(attributes)); + } + } + + /** Several descriptors, for listing loci. */ + record Descriptors(List items) implements Result { + public Descriptors { + items = List.copyOf(items); + } + } + + /** An iCalendar object. */ + record CalendarData(Calendar calendar) implements Result { + } + + /** A vCard object. */ + record CardData(VCard card) implements Result { + } + + /** One validation finding. */ + record ValidationEntry(String severity, String context, String message) { + } + + /** A validation outcome: no entries means valid. */ + record Validation(List entries) implements Result { + public Validation { + entries = List.copyOf(entries); + } + + public boolean valid() { + return entries.isEmpty(); + } + } +} diff --git a/src/main/java/org/ical4j/command/ops/Stores.java b/src/main/java/org/ical4j/command/ops/Stores.java new file mode 100644 index 0000000..7ac1fed --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Stores.java @@ -0,0 +1,92 @@ +package org.ical4j.command.ops; + +import org.ical4j.command.vocab.SerializationFamily; +import org.ical4j.connector.CalendarCollection; +import org.ical4j.connector.CardCollection; +import org.ical4j.connector.ObjectCollection; +import org.ical4j.connector.ObjectNotFoundException; +import org.ical4j.connector.ObjectStore; +import org.ical4j.connector.ObjectStoreException; + +import java.util.List; +import java.util.Locale; + +/** + * Store access shared by handlers: parameter conventions and the mapping of connector + * exceptions onto {@link OperationException}. + */ +final class Stores { + + static final Param COLLECTION = Param.string("collection", "Name of the collection").asRequired(); + + static final Param TYPE = Param.choice("type", "Collection type", SerializationFamily.class).defaultTo("calendar"); + + private Stores() { + } + + static SerializationFamily family(Params params) { + return SerializationFamily.valueOf(params.string("type", "calendar").toUpperCase(Locale.ROOT)); + } + + static ObjectStore> store(Context context, SerializationFamily family) { + return family == SerializationFamily.CARD ? context.cardStore() : context.calendarStore(); + } + + static CalendarCollection calendarCollection(Context context, String name) { + return collection(context.calendarStore(), name, context.activeWorkspace()); + } + + static CardCollection cardCollection(Context context, String name) { + return collection(context.cardStore(), name, context.activeWorkspace()); + } + + static > C collection(ObjectStore store, String name, String workspace) { + try { + return store.getCollection(name, workspace); + } catch (ObjectNotFoundException e) { + throw new OperationException.NotFound("No such collection: " + name); + } catch (ObjectStoreException e) { + throw new OperationException.Store("Cannot open collection " + name + ": " + e.getMessage(), e); + } + } + + static boolean exists(ObjectStore> store, String name, String workspace) { + try { + store.getCollection(name, workspace); + return true; + } catch (ObjectNotFoundException e) { + return false; + } catch (ObjectStoreException e) { + throw new OperationException.Store("Cannot open collection " + name + ": " + e.getMessage(), e); + } + } + + static > List collections(ObjectStore store, String workspace) { + try { + return store.getCollections(workspace); + } catch (ObjectNotFoundException e) { + // A workspace nobody has written to yet has no collections. + return List.of(); + } catch (ObjectStoreException e) { + throw new OperationException.Store("Cannot list collections: " + e.getMessage(), e); + } + } + + /** Runs a store action, translating connector failures. */ + static T call(StoreCall action) { + try { + return action.run(); + } catch (ObjectNotFoundException e) { + throw new OperationException.NotFound(e.getMessage() == null ? "Not found" : e.getMessage()); + } catch (OperationException e) { + throw e; + } catch (Exception e) { + throw new OperationException.Store(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(), e); + } + } + + @FunctionalInterface + interface StoreCall { + T run() throws Exception; + } +} diff --git a/src/main/java/org/ical4j/command/ops/Surface.java b/src/main/java/org/ical4j/command/ops/Surface.java new file mode 100644 index 0000000..5b9a02e --- /dev/null +++ b/src/main/java/org/ical4j/command/ops/Surface.java @@ -0,0 +1,9 @@ +package org.ical4j.command.ops; + +/** + * The views that expose registry operations. + */ +public enum Surface { + CLI, + MCP +} diff --git a/ical4j-command-cli/src/main/java/org/ical4j/command/util/Filesystem.java b/src/main/java/org/ical4j/command/util/Filesystem.java similarity index 53% rename from ical4j-command-cli/src/main/java/org/ical4j/command/util/Filesystem.java rename to src/main/java/org/ical4j/command/util/Filesystem.java index e357c1a..d86cac9 100644 --- a/ical4j-command-cli/src/main/java/org/ical4j/command/util/Filesystem.java +++ b/src/main/java/org/ical4j/command/util/Filesystem.java @@ -6,10 +6,21 @@ public interface Filesystem { /** - * Get the appropriate data directory for the current operating system. + * Environment variable that overrides the platform data directory. Used by tests, the + * native smoke suite and MCP client configurations that want an isolated store. + */ + String DATA_DIR_ENV = "ICT_DATA_DIR"; + + /** + * Get the appropriate data directory: {@code ICT_DATA_DIR} if set, otherwise the platform + * convention for the current operating system. * @return the data directory path */ static String getDataDirectory() { + String override = System.getenv(DATA_DIR_ENV); + if (override != null && !override.isBlank()) { + return override; + } String os = System.getProperty("os.name").toLowerCase(); String userHome = System.getProperty("user.home"); diff --git a/ical4j-command-core/src/main/java/org/ical4j/command/core/EntityType.java b/src/main/java/org/ical4j/command/vocab/EntityType.java similarity index 96% rename from ical4j-command-core/src/main/java/org/ical4j/command/core/EntityType.java rename to src/main/java/org/ical4j/command/vocab/EntityType.java index fb4cae9..ee1b0c6 100644 --- a/ical4j-command-core/src/main/java/org/ical4j/command/core/EntityType.java +++ b/src/main/java/org/ical4j/command/vocab/EntityType.java @@ -29,14 +29,14 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.ical4j.command.core; +package org.ical4j.command.vocab; /** * The canonical entity types that operations act on. Every type lives directly within a * {@link Locus#COLLECTION}. Note that {@code calendar} and {@code card} are NOT entity * types - they are {@link SerializationFamily serialization families}. */ -public enum EntityType { +public enum EntityType implements Subject { EVENT, ACTION, diff --git a/ical4j-command-core/src/main/java/org/ical4j/command/core/Locus.java b/src/main/java/org/ical4j/command/vocab/Locus.java similarity index 73% rename from ical4j-command-core/src/main/java/org/ical4j/command/core/Locus.java rename to src/main/java/org/ical4j/command/vocab/Locus.java index 9c070cc..ba8c80a 100644 --- a/ical4j-command-core/src/main/java/org/ical4j/command/core/Locus.java +++ b/src/main/java/org/ical4j/command/vocab/Locus.java @@ -29,18 +29,37 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.ical4j.command.core; +package org.ical4j.command.vocab; /** * The containment hierarchy an operation acts within. The hierarchy is exactly two levels * deep: a {@link #WORKSPACE} contains {@link #COLLECTION}s, and a collection directly * contains entities. There is no container level between a collection and its entities. */ -public enum Locus { +public enum Locus implements Subject { /** Top-level container of collections. */ WORKSPACE, /** Container of entities; entities live directly here. */ - COLLECTION + COLLECTION, + + /** + * Items are transmitted over or accepted from a channel rather than stored: the locus of + * {@code send} and {@code receive}. Not a container, so never a subject. + */ + CHANNEL, + + /** + * The operation acts on a stream or file, or synthesises output, without touching a store: + * {@code generate}, {@code validate} of a file, {@code export} from stdin. Never a subject. + */ + NONE; + + /** + * @return whether an operation may name this locus as its subject + */ + public boolean isSubject() { + return this == WORKSPACE || this == COLLECTION; + } } diff --git a/ical4j-command-core/src/main/java/org/ical4j/command/core/SendMethod.java b/src/main/java/org/ical4j/command/vocab/SendMethod.java similarity index 98% rename from ical4j-command-core/src/main/java/org/ical4j/command/core/SendMethod.java rename to src/main/java/org/ical4j/command/vocab/SendMethod.java index 8f70236..6d5a8de 100644 --- a/ical4j-command-core/src/main/java/org/ical4j/command/core/SendMethod.java +++ b/src/main/java/org/ical4j/command/vocab/SendMethod.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.ical4j.command.core; +package org.ical4j.command.vocab; /** * iTIP (RFC 5546) methods that specialise a {@link Verb#SEND} operation. These are carried diff --git a/ical4j-command-core/src/main/java/org/ical4j/command/core/SerializationFamily.java b/src/main/java/org/ical4j/command/vocab/SerializationFamily.java similarity index 95% rename from ical4j-command-core/src/main/java/org/ical4j/command/core/SerializationFamily.java rename to src/main/java/org/ical4j/command/vocab/SerializationFamily.java index d7e1c4d..e0658bc 100644 --- a/ical4j-command-core/src/main/java/org/ical4j/command/core/SerializationFamily.java +++ b/src/main/java/org/ical4j/command/vocab/SerializationFamily.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.ical4j.command.core; +package org.ical4j.command.vocab; /** * The serialization / object families that data is imported from and exported to. These @@ -37,7 +37,7 @@ * or writes via {@link Verb#IMPORT} / {@link Verb#EXPORT} when crossing a collection * boundary. */ -public enum SerializationFamily { +public enum SerializationFamily implements Subject { /** iCalendar (RFC 5545) representation. */ CALENDAR, diff --git a/src/main/java/org/ical4j/command/vocab/Subject.java b/src/main/java/org/ical4j/command/vocab/Subject.java new file mode 100644 index 0000000..1c06f2a --- /dev/null +++ b/src/main/java/org/ical4j/command/vocab/Subject.java @@ -0,0 +1,26 @@ +package org.ical4j.command.vocab; + +import java.util.Locale; + +/** + * The type axis of an operation: what a verb acts on. + *

+ * Entity types are the usual subjects, but a serialization family is the subject of + * {@code import}/{@code export}/{@code validate}, and a locus is the subject when the container + * itself is listed, fetched, added or removed ({@code list collection}, {@code add collection}). + * {@link Locus#NONE} is never a valid subject; the registry rejects it. + */ +public interface Subject { + + /** + * @return the enum constant name + */ + String name(); + + /** + * @return the lowercase name used in command syntax and tool names + */ + default String key() { + return name().toLowerCase(Locale.ROOT); + } +} diff --git a/ical4j-command-core/src/main/java/org/ical4j/command/core/Verb.java b/src/main/java/org/ical4j/command/vocab/Verb.java similarity index 98% rename from ical4j-command-core/src/main/java/org/ical4j/command/core/Verb.java rename to src/main/java/org/ical4j/command/vocab/Verb.java index c635326..8d4ab71 100644 --- a/ical4j-command-core/src/main/java/org/ical4j/command/core/Verb.java +++ b/src/main/java/org/ical4j/command/vocab/Verb.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.ical4j.command.core; +package org.ical4j.command.vocab; /** * The canonical set of action verbs shared by all command surfaces (CLI, MCP, agent). diff --git a/src/main/resources/META-INF/native-image/org.ical4j/ict/reachability-metadata.json b/src/main/resources/META-INF/native-image/org.ical4j/ict/reachability-metadata.json new file mode 100644 index 0000000..49a0faf --- /dev/null +++ b/src/main/resources/META-INF/native-image/org.ical4j/ict/reachability-metadata.json @@ -0,0 +1,950 @@ +{ + "reflection": [ + { + "type": "com.ctc.wstx.stax.WstxInputFactory" + }, + { + "type": "com.ctc.wstx.stax.WstxOutputFactory" + }, + { + "type": "com.ethlo.time.ITU" + }, + { + "type": "com.fasterxml.jackson.databind.deser.BeanDeserializerModifier[]" + }, + { + "type": "com.fasterxml.jackson.databind.ext.Java7SupportImpl", + "methods": [ + { + "name": "", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "com.fasterxml.jackson.databind.ser.BeanSerializerModifier[]" + }, + { + "type": "com.fasterxml.jackson.databind.ser.Serializers[]" + }, + { + "type": "io.modelcontextprotocol.json.schema.jackson2.JacksonJsonSchemaValidatorSupplier" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Annotated" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Annotations" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$CallToolRequest", + "methods": [ + { + "name": "fromJson", + "parameterTypes": [ + "java.lang.String", + "java.util.Map", + "java.util.Map" + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$CallToolResult", + "methods": [ + { + "name": "content", + "parameterTypes": [ + + ] + }, + { + "name": "isError", + "parameterTypes": [ + + ] + }, + { + "name": "meta", + "parameterTypes": [ + + ] + }, + { + "name": "structuredContent", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ClientCapabilities", + "methods": [ + { + "name": "", + "parameterTypes": [ + "java.util.Map", + "io.modelcontextprotocol.spec.McpSchema$ClientCapabilities$RootCapabilities", + "io.modelcontextprotocol.spec.McpSchema$ClientCapabilities$Sampling", + "io.modelcontextprotocol.spec.McpSchema$ClientCapabilities$Elicitation" + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ClientCapabilities$Elicitation" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ClientCapabilities$Elicitation$Form" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ClientCapabilities$Elicitation$Url" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ClientCapabilities$RootCapabilities" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ClientCapabilities$Sampling" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Content" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Icon" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Identifier" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Implementation", + "methods": [ + { + "name": "description", + "parameterTypes": [ + + ] + }, + { + "name": "fromJson", + "parameterTypes": [ + "java.lang.String", + "java.lang.String", + "java.lang.String", + "java.lang.String", + "java.util.List", + "java.lang.String" + ] + }, + { + "name": "icons", + "parameterTypes": [ + + ] + }, + { + "name": "name", + "parameterTypes": [ + + ] + }, + { + "name": "title", + "parameterTypes": [ + + ] + }, + { + "name": "version", + "parameterTypes": [ + + ] + }, + { + "name": "websiteUrl", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$InitializeRequest", + "methods": [ + { + "name": "fromJson", + "parameterTypes": [ + "java.lang.String", + "io.modelcontextprotocol.spec.McpSchema$ClientCapabilities", + "io.modelcontextprotocol.spec.McpSchema$Implementation", + "java.util.Map" + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$InitializeResult", + "methods": [ + { + "name": "capabilities", + "parameterTypes": [ + + ] + }, + { + "name": "instructions", + "parameterTypes": [ + + ] + }, + { + "name": "meta", + "parameterTypes": [ + + ] + }, + { + "name": "protocolVersion", + "parameterTypes": [ + + ] + }, + { + "name": "serverInfo", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$JSONRPCMessage" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$JSONRPCNotification", + "methods": [ + { + "name": "", + "parameterTypes": [ + "java.lang.String", + "java.lang.String", + "java.lang.Object" + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$JSONRPCRequest", + "methods": [ + { + "name": "", + "parameterTypes": [ + "java.lang.String", + "java.lang.String", + "java.lang.Object", + "java.lang.Object" + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$JSONRPCResponse", + "methods": [ + { + "name": "error", + "parameterTypes": [ + + ] + }, + { + "name": "id", + "parameterTypes": [ + + ] + }, + { + "name": "jsonrpc", + "parameterTypes": [ + + ] + }, + { + "name": "result", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$JSONRPCResponse$JSONRPCError" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ListToolsResult", + "methods": [ + { + "name": "meta", + "parameterTypes": [ + + ] + }, + { + "name": "nextCursor", + "parameterTypes": [ + + ] + }, + { + "name": "tools", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Meta" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Request" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Result" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ServerCapabilities", + "methods": [ + { + "name": "completions", + "parameterTypes": [ + + ] + }, + { + "name": "experimental", + "parameterTypes": [ + + ] + }, + { + "name": "logging", + "parameterTypes": [ + + ] + }, + { + "name": "prompts", + "parameterTypes": [ + + ] + }, + { + "name": "resources", + "parameterTypes": [ + + ] + }, + { + "name": "tools", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ServerCapabilities$CompletionCapabilities" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ServerCapabilities$LoggingCapabilities" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ServerCapabilities$PromptCapabilities" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ServerCapabilities$ResourceCapabilities" + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ServerCapabilities$ToolCapabilities", + "methods": [ + { + "name": "listChanged", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$TextContent", + "methods": [ + { + "name": "annotations", + "parameterTypes": [ + + ] + }, + { + "name": "meta", + "parameterTypes": [ + + ] + }, + { + "name": "text", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Tool", + "methods": [ + { + "name": "annotations", + "parameterTypes": [ + + ] + }, + { + "name": "description", + "parameterTypes": [ + + ] + }, + { + "name": "icons", + "parameterTypes": [ + + ] + }, + { + "name": "inputSchema", + "parameterTypes": [ + + ] + }, + { + "name": "meta", + "parameterTypes": [ + + ] + }, + { + "name": "name", + "parameterTypes": [ + + ] + }, + { + "name": "outputSchema", + "parameterTypes": [ + + ] + }, + { + "name": "title", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$ToolAnnotations", + "methods": [ + { + "name": "destructiveHint", + "parameterTypes": [ + + ] + }, + { + "name": "idempotentHint", + "parameterTypes": [ + + ] + }, + { + "name": "openWorldHint", + "parameterTypes": [ + + ] + }, + { + "name": "readOnlyHint", + "parameterTypes": [ + + ] + }, + { + "name": "returnDirect", + "parameterTypes": [ + + ] + }, + { + "name": "title", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "io.modelcontextprotocol.spec.McpSchema$Tool[]" + }, + { + "type": "java.io.Serializable" + }, + { + "type": "java.lang.Boolean", + "jniAccessible": true, + "methods": [ + { + "name": "getBoolean", + "parameterTypes": [ + "java.lang.String" + ] + } + ] + }, + { + "type": "java.lang.Class", + "methods": [ + { + "name": "getRecordComponents", + "parameterTypes": [ + + ] + }, + { + "name": "isRecord", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "java.lang.Comparable" + }, + { + "type": "java.lang.Double" + }, + { + "type": "java.lang.Iterable" + }, + { + "type": "java.lang.Number" + }, + { + "type": "java.lang.Object" + }, + { + "type": "java.lang.Object[]" + }, + { + "type": "java.lang.Record" + }, + { + "type": "java.lang.System", + "methods": [ + { + "name": "console", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "java.lang.constant.Constable" + }, + { + "type": "java.lang.constant.ConstantDesc" + }, + { + "type": "java.lang.reflect.RecordComponent", + "methods": [ + { + "name": "getName", + "parameterTypes": [ + + ] + }, + { + "name": "getType", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "java.nio.file.Path" + }, + { + "type": "java.nio.file.Paths" + }, + { + "type": "java.time.Duration" + }, + { + "type": "java.time.Instant" + }, + { + "type": "java.time.LocalDate" + }, + { + "type": "java.time.LocalDateTime" + }, + { + "type": "java.time.LocalTime" + }, + { + "type": "java.time.MonthDay" + }, + { + "type": "java.time.OffsetDateTime" + }, + { + "type": "java.time.OffsetTime" + }, + { + "type": "java.time.Period" + }, + { + "type": "java.time.Year" + }, + { + "type": "java.time.YearMonth" + }, + { + "type": "java.time.ZoneId" + }, + { + "type": "java.time.ZoneOffset" + }, + { + "type": "java.time.ZonedDateTime" + }, + { + "type": "java.util.AbstractCollection" + }, + { + "type": "java.util.Collection" + }, + { + "type": "java.util.ImmutableCollections$AbstractImmutableCollection" + }, + { + "type": "java.util.ImmutableCollections$AbstractImmutableList" + }, + { + "type": "java.util.ImmutableCollections$List12" + }, + { + "type": "java.util.ImmutableCollections$ListN" + }, + { + "type": "java.util.List" + }, + { + "type": "java.util.RandomAccess" + }, + { + "type": "net.fortuna.ical4j.extensions.validate.ExtensionsCalendarValidatorFactory" + }, + { + "type": "net.fortuna.ical4j.model.DefaultZoneRulesProvider" + }, + { + "type": "net.fortuna.ical4j.model.TimeZoneRegistryImpl", + "methods": [ + { + "name": "", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "net.fortuna.ical4j.model.TimeZoneRegistryImpl" + }, + { + "type": "net.fortuna.ical4j.util.MapTimeZoneCache", + "methods": [ + { + "name": "", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "org.ical4j.command.cli.GlobalOptions", + "methods": [ + { + "name": "setFormat", + "parameterTypes": [ + "org.ical4j.command.ops.Format" + ] + } + ] + }, + { + "type": "org.ical4j.command.cli.Main" + }, + { + "type": "org.ical4j.command.cli.VersionProvider", + "methods": [ + { + "name": "", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "org.slf4j.simple.SimpleServiceProvider" + }, + { + "type": "picocli.CommandLine$AutoHelpMixin", + "fields": [ + { + "name": "helpRequested" + }, + { + "name": "versionRequested" + } + ] + }, + { + "type": "reactor.core.publisher.FlatMapTracker" + }, + { + "type": "reactor.core.publisher.FluxFlatMap$FlatMapInner" + }, + { + "type": "reactor.core.publisher.FluxFlatMap$FlatMapMain" + }, + { + "type": "reactor.core.publisher.FluxIterable$IterableSubscription" + }, + { + "type": "reactor.core.publisher.FluxOnErrorReturn$ReturnSubscriber" + }, + { + "type": "reactor.core.publisher.FluxPublishOn$PublishOnConditionalSubscriber" + }, + { + "type": "reactor.core.publisher.FluxReplay" + }, + { + "type": "reactor.core.publisher.FluxSubscribeOnCallable$CallableSubscribeOnSubscription" + }, + { + "type": "reactor.core.publisher.LambdaMonoSubscriber" + }, + { + "type": "reactor.core.publisher.LambdaSubscriber" + }, + { + "type": "reactor.core.publisher.MonoFlatMap$FlatMapMain" + }, + { + "type": "reactor.core.publisher.MonoIgnoreThen$ThenIgnoreMain" + }, + { + "type": "reactor.core.publisher.MonoZip$ZipCoordinator" + }, + { + "type": "reactor.core.publisher.MonoZip$ZipInner" + }, + { + "type": "reactor.core.publisher.Operators$BaseFluxToMonoOperator" + }, + { + "type": "reactor.core.publisher.Operators$MonoInnerProducerBase" + }, + { + "type": "reactor.core.publisher.Operators$MultiSubscriptionSubscriber" + }, + { + "type": "reactor.core.publisher.Operators$ScalarSubscription" + }, + { + "type": "reactor.core.publisher.SinkEmptyMulticast" + }, + { + "type": "reactor.core.publisher.SinkManyUnicast" + }, + { + "type": "reactor.core.publisher.SinksSpecs$AbstractSerializedSink" + }, + { + "type": "reactor.core.scheduler.BoundedElasticScheduler" + }, + { + "type": "reactor.core.scheduler.BoundedElasticScheduler$BoundedServices" + }, + { + "type": "reactor.core.scheduler.BoundedElasticScheduler$BoundedState" + }, + { + "type": "reactor.core.scheduler.DelegateServiceScheduler" + }, + { + "type": "reactor.core.scheduler.SchedulerTask" + }, + { + "type": "reactor.core.scheduler.WorkerTask" + }, + { + "type": "reactor.util.concurrent.SpscArrayQueueConsumer" + }, + { + "type": "reactor.util.concurrent.SpscArrayQueueProducer" + }, + { + "type": "reactor.util.concurrent.SpscLinkedArrayQueue" + }, + { + "type": "sun.security.provider.NativePRNG", + "methods": [ + { + "name": "", + "parameterTypes": [ + "java.security.SecureRandomParameters" + ] + } + ] + }, + { + "type": "sun.security.provider.SHA", + "methods": [ + { + "name": "", + "parameterTypes": [ + + ] + } + ] + }, + { + "type": "sun.text.resources.BreakIteratorInfo" + }, + { + "type": "sun.text.resources.BreakIteratorResources" + }, + { + "type": "sun.text.resources.BreakIteratorResources_en" + }, + { + "type": "sun.text.resources.cldr.FormatData" + }, + { + "type": "sun.text.resources.cldr.FormatData_en" + }, + { + "type": "sun.text.resources.cldr.FormatData_en_US" + }, + { + "type": "sun.util.resources.cldr.CalendarData" + }, + { + "type": "sun.util.resources.cldr.TimeZoneNames" + }, + { + "type": "sun.util.resources.cldr.TimeZoneNames_en" + }, + { + "type": "sun.util.resources.cldr.TimeZoneNames_en_US" + } + ], + "resources": [ + { + "glob": "META-INF/services/io.modelcontextprotocol.json.schema.JsonSchemaValidatorSupplier" + }, + { + "glob": "META-INF/services/java.time.zone.ZoneRulesProvider" + }, + { + "glob": "META-INF/services/javax.xml.stream.XMLInputFactory" + }, + { + "glob": "META-INF/services/javax.xml.stream.XMLOutputFactory" + }, + { + "glob": "META-INF/services/net.fortuna.ical4j.validate.CalendarValidatorFactory" + }, + { + "glob": "META-INF/services/org.slf4j.spi.SLF4JServiceProvider" + }, + { + "glob": "draft/2020-12/meta/applicator" + }, + { + "glob": "draft/2020-12/meta/content" + }, + { + "glob": "draft/2020-12/meta/core" + }, + { + "glob": "draft/2020-12/meta/format-annotation" + }, + { + "glob": "draft/2020-12/meta/meta-data" + }, + { + "glob": "draft/2020-12/meta/unevaluated" + }, + { + "glob": "draft/2020-12/meta/validation" + }, + { + "glob": "draft/2020-12/schema" + }, + { + "glob": "ical4j.properties" + }, + { + "glob": "ictrc.default.toml" + }, + { + "glob": "net/fortuna/ical4j/model/tz.alias" + }, + { + "glob": "net/fortuna/ical4j/transform/compliance/msTimezoneIds" + }, + { + "glob": "net/fortuna/ical4j/transform/compliance/msTimezoneNames" + }, + { + "glob": "org/ical4j/command/version.properties" + }, + { + "glob": "simplelogger.properties" + }, + { + "glob": "tz.alias" + }, + { + "glob": "zoneinfo-global/**" + }, + { + "glob": "zoneinfo/**" + }, + { + "module": "java.base", + "glob": "sun/text/resources/LineBreakIteratorData" + } + ] +} diff --git a/src/main/resources/ictrc.default.toml b/src/main/resources/ictrc.default.toml new file mode 100644 index 0000000..01c23f3 --- /dev/null +++ b/src/main/resources/ictrc.default.toml @@ -0,0 +1,14 @@ +# Default ict configuration, copied to /iCal4j/ictrc.toml on first use. + +[user] + agent = "ict/1.0" + +[workspace] + active = "default" + +[store] + calendar.path = "calendars" + card.path = "vcards" + +[contentType] + default = "text/plain" diff --git a/src/main/resources/org/ical4j/command/version.properties b/src/main/resources/org/ical4j/command/version.properties new file mode 100644 index 0000000..05563c4 --- /dev/null +++ b/src/main/resources/org/ical4j/command/version.properties @@ -0,0 +1,2 @@ +# Expanded by processResources; read by cli.VersionProvider. +version=${version} diff --git a/src/main/resources/simplelogger.properties b/src/main/resources/simplelogger.properties new file mode 100644 index 0000000..620743a --- /dev/null +++ b/src/main/resources/simplelogger.properties @@ -0,0 +1,10 @@ +# slf4j-simple configuration. Everything goes to stderr; stdout belongs to command output. +# The default level is overridden at startup by ICT_LOG_LEVEL or the -v/--verbose flag, +# see org.ical4j.command.LogLevel. +org.slf4j.simpleLogger.logFile=System.err +org.slf4j.simpleLogger.defaultLogLevel=warn +org.slf4j.simpleLogger.showDateTime=false +org.slf4j.simpleLogger.showThreadName=false +org.slf4j.simpleLogger.showLogName=false +org.slf4j.simpleLogger.showShortLogName=true +org.slf4j.simpleLogger.levelInBrackets=true diff --git a/src/smoke/java/org/ical4j/command/smoke/SmokeSuite.java b/src/smoke/java/org/ical4j/command/smoke/SmokeSuite.java new file mode 100644 index 0000000..47b7c0f --- /dev/null +++ b/src/smoke/java/org/ical4j/command/smoke/SmokeSuite.java @@ -0,0 +1,328 @@ +package org.ical4j.command.smoke; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.ical4j.command.ops.Operation; +import org.ical4j.command.ops.Operations; +import org.ical4j.command.ops.Surface; +import org.ical4j.command.util.Filesystem; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * Black-box smoke run of an {@code ict} executable: {@code --help} for every operation, one real + * invocation per operation, the native-sensitive paths (time zones, ServiceLoader factories, + * JSON and XML output) and one {@code ict mcp} handshake. + *

+ * The target is a command prefix, so the same steps run against the native binary + * ({@code SmokeSuite build/native/nativeCompile/ict}) and against the JVM build under the + * tracing agent, which is how the native metadata is captured (design D6). Before running, the + * suite checks that every operation in the standard registry is covered by a step and fails if + * one is not (design D8). + */ +public final class SmokeSuite { + + private static final ObjectMapper JSON = new ObjectMapper(); + + private static final long TIMEOUT_SECONDS = 60; + + /** + * One invocation. + * + * @param covers the operation tuple this step is the real invocation of, or {@code null} + * @param args arguments after the executable + * @param stdin standard input, or {@code null} + * @param exit expected exit code + * @param expect substrings stdout must contain + */ + record Step(String covers, List args, String stdin, int exit, List expect) { + + static Step of(String covers, int exit, String args, String... expect) { + return new Step(covers, List.of(args.split(" ")), null, exit, List.of(expect)); + } + + Step withStdin(String input) { + return new Step(covers, args, input, exit, expect); + } + + /** Appends one argument verbatim, for paths that may contain spaces. */ + Step plus(Object arg) { + List more = new ArrayList<>(args); + more.add(arg.toString()); + return new Step(covers, more, stdin, exit, expect); + } + } + + private SmokeSuite() { + } + + public static void main(String[] argv) throws Exception { + if (argv.length == 0) { + System.err.println("Usage: SmokeSuite [args before the command ...]"); + System.exit(2); + } + Set missing = missing(); + if (!missing.isEmpty()) { + System.err.println("Operations with no smoke step: " + missing); + System.exit(1); + } + List prefix = List.of(argv); + Path work = Files.createTempDirectory("ict-smoke"); + Path data = Files.createDirectories(work.resolve("data")); + Path fixtures = Fixtures.write(Files.createDirectories(work.resolve("fixtures"))); + + int failures = 0; + for (Step step : steps(fixtures)) { + failures += run(prefix, data, step) ? 0 : 1; + } + failures += mcpHandshake(prefix, data) ? 0 : 1; + + System.out.println(failures == 0 ? "Smoke suite passed" : "Smoke suite FAILED: " + failures + " step(s)"); + System.exit(failures == 0 ? 0 : 1); + } + + /** Operation tuples in the standard registry that no step claims to cover. */ + public static Set missing() { + Set missing = new LinkedHashSet<>(); + Operations.standard().all().forEach(op -> missing.add(op.id().toString())); + steps(Path.of("fixtures")).forEach(s -> missing.remove(s.covers())); + return missing; + } + + static List steps(Path fixtures) { + List steps = new ArrayList<>(); + steps.add(Step.of(null, 0, "--help", "Commands:", "mcp")); + steps.add(Step.of(null, 0, "--version", "ict ")); + for (Operation op : Operations.standard().forSurface(Surface.CLI)) { + steps.add(Step.of(null, 0, op.id().verbKey() + " " + op.id().subjectKey() + " --help", leadingWords(op.description()))); + } + steps.add(Step.of(null, 2, "list")); + + steps.add(Step.of("add collection in workspace", 0, "add collection --collection work", "Added calendar collection 'work'")); + steps.add(Step.of(null, 0, "add collection --collection people --type card --description Contacts")); + steps.add(Step.of("list collection in workspace", 0, "list collection --format json", "\"work\"", "\"people\"")); + steps.add(Step.of("get collection in workspace", 0, "get collection --collection people --type card", "description: Contacts")); + steps.add(Step.of(null, 1, "get collection --collection missing")); + + // ServiceLoader factories: VEVENT/VTODO/VJOURNAL/VAVAILABILITY are all created through + // ical4j's ComponentFactory services, X-WR-CALNAME through ical4j-extensions' PropertyFactory. + steps.add(Step.of("import calendar in collection", 0, "import calendar --collection work --file", "tz1@ict") + .plus(fixtures.resolve("smoke.ics"))); + steps.add(Step.of(null, 0, "import calendar --collection work", "av1@ict").withStdin(Fixtures.AVAILABILITY)); + steps.add(Step.of("list event in collection", 0, "list event --collection work", "tz1@ict", "Melbourne meeting")); + steps.add(Step.of("list action in collection", 0, "list action --collection work", "todo1@ict")); + steps.add(Step.of("list note in collection", 0, "list note --collection work", "note1@ict")); + + // Time zones: the VTIMEZONE comes from ical4j's zoneinfo resources. + steps.add(Step.of("export calendar in collection", 0, "export calendar --collection work --uid tz1@ict", + "BEGIN:VCALENDAR", "X-WR-CALNAME:Smoke", "X-ICT-SMOKE:yes", "BEGIN:VTIMEZONE", "TZID:Australia/Melbourne")); + steps.add(Step.of(null, 0, "export calendar --collection work --uid av1@ict", + "BEGIN:VAVAILABILITY", "BEGIN:AVAILABLE", "RRULE:FREQ=WEEKLY")); + steps.add(Step.of(null, 0, "export calendar --collection work --uid tz1@ict --format json", "\"vcalendar\"", "\"vtimezone\"")); + steps.add(Step.of(null, 0, "export calendar --collection work --uid tz1@ict --format xml", + "urn:ietf:params:xml:ns:icalendar-2.0", "")); + steps.add(Step.of(null, 0, "export calendar --collection work", "UID:tz1@ict", "UID:todo1@ict", "UID:av1@ict")); + steps.add(Step.of("remove calendar in collection", 0, "remove calendar --collection work --uid note1@ict", "Removed calendar")); + steps.add(Step.of(null, 1, "remove calendar --collection work --uid note1@ict")); + + steps.add(Step.of("import card in collection", 0, "import card --collection people --file", "ada@ict") + .plus(fixtures.resolve("ada.vcf"))); + steps.add(Step.of("list entity in collection", 0, "list entity --collection people", "Ada Lovelace")); + steps.add(Step.of("export card in collection", 0, "export card --collection people --uid ada@ict", + "BEGIN:VCARD", "FN:Ada Lovelace")); + steps.add(Step.of("remove card in collection", 0, "remove card --collection people --uid ada@ict", "Removed card")); + steps.add(Step.of("remove collection in workspace", 0, "remove collection --collection people --type card", + "Removed card collection 'people'")); + + steps.add(Step.of(null, 0, "config workspace.active", "default")); + return steps; + } + + /** The start of a description, short enough that usage help never wraps it. */ + private static String leadingWords(String text) { + if (text.length() <= 40) { + return text; + } + int cut = text.lastIndexOf(' ', 40); + return text.substring(0, cut > 0 ? cut : 40); + } + + private static boolean run(List prefix, Path data, Step step) throws IOException, InterruptedException { + long start = System.nanoTime(); + List command = new ArrayList<>(prefix); + command.addAll(step.args()); + Process process = start(command, data); + try (OutputStream in = process.getOutputStream()) { + if (step.stdin() != null) { + in.write(step.stdin().getBytes(StandardCharsets.UTF_8)); + } + } + // Drain stderr concurrently so a chatty process cannot block on a full pipe. + StringBuilder err = new StringBuilder(); + Thread errPump = pump(process, err); + String out = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + if (!process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + process.destroyForcibly(); + return report(false, step.args(), start, "timed out"); + } + errPump.join(); + List problems = new ArrayList<>(); + if (process.exitValue() != step.exit()) { + problems.add("exit " + process.exitValue() + ", expected " + step.exit()); + } + for (String expected : step.expect()) { + if (!out.contains(expected)) { + problems.add("stdout lacks '" + expected + "'"); + } + } + if (step.exit() == 0 && !err.toString().isBlank()) { + problems.add("unexpected stderr"); + } + String detail = problems.isEmpty() ? "" : String.join("; ", problems) + "\n--- stdout\n" + out + "--- stderr\n" + err; + return report(problems.isEmpty(), step.args(), start, detail); + } + + /** initialize, tools/list, tools/call, then EOF: exit 0 and nothing but JSON-RPC on stdout. */ + private static boolean mcpHandshake(List prefix, Path data) throws IOException, InterruptedException { + long start = System.nanoTime(); + List command = new ArrayList<>(prefix); + command.add("mcp"); + Process process = start(command, data); + StringBuilder err = new StringBuilder(); + Thread errPump = pump(process, err); + List problems = new ArrayList<>(); + try (OutputStream in = process.getOutputStream(); + BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { + Map init = rpc(in, out, 1, "initialize", Map.of("protocolVersion", "2025-06-18", + "capabilities", Map.of(), "clientInfo", Map.of("name", "smoke", "version", "1"))); + if (!"ict".equals(((Map) ((Map) init.get("result")).get("serverInfo")).get("name"))) { + problems.add("initialize: unexpected serverInfo " + init); + } + send(in, Map.of("jsonrpc", "2.0", "method", "notifications/initialized")); + List tools = (List) ((Map) rpc(in, out, 2, "tools/list", Map.of()).get("result")).get("tools"); + long exposed = Operations.standard().forSurface(Surface.MCP).size(); + if (tools.size() != exposed) { + problems.add("tools/list: " + tools.size() + " tools, expected " + exposed); + } + Map call = (Map) rpc(in, out, 3, "tools/call", + Map.of("name", "export_calendar", "arguments", Map.of("collection", "work", "uid", "tz1@ict"))).get("result"); + String text = String.valueOf(((Map) ((List) call.get("content")).get(0)).get("text")); + if (Boolean.TRUE.equals(call.get("isError")) || !text.contains("TZID:Australia/Melbourne")) { + problems.add("tools/call export_calendar: " + call); + } + in.close(); + String trailing = out.readLine(); + if (trailing != null) { + problems.add("stdout after EOF: " + trailing); + } + } catch (RuntimeException | IOException e) { + problems.add(e.toString()); + } + if (!process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + process.destroyForcibly(); + problems.add("did not exit after EOF"); + } else if (process.exitValue() != 0) { + problems.add("exit " + process.exitValue()); + } + errPump.join(); + String detail = problems.isEmpty() ? "" : String.join("; ", problems) + "\n--- stderr\n" + err; + return report(problems.isEmpty(), List.of("mcp", "(handshake)"), start, detail); + } + + private static Map rpc(OutputStream in, BufferedReader out, int id, String method, Map params) + throws IOException { + send(in, Map.of("jsonrpc", "2.0", "id", id, "method", method, "params", params)); + String line = out.readLine(); + if (line == null) { + throw new IOException("no response to " + method); + } + Map response = JSON.readValue(line, Map.class); + if (!"2.0".equals(response.get("jsonrpc")) || !Integer.valueOf(id).equals(response.get("id"))) { + throw new IOException("not a JSON-RPC response to " + method + ": " + line); + } + return response; + } + + private static void send(OutputStream in, Map message) throws IOException { + in.write((JSON.writeValueAsString(message) + "\n").getBytes(StandardCharsets.UTF_8)); + in.flush(); + } + + private static Process start(List command, Path data) throws IOException { + ProcessBuilder builder = new ProcessBuilder(command); + builder.environment().put(Filesystem.DATA_DIR_ENV, data.toString()); + builder.environment().remove("ICT_LOG_LEVEL"); + return builder.start(); + } + + private static Thread pump(Process process, StringBuilder into) { + Thread t = new Thread(() -> { + try { + String s = new String(process.getErrorStream().readAllBytes(), StandardCharsets.UTF_8); + synchronized (into) { + into.append(s); + } + } catch (IOException e) { + synchronized (into) { + into.append(e); + } + } + }); + t.start(); + return t; + } + + private static boolean report(boolean ok, List args, long start, String detail) { + long ms = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + System.out.printf("%s %5d ms ict %s%n", ok ? "PASS" : "FAIL", ms, String.join(" ", args)); + if (!ok) { + System.out.println(detail.indent(4)); + } + return ok; + } + + /** Input files. */ + static final class Fixtures { + + static final String AVAILABILITY = String.join("\r\n", + "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//ict smoke//EN", + "BEGIN:VAVAILABILITY", "UID:av1@ict", "DTSTAMP:20260101T000000Z", + "DTSTART;TZID=Australia/Melbourne:20260101T090000", + "BEGIN:AVAILABLE", "UID:av1-a@ict", "DTSTAMP:20260101T000000Z", + "DTSTART;TZID=Australia/Melbourne:20260105T090000", "DTEND;TZID=Australia/Melbourne:20260105T170000", + "RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR", "END:AVAILABLE", + "END:VAVAILABILITY", "END:VCALENDAR", ""); + + static final String CALENDAR = String.join("\r\n", + "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//ict smoke//EN", "X-WR-CALNAME:Smoke", + "BEGIN:VEVENT", "UID:tz1@ict", "DTSTAMP:20260101T000000Z", + "DTSTART;TZID=Australia/Melbourne:20260310T100000", "DTEND;TZID=Australia/Melbourne:20260310T110000", + "SUMMARY:Melbourne meeting", "X-ICT-SMOKE:yes", "END:VEVENT", + "BEGIN:VTODO", "UID:todo1@ict", "DTSTAMP:20260101T000000Z", "SUMMARY:Smoke todo", "END:VTODO", + "BEGIN:VJOURNAL", "UID:note1@ict", "DTSTAMP:20260101T000000Z", "SUMMARY:Smoke note", "END:VJOURNAL", + "END:VCALENDAR", ""); + + static final String CARD = String.join("\r\n", + "BEGIN:VCARD", "VERSION:4.0", "UID:ada@ict", "FN:Ada Lovelace", "N:Lovelace;Ada;;;", "END:VCARD", ""); + + private Fixtures() { + } + + static Path write(Path dir) throws IOException { + Files.writeString(dir.resolve("smoke.ics"), CALENDAR); + Files.writeString(dir.resolve("ada.vcf"), CARD); + return dir; + } + } +} diff --git a/src/smoke/java/org/ical4j/command/smoke/StartupTime.java b/src/smoke/java/org/ical4j/command/smoke/StartupTime.java new file mode 100644 index 0000000..30147e8 --- /dev/null +++ b/src/smoke/java/org/ical4j/command/smoke/StartupTime.java @@ -0,0 +1,54 @@ +package org.ical4j.command.smoke; + +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +/** + * Measures {@code ict --help} wall-clock time over several runs and fails if the median exceeds + * a limit. Usage: {@code StartupTime [runs=10] [limit-ms=100]}. One unmeasured + * warm-up run comes first so the file cache does not count against the binary. + */ +public final class StartupTime { + + private StartupTime() { + } + + public static void main(String[] args) throws IOException, InterruptedException { + if (args.length == 0) { + System.err.println("Usage: StartupTime [runs] [limit-ms]"); + System.exit(2); + } + String binary = args[0]; + int runs = args.length > 1 ? Integer.parseInt(args[1]) : 10; + long limit = args.length > 2 ? Long.parseLong(args[2]) : 100; + + time(binary); + long[] millis = new long[runs]; + for (int i = 0; i < runs; i++) { + millis[i] = time(binary); + } + long[] sorted = millis.clone(); + Arrays.sort(sorted); + double median = runs % 2 == 1 ? sorted[runs / 2] : (sorted[runs / 2 - 1] + sorted[runs / 2]) / 2.0; + + System.out.printf("ict --help over %d runs: median %.1f ms, min %d ms, max %d ms (limit %d ms)%n", + runs, median, sorted[0], sorted[runs - 1], limit); + if (median > limit) { + System.out.println("Startup time FAILED: median exceeds " + limit + " ms"); + System.exit(1); + } + } + + private static long time(String binary) throws IOException, InterruptedException { + long start = System.nanoTime(); + Process process = new ProcessBuilder(binary, "--help") + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + throw new IllegalStateException(binary + " --help failed"); + } + return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + } +} diff --git a/src/test/groovy/org/ical4j/command/cli/CommandTreeTest.groovy b/src/test/groovy/org/ical4j/command/cli/CommandTreeTest.groovy new file mode 100644 index 0000000..bd5bfc9 --- /dev/null +++ b/src/test/groovy/org/ical4j/command/cli/CommandTreeTest.groovy @@ -0,0 +1,232 @@ +package org.ical4j.command.cli + +import org.ical4j.command.Version +import org.ical4j.command.config.CommandConfig +import org.ical4j.command.ops.Operation +import org.ical4j.command.ops.OperationException +import org.ical4j.command.ops.Param +import org.ical4j.command.ops.Params +import org.ical4j.command.ops.Registry +import org.ical4j.command.ops.Result +import org.ical4j.command.ops.Surface +import org.ical4j.command.vocab.EntityType +import org.ical4j.command.vocab.Locus +import org.ical4j.command.vocab.SerializationFamily +import org.ical4j.command.vocab.Verb +import spock.lang.Specification +import spock.lang.TempDir + +import java.nio.file.Path + +/** + * The CLI view built from a stub registry: tree shape, option derivation, exit codes and the + * stdout/stderr split. Handlers here are stubs; real operations are covered by MainTest. + */ +class CommandTreeTest extends Specification { + + @TempDir + Path dir + + ByteArrayOutputStream out = new ByteArrayOutputStream() + ByteArrayOutputStream err = new ByteArrayOutputStream() + Params received + + def 'root help lists one command per verb with CLI operations, plus config'() { + when: + def code = run(registry(), '--help') + + then: + code == 0 + commands(out.toString()) == ['list', 'export', 'config', 'mcp'] + err.toString().isEmpty() + } + + def 'verb help lists the types under that verb'() { + when: + def code = run(registry(), 'list', '--help') + + then: + code == 0 + commands(out.toString()) == ['event', 'collection'] + } + + def 'operations not exposed to the CLI have no command'() { + given: + def reg = Registry.builder() + .add(stub(Verb.LIST, EntityType.EVENT, Locus.COLLECTION)) + .add(Operation.define(Verb.REMOVE, EntityType.EVENT, Locus.COLLECTION).description('mcp only') + .only(Surface.MCP).handler({ c, p -> new Result.Status('x') }).build()) + .build() + + when: + run(reg, '--help') + + then: + commands(out.toString()) == ['list', 'config', 'mcp'] + } + + def 'options are derived from parameter descriptors'() { + given: + def op = Operation.define(Verb.LIST, EntityType.EVENT, Locus.COLLECTION).description('d') + .params(Param.string('collection', 'Collection name').asRequired(), + Param.integer('limit', 'At most this many'), + Param.bool('all', 'Everything'), + Param.choice('kind', 'Kind of thing', ['a', 'b']).defaultTo('a'), + Param.path('file', 'Input file').asMultiple()) + .handler({ c, p -> received = p; new Result.Status('ok') }).build() + def cli = Main.commandLine(Registry.builder().add(op).build(), out, err, + InputStream.nullInputStream(), { new CommandConfig(dir.toFile()) }) + def leaf = cli.subcommands.list.subcommands.event.commandSpec + + expect: + with(leaf.findOption('--collection')) { + required() + type() == String + description()[0] == 'Collection name' + } + !leaf.findOption('--limit').required() + leaf.findOption('--all').type() == boolean + leaf.findOption('--kind').completionCandidates().toList() == ['a', 'b'] + leaf.findOption('--kind').description()[0] == 'Kind of thing (one of: a, b) (default: a)' + leaf.findOption('--file').type() == String[] + leaf.positionalParameters().isEmpty() + + when: + def code = cli.execute('list', 'event', '--collection', 'work', '--all', '--file', 'x.ics', '--file', 'y.ics') + + then: 'only matched options reach the handler, and descriptor defaults are applied' + code == 0 + received.asMap() == [collection: 'work', all: true, file: ['x.ics', 'y.ics'], kind: 'a'] + out.toString() == 'ok\n' + } + + def 'two operations with the same verb and subject cannot both be on the CLI'() { + given: + def reg = Registry.builder() + .add(stub(Verb.LIST, Locus.COLLECTION, Locus.WORKSPACE)) + .add(stub(Verb.LIST, Locus.COLLECTION, Locus.NONE)) + .build() + + when: + run(reg, '--help') + + then: + def e = thrown(IllegalStateException) + e.message.contains("'list collection in workspace'") + e.message.contains("'list collection'") + } + + def 'a parameter may not shadow a global option'() { + given: + def reg = Registry.builder().add(Operation.define(Verb.LIST, EntityType.EVENT, Locus.COLLECTION) + .description('d').params(Param.string('format', 'x')) + .handler({ c, p -> new Result.Status('x') }).build()).build() + + when: + run(reg, '--help') + + then: + def e = thrown(IllegalStateException) + e.message.contains('--format') + } + + def 'exit codes: #scenario'() { + when: + def code = run(registry(), *args) + + then: + code == expected + (out.toString().isEmpty()) == (expected != 0) + (err.toString().isEmpty()) == (expected == 0) + err.toString().contains(diagnostic) + + where: + scenario | args | expected | diagnostic + 'success' | ['list', 'event', '--collection', 'work'] | 0 | '' + 'not found' | ['list', 'event', '--collection', 'missing'] | 1 | 'ict: No such collection: missing' + 'store failure' | ['list', 'event', '--collection', 'broken'] | 1 | 'ict: disk on fire' + 'missing type' | ['list'] | 2 | 'Usage: ict list' + 'no command' | [] | 2 | 'Usage: ict' + 'unknown type' | ['list', 'widget'] | 2 | "Unmatched argument at index 1: 'widget'" + 'missing required' | ['list', 'event'] | 2 | "Missing required option: '--collection='" + 'usage from handler' | ['list', 'event', '--collection', 'usage'] | 2 | "Try 'ict list event --help'" + 'xml for a list' | ['list', 'event', '--collection', 'work', '--format', 'xml'] | 2 | 'XML output is only available' + 'unexpected exception' | ['list', 'event', '--collection', 'bug'] | 1 | 'java.lang.IllegalArgumentException: bad' + } + + def 'global options apply on either side of the verb'() { + when: + run(registry(), *args) + + then: + out.toString().trim() == '[ "e1@ict" ]' + + where: + args << [['--format', 'json', 'list', 'event', '--collection', 'work'], + ['list', 'event', '--collection', 'work', '--format', 'JSON']] + } + + def 'workspace option overrides the configured workspace'() { + given: + def reg = Registry.builder().add(Operation.define(Verb.LIST, Locus.COLLECTION, Locus.WORKSPACE) + .description('d').handler({ c, p -> new Result.Status(c.activeWorkspace()) }).build()).build() + + expect: + run(reg, 'list', 'collection') == 0 + out.toString() == 'default\n' + + when: + out.reset() + run(reg, 'list', 'collection', '--workspace', 'other') + + then: + out.toString() == 'other\n' + } + + def 'version prints the embedded build version to stdout'() { + when: + def code = run(registry(), '--version') + + then: + code == 0 + out.toString().startsWith("ict ${Version.get()} ") + Version.get() != 'unknown' + } + + // ---- fixtures --------------------------------------------------------------------------- + + private int run(Registry registry, String... args) { + Main.commandLine(registry, out, err, InputStream.nullInputStream(), + { new CommandConfig(dir.toFile()) }).execute(args) + } + + private static Registry registry() { + Registry.builder() + .add(Operation.define(Verb.LIST, EntityType.EVENT, Locus.COLLECTION).description('List events') + .params(Param.string('collection', 'Collection name').asRequired()) + .handler({ c, p -> + switch (p.require('collection')) { + case 'missing': throw new OperationException.NotFound('No such collection: missing') + case 'broken': throw new OperationException.Store('disk on fire', null) + case 'usage': throw new OperationException.Usage('bad usage') + case 'bug': throw new IllegalArgumentException('bad') + default: return new Result.Identifiers(['e1@ict']) + } + }).build()) + .add(stub(Verb.LIST, Locus.COLLECTION, Locus.WORKSPACE)) + .add(stub(Verb.EXPORT, SerializationFamily.CALENDAR, Locus.COLLECTION)) + .build() + } + + private static Operation stub(Verb verb, def subject, Locus locus) { + Operation.define(verb, subject, locus).description("stub ${verb} ${subject}") + .handler({ c, p -> new Result.Status('ok') }).build() + } + + /** Command names from the commands/types section of usage help. */ + private static List commands(String help) { + def lines = help.readLines() + def start = lines.findIndexOf { it ==~ /(Commands|Types):/ } + lines.drop(start + 1).takeWhile { it.startsWith(' ') }.collect { it.trim().split(/\s+/)[0] } + } +} diff --git a/src/test/groovy/org/ical4j/command/cli/LogLevelTest.groovy b/src/test/groovy/org/ical4j/command/cli/LogLevelTest.groovy new file mode 100644 index 0000000..edb887f --- /dev/null +++ b/src/test/groovy/org/ical4j/command/cli/LogLevelTest.groovy @@ -0,0 +1,63 @@ +package org.ical4j.command.cli + +import spock.lang.Specification + +class LogLevelTest extends Specification { + + def 'verbose flags map to levels'() { + expect: + LogLevel.fromVerbosity(LogLevel.countVerbose(args as String[])) == level + + where: + args | level + [] | null + ['list'] | null + ['-v', 'list'] | 'info' + ['--verbose', 'list'] | 'info' + ['-vv'] | 'debug' + ['-v', '-v'] | 'debug' + ['-vvv'] | 'trace' + ['--', '-v'] | null + ['-verbose'] | null + ['-version'] | null + } + + def 'quiet selects error unless verbosity or the environment says otherwise'() { + given: + def previous = System.getProperty('org.slf4j.simpleLogger.defaultLogLevel') + System.clearProperty('org.slf4j.simpleLogger.defaultLogLevel') + + when: + LogLevel.configure(args as String[], env) + + then: + System.getProperty('org.slf4j.simpleLogger.defaultLogLevel') == level + + cleanup: + if (previous == null) System.clearProperty('org.slf4j.simpleLogger.defaultLogLevel') + else System.setProperty('org.slf4j.simpleLogger.defaultLogLevel', previous) + + where: + args | env | level + ['-q', 'list'] | null | 'error' + ['--quiet'] | null | 'error' + ['-q', '-v'] | null | 'info' + ['-q'] | 'warn' | 'warn' + ['--', '-q'] | null | null + } + + def 'environment overrides flags'() { + given: + def previous = System.getProperty('org.slf4j.simpleLogger.defaultLogLevel') + + when: + LogLevel.configure(['-vv'] as String[], 'ERROR') + + then: + System.getProperty('org.slf4j.simpleLogger.defaultLogLevel') == 'error' + + cleanup: + if (previous == null) System.clearProperty('org.slf4j.simpleLogger.defaultLogLevel') + else System.setProperty('org.slf4j.simpleLogger.defaultLogLevel', previous) + } +} diff --git a/src/test/groovy/org/ical4j/command/cli/MainTest.groovy b/src/test/groovy/org/ical4j/command/cli/MainTest.groovy new file mode 100644 index 0000000..0fea208 --- /dev/null +++ b/src/test/groovy/org/ical4j/command/cli/MainTest.groovy @@ -0,0 +1,193 @@ +package org.ical4j.command.cli + +import com.fasterxml.jackson.databind.ObjectMapper +import org.ical4j.command.config.CommandConfig +import org.ical4j.command.ops.OperationId +import org.ical4j.command.ops.Operations +import org.ical4j.command.ops.Surface +import spock.lang.Shared +import spock.lang.Specification +import spock.lang.Stepwise +import spock.lang.TempDir + +import java.nio.charset.StandardCharsets +import java.nio.file.Path + +import static org.ical4j.command.ops.Fixtures.card +import static org.ical4j.command.ops.Fixtures.event +import static org.ical4j.command.ops.Fixtures.todo +import static org.ical4j.command.ops.Fixtures.write + +/** + * Runs {@link Main} in-process, as a user would, against a temp-dir store: one scenario per + * CLI-exposed operation in the standard registry, in an order that builds up state. + */ +@Stepwise +class MainTest extends Specification { + + @Shared + @TempDir + Path dir + + @Shared + Set exercised = [] + + def "'add collection in workspace': ict add collection"() { + expect: + ict('add', 'collection', '--collection', 'work') == ok("Added calendar collection 'work'\n") + ict('add', 'collection', '--collection', 'people', '--type', 'card', '--description', 'Contacts') == + ok("Added card collection 'people'\n") + ict('add', 'collection', '--collection', 'work').code == 1 + + cleanup: + exercised << 'add collection in workspace' + } + + def "'list collection in workspace': ict list collection"() { + when: + def text = ict('list', 'collection') + def json = ict('list', 'collection', '--format', 'json') + + then: + text.code == 0 + text.out.readLines()[0].split(/\s+/) as List == ['name', 'type', 'description', 'objects'] + text.out.readLines()*.split(/\s+/)*.getAt(0).drop(1) == ['work', 'people'] + json.code == 0 + new ObjectMapper().readValue(json.out, List)*.name == ['work', 'people'] + + cleanup: + exercised << 'list collection in workspace' + } + + def "'get collection in workspace': ict get collection"() { + expect: + ict('get', 'collection', '--collection', 'people', '--type', 'card').out == + 'name: people\ntype: card\ndescription: Contacts\nobjects: 0\n' + ict('get', 'collection', '--collection', 'missing') == fail(1, 'ict: No such collection: missing\n') + + cleanup: + exercised << 'get collection in workspace' + } + + def "'import calendar in collection': ict import calendar from a file and from stdin"() { + given: + def file = write(dir, 'e1.ics', event('e1@ict', 'Planning')) + + expect: + ict('import', 'calendar', '--collection', 'work', '--file', file.toString()) == ok('e1@ict\n') + piped(todo('t1@ict', 'Write tests'), 'import', 'calendar', '--collection', 'work') == ok('t1@ict\n') + ict('import', 'calendar', '--collection', 'work', '--file', dir.resolve('none.ics').toString()).code == 1 + + cleanup: + exercised << 'import calendar in collection' + } + + def "'list event in collection', 'list action in collection', 'list note in collection': ict list "() { + expect: + ict('list', 'event', '--collection', 'work').out.readLines()[1].startsWith('e1@ict Planning') + ict('list', 'action', '--collection', 'work').out.readLines()[1].startsWith('t1@ict Write tests') + ict('list', 'note', '--collection', 'work') == ok('') + ict('list', 'event', '--collection', 'missing').code == 1 + + cleanup: + exercised.addAll(['list event in collection', 'list action in collection', 'list note in collection']) + } + + def "'export calendar in collection': ict export calendar"() { + when: + def one = ict('export', 'calendar', '--collection', 'work', '--uid', 'e1@ict') + def all = ict('export', 'calendar', '--collection', 'work') + def json = ict('export', 'calendar', '--collection', 'work', '--uid', 'e1@ict', '--format', 'json') + + then: + one.code == 0 + one.out.startsWith('BEGIN:VCALENDAR') + one.out.contains('SUMMARY:Planning') + all.out.contains('UID:e1@ict') && all.out.contains('UID:t1@ict') + json.out.startsWith('[ "vcalendar"') + ict('export', 'calendar', '--collection', 'work', '--uid', 'nope').code == 1 + + cleanup: + exercised << 'export calendar in collection' + } + + def "'remove calendar in collection': ict remove calendar"() { + expect: + ict('remove', 'calendar', '--collection', 'work', '--uid', 't1@ict') == ok("Removed calendar 't1@ict'\n") + ict('remove', 'calendar', '--collection', 'work', '--uid', 't1@ict') == fail(1, "ict: No such calendar: t1@ict\n") + ict('remove', 'calendar', '--collection', 'work').code == 2 + + cleanup: + exercised << 'remove calendar in collection' + } + + def "'import card in collection', 'list entity in collection', 'export card in collection', 'remove card in collection'"() { + given: + def file = write(dir, 'ada.vcf', card('c1@ict', 'Ada Lovelace')) + + expect: + ict('import', 'card', '--collection', 'people', '--file', file.toString()) == ok('c1@ict\n') + ict('list', 'entity', '--collection', 'people').out == 'uid name\nc1@ict Ada Lovelace\n' + ict('export', 'card', '--collection', 'people', '--uid', 'c1@ict').out.startsWith('BEGIN:VCARD') + ict('remove', 'card', '--collection', 'people', '--uid', 'c1@ict') == ok("Removed card 'c1@ict'\n") + ict('list', 'entity', '--collection', 'people') == ok('') + + cleanup: + exercised.addAll(['import card in collection', 'list entity in collection', 'export card in collection', + 'remove card in collection']) + } + + def "'remove collection in workspace': ict remove collection"() { + expect: + ict('remove', 'collection', '--collection', 'people', '--type', 'card') == ok("Removed card collection 'people'\n") + ict('list', 'collection').out.readLines()*.split(/\s+/)*.getAt(0).drop(1) == ['work'] + + cleanup: + exercised << 'remove collection in workspace' + } + + def 'ict config reads and writes the configuration file'() { + expect: + ict('config', 'workspace.active') == ok('default\n') + ict('config', 'user.name', 'Ada', 'Lovelace') == ok("Set 'user.name' to 'Ada Lovelace'\n") + ict('config', 'user.name') == ok('Ada Lovelace\n') + ict('config').out.readLines().contains('user.name = Ada Lovelace') + ict('config', 'nonsense.key', 'x').code == 1 + ict('config', 'user.nobody').code == 1 + } + + def 'every CLI operation in the standard registry was exercised above'() { + expect: + Operations.standard().forSurface(Surface.CLI)*.id()*.toString().toSet() - exercised == [] as Set + exercised.every { OperationId.parse(it) } + } + + // ---- fixtures --------------------------------------------------------------------------- + + private Run ict(String... args) { + piped(null, args) + } + + private Run piped(String stdin, String... args) { + def out = new ByteArrayOutputStream() + def err = new ByteArrayOutputStream() + def input = new ByteArrayInputStream((stdin ?: '').getBytes(StandardCharsets.UTF_8)) + int code = Main.run(args, out, err, input, { new CommandConfig(dir.toFile()) }) + new Run(code, out.toString(StandardCharsets.UTF_8).normalize(), err.toString(StandardCharsets.UTF_8)) + } + + private static Run ok(String out) { + new Run(0, out, '') + } + + private static Run fail(int code, String err) { + new Run(code, '', err) + } + + @groovy.transform.Canonical + static class Run { + int code + String out + String err + } +} diff --git a/src/test/groovy/org/ical4j/command/config/CommandConfigTest.groovy b/src/test/groovy/org/ical4j/command/config/CommandConfigTest.groovy new file mode 100644 index 0000000..43d8b0d --- /dev/null +++ b/src/test/groovy/org/ical4j/command/config/CommandConfigTest.groovy @@ -0,0 +1,77 @@ +package org.ical4j.command.config + +import spock.lang.Specification +import spock.lang.TempDir + +import java.nio.file.Path + +class CommandConfigTest extends Specification { + + @TempDir + Path dataDir + + def 'defaults come from the bundled resource and the file is created under the data directory'() { + when: + def config = new CommandConfig(dataDir.toFile()) + + then: + config.activeWorkspace == 'default' + config.userAgent == 'ict/1.0' + config.configFile() == dataDir.resolve('iCal4j/ictrc.toml').toFile() + config.configFile().exists() + config.configFile().text.contains('[workspace]') + } + + def 'settings persist to the file and survive a reload'() { + given: + def config = new CommandConfig(dataDir.toFile()) + + when: + def previous = config.setActiveWorkspace('work') + + then: + previous == 'default' + config.activeWorkspace == 'work' + new CommandConfig(dataDir.toFile()).activeWorkspace == 'work' + } + + def 'store directories sit under the application directory and are configurable'() { + given: + def config = new CommandConfig(dataDir.toFile()) + + expect: + config.calendarStoreDirectory() == dataDir.resolve('iCal4j/calendars').toFile() + config.cardStoreDirectory() == dataDir.resolve('iCal4j/vcards').toFile() + + when: + config.setCalendarStorePath('cal') + + then: + config.calendarStoreDirectory() == dataDir.resolve('iCal4j/cal').toFile() + } + + def 'the context carries the active workspace and opens local stores lazily'() { + given: + def config = new CommandConfig(dataDir.toFile()) + config.setActiveWorkspace('work') + + when: + def context = config.context() + + then: + context.activeWorkspace() == 'work' + !dataDir.resolve('iCal4j/calendars').toFile().exists() + + when: + context.calendarStore().addCollection('events', 'work') + + then: + dataDir.resolve('iCal4j/calendars/work/events').toFile().directory + + when: + context.cardStore().addCollection('people', 'work') + + then: + dataDir.resolve('iCal4j/vcards/work/people').toFile().directory + } +} diff --git a/src/test/groovy/org/ical4j/command/mcp/McpServerTest.groovy b/src/test/groovy/org/ical4j/command/mcp/McpServerTest.groovy new file mode 100644 index 0000000..c39bd8f --- /dev/null +++ b/src/test/groovy/org/ical4j/command/mcp/McpServerTest.groovy @@ -0,0 +1,190 @@ +package org.ical4j.command.mcp + +import com.fasterxml.jackson.databind.ObjectMapper +import org.ical4j.command.Version +import org.ical4j.command.cli.Main +import org.ical4j.command.config.CommandConfig +import org.ical4j.command.ops.Operations +import org.ical4j.command.ops.Surface +import org.ical4j.command.util.Filesystem +import spock.lang.Specification +import spock.lang.TempDir + +import java.nio.charset.StandardCharsets +import java.nio.file.Path +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit + +import static org.ical4j.command.ops.Fixtures.event +import static org.ical4j.command.ops.Fixtures.write + +/** + * {@code ict mcp} as a client sees it: a separate JVM spoken to over its real stdin and stdout, + * so the stdout discipline is tested where it matters. The child gets the test runtime + * classpath and an isolated data directory. + */ +class McpServerTest extends Specification { + + static final ObjectMapper JSON = new ObjectMapper() + + @TempDir + Path dir + + Client client + + def setup() { + // Seed a collection with one event through the CLI, in-process. + def config = { new CommandConfig(dir.toFile()) } + def sink = new ByteArrayOutputStream() + assert Main.run(['add', 'collection', '--collection', 'work'] as String[], sink, sink, InputStream.nullInputStream(), config) == 0 + def ics = write(dir, 'e.ics', event('e1@ict', 'Planning')) + assert Main.run(['import', 'calendar', '--collection', 'work', '--file', ics.toString()] as String[], sink, sink, + InputStream.nullInputStream(), config) == 0 + } + + def cleanup() { + client?.kill() + } + + def "initialize, tools/list and tools/call for 'list event in collection', then a clean shutdown on EOF"() { + given: + client = Client.start(dir) + + when: + def init = client.request('initialize', [protocolVersion: '2025-06-18', capabilities: [:], + clientInfo : [name: 'spec', version: '1']]) + client.notify('notifications/initialized') + + then: + init.result.serverInfo == [name: 'ict', version: Version.get()] + init.result.capabilities.tools != null + + when: + def tools = client.request('tools/list').result.tools + def listEvent = tools.find { it.name == 'list_event' } + + then: 'one tool per MCP-exposed operation' + tools*.name as Set == Operations.standard().forSurface(Surface.MCP).collect { Tools.name(it.id()) } as Set + listEvent.inputSchema.properties.collection.type == 'string' + listEvent.inputSchema.required == ['collection'] + + when: + def listed = client.request('tools/call', [name: 'list_event', arguments: [collection: 'work']]).result + + then: + !listed.isError + JSON.readValue(listed.content[0].text as String, List)*.uid == ['e1@ict'] + + when: 'a not-found failure is a tool result, and the server carries on' + def missing = client.request('tools/call', [name: 'get_collection', arguments: [collection: 'nope']]).result + def exported = client.request('tools/call', [name: 'export_calendar', arguments: [collection: 'work', uid: 'e1@ict']]).result + + then: + missing.isError + missing.content[0].text == 'No such collection: nope' + !exported.isError + exported.content[0].text.startsWith('BEGIN:VCALENDAR') + + when: + def exit = client.closeAndWait() + + then: + exit == 0 + client.unread().isEmpty() + } + + def 'with verbose logging every stdout line is a JSON-RPC message and the logs are on stderr'() { + given: + client = Client.start(dir, '-vvv') + + when: + client.request('initialize', [protocolVersion: '2025-06-18', capabilities: [:], clientInfo: [name: 'spec', version: '1']]) + client.notify('notifications/initialized') + client.request('tools/list') + client.request('tools/call', [name: 'list_collection', arguments: [:]]) + client.request('tools/call', [name: 'get_collection', arguments: [collection: 'nope']]) + def exit = client.closeAndWait() + + then: + exit == 0 + client.stdoutLines.size() == 4 + client.stdoutLines.every { line -> JSON.readValue(line, Map).jsonrpc == '2.0' } + def stderr = client.stderr() + stderr.contains('[DEBUG] Tools - Calling list collection in workspace') + stderr.contains('[INFO] McpCommand - MCP server ready') + } + + /** A minimal line-oriented JSON-RPC client over a child process's stdio. */ + static class Client { + final Process process + final LinkedBlockingQueue lines = new LinkedBlockingQueue<>() + final List stdoutLines = Collections.synchronizedList([]) + final ByteArrayOutputStream errBytes = new ByteArrayOutputStream() + final Thread stdoutPump + final Thread stderrPump + int nextId = 1 + + static Client start(Path dataDir, String... flags) { + def java = ProcessHandle.current().info().command().orElse('java') + def command = [java, '-cp', System.getProperty('java.class.path'), Main.name, 'mcp', *flags] + def builder = new ProcessBuilder(command) + builder.environment().put(Filesystem.DATA_DIR_ENV, dataDir.toString()) + builder.environment().remove('ICT_LOG_LEVEL') + new Client(builder.start()) + } + + Client(Process process) { + this.process = process + stdoutPump = Thread.start { + process.inputStream.newReader(StandardCharsets.UTF_8.name()).eachLine { line -> + stdoutLines << line + lines.put(line) + } + } + stderrPump = Thread.start { errBytes << process.errorStream } + } + + Map request(String method, Map params = null) { + int id = nextId++ + send([jsonrpc: '2.0', id: id, method: method] + (params == null ? [:] : [params: params])) + def line = lines.poll(30, TimeUnit.SECONDS) + assert line != null: "no response to $method; stderr:\n${stderr()}" + def response = JSON.readValue(line, Map) + assert response.id == id + response + } + + void notify(String method) { + send([jsonrpc: '2.0', method: method]) + } + + private void send(Map message) { + process.outputStream.write((JSON.writeValueAsString(message) + '\n').getBytes(StandardCharsets.UTF_8)) + process.outputStream.flush() + } + + int closeAndWait() { + process.outputStream.close() + assert process.waitFor(30, TimeUnit.SECONDS): "server did not exit after EOF; stderr:\n${stderr()}" + stdoutPump.join(5000) + stderrPump.join(5000) + process.exitValue() + } + + List unread() { + new ArrayList<>(lines) + } + + String stderr() { + synchronized (errBytes) { + errBytes.toString(StandardCharsets.UTF_8) + } + } + + void kill() { + if (process.alive) { + process.destroyForcibly() + } + } + } +} diff --git a/src/test/groovy/org/ical4j/command/mcp/ToolsTest.groovy b/src/test/groovy/org/ical4j/command/mcp/ToolsTest.groovy new file mode 100644 index 0000000..4a8b5a4 --- /dev/null +++ b/src/test/groovy/org/ical4j/command/mcp/ToolsTest.groovy @@ -0,0 +1,123 @@ +package org.ical4j.command.mcp + +import org.ical4j.command.ops.Context +import org.ical4j.command.ops.Operation +import org.ical4j.command.ops.OperationException +import org.ical4j.command.ops.Param +import org.ical4j.command.ops.Registry +import org.ical4j.command.ops.Result +import org.ical4j.command.ops.Surface +import org.ical4j.command.vocab.EntityType +import org.ical4j.command.vocab.Locus +import org.ical4j.command.vocab.SerializationFamily +import org.ical4j.command.vocab.Verb +import spock.lang.Specification + +/** + * Tool derivation from stub operations. The protocol round trip is covered by McpServerTest. + */ +class ToolsTest extends Specification { + + def 'tools are named _ and only MCP-exposed operations become tools'() { + given: + def registry = Registry.builder() + .add(stub(Verb.LIST, EntityType.EVENT, Locus.COLLECTION)) + .add(stub(Verb.IMPORT, SerializationFamily.CALENDAR, Locus.COLLECTION)) + .add(Operation.define(Verb.REMOVE, EntityType.EVENT, Locus.COLLECTION).description('cli only') + .only(Surface.CLI).handler({ c, p -> new Result.Status('x') }).build()) + .build() + + expect: + Tools.specifications(registry, { context() })*.tool()*.name() == ['list_event', 'import_calendar'] + } + + def 'the input schema is derived from the parameter descriptors'() { + given: + def op = Operation.define(Verb.LIST, EntityType.EVENT, Locus.COLLECTION).description('List events') + .params(Param.string('collection', 'Collection name').asRequired(), + Param.string('uid', 'One UID'), + Param.integer('limit', 'At most'), + Param.bool('all', 'Everything'), + Param.choice('kind', 'Kind', ['a', 'b']).defaultTo('b'), + Param.path('file', 'Files').asMultiple()) + .handler({ c, p -> new Result.Status('x') }).build() + + when: + def tool = Tools.tool(op) + + then: + tool.name() == 'list_event' + tool.description() == 'List events' + tool.annotations().readOnlyHint() + !tool.annotations().destructiveHint() + tool.inputSchema() == [ + type : 'object', + properties : [ + collection: [type: 'string', description: 'Collection name'], + uid : [type: 'string', description: 'One UID'], + limit : [type: 'integer', description: 'At most'], + all : [type: 'boolean', description: 'Everything', default: false], + kind : [type: 'string', enum: ['a', 'b'], description: 'Kind', default: 'b'], + file : [type: 'array', items: [type: 'string'], description: 'Files']], + required : ['collection'], + additionalProperties: false] + } + + def 'destructive verbs are annotated as such'() { + expect: + Tools.tool(stub(Verb.REMOVE, SerializationFamily.CALENDAR, Locus.COLLECTION)).annotations().destructiveHint() + } + + def 'a call runs the handler with the arguments; failures become isError results'() { + given: + def registry = Registry.builder().add(Operation.define(Verb.GET, Locus.COLLECTION, Locus.WORKSPACE) + .description('Get').params(Param.string('collection', 'Name').asRequired()) + .handler({ c, p -> + switch (p.require('collection')) { + case 'missing': throw new OperationException.NotFound('No such collection: missing') + case 'bug': throw new IllegalStateException('boom') + case 'ics': return new Result.CalendarData(new net.fortuna.ical4j.model.Calendar()) + default: return new Result.Descriptor([name: p.require('collection'), ws: c.activeWorkspace()]) + } + }).build()).build() + def handler = Tools.specifications(registry, { context() })[0].callHandler() + + expect: + call(handler, [collection: 'work']).with { !isError() && text(it) == '{"name":"work","ws":"default"}\n' } + call(handler, [collection: 'ics']).with { !isError() && text(it).startsWith('BEGIN:VCALENDAR') } + call(handler, [collection: 'missing']).with { isError() && text(it) == 'No such collection: missing' } + call(handler, [collection: 'bug']).with { isError() && text(it) == 'boom' } + call(handler, null).with { isError() && text(it) == 'Missing required parameter: collection' } + } + + def 'two exposed operations with the same tool name are rejected'() { + given: + def registry = Registry.builder() + .add(stub(Verb.LIST, Locus.COLLECTION, Locus.WORKSPACE)) + .add(stub(Verb.LIST, Locus.COLLECTION, Locus.NONE)) + .build() + + when: + Tools.specifications(registry, { context() }) + + then: + def e = thrown(IllegalStateException) + e.message.contains('list_collection') + } + + private static def call(handler, Map args) { + handler.apply(null, new io.modelcontextprotocol.spec.McpSchema.CallToolRequest('t', args, null)) + } + + private static String text(result) { + result.content()[0].text() + } + + private static Context context() { + Context.builder().build() + } + + private static Operation stub(Verb verb, def subject, Locus locus) { + Operation.define(verb, subject, locus).description('stub').handler({ c, p -> new Result.Status('ok') }).build() + } +} diff --git a/src/test/groovy/org/ical4j/command/ops/CalendarOperationsTest.groovy b/src/test/groovy/org/ical4j/command/ops/CalendarOperationsTest.groovy new file mode 100644 index 0000000..68c6b4e --- /dev/null +++ b/src/test/groovy/org/ical4j/command/ops/CalendarOperationsTest.groovy @@ -0,0 +1,145 @@ +package org.ical4j.command.ops + +import spock.lang.Specification +import spock.lang.TempDir + +import java.nio.file.Path + +import static org.ical4j.command.ops.Fixtures.* + +class CalendarOperationsTest extends Specification { + + @TempDir + Path dir + + Context ctx + + def setup() { + ctx = context(dir) + op('add collection in workspace').execute(ctx, Params.of(collection: 'events')) + } + + def "'import calendar in collection' merges a file and reports the UIDs"() { + given: + def file = write(dir, 'a.ics', event('a@ict', 'First')) + + when: + def result = op('import calendar in collection').execute(ctx, Params.of(collection: 'events', file: file.toString())) + + then: + (result as Result.Identifiers).ids() == ['a@ict'] + ctx.calendarStore().getCollection('events', 'work').listObjectUIDs() == ['a@ict'] + + when: + op('import calendar in collection').execute(ctx, Params.of(collection: 'missing', file: file.toString())) + + then: + thrown(OperationException.NotFound) + + when: + op('import calendar in collection').execute(ctx, Params.of(collection: 'events', file: dir.resolve('none.ics').toString())) + + then: + thrown(OperationException.NotFound) + } + + def "'import calendar in collection' reads standard input when no file is given"() { + given: + def stdin = Context.builder().activeWorkspace('work') + .calendarStore(ctx.calendarStore()).cardStore(ctx.cardStore()) + .stdin({ new ByteArrayInputStream(event('b@ict', 'Second').bytes) }).build() + + when: + def result = op('import calendar in collection').execute(stdin, Params.of(collection: 'events')) + + then: + (result as Result.Identifiers).ids() == ['b@ict'] + } + + def "'import calendar in collection' rejects data that does not parse"() { + given: + def file = write(dir, 'bad.ics', 'not a calendar') + + when: + op('import calendar in collection').execute(ctx, Params.of(collection: 'events', file: file.toString())) + + then: + thrown(OperationException.InvalidData) + } + + def "'export calendar in collection' returns one object by UID or the whole collection"() { + given: + op('import calendar in collection').execute(ctx, Params.of(collection: 'events', file: write(dir, 'a.ics', event('a@ict', 'First')).toString())) + op('import calendar in collection').execute(ctx, Params.of(collection: 'events', file: write(dir, 'b.ics', event('b@ict', 'Second')).toString())) + + when: + def one = op('export calendar in collection').execute(ctx, Params.of(collection: 'events', uid: 'a@ict')) as Result.CalendarData + + then: + one.calendar().getComponents()*.getUid()*.get()*.value == ['a@ict'] + + when: + def all = op('export calendar in collection').execute(ctx, Params.of(collection: 'events')) as Result.CalendarData + + then: + all.calendar().getComponents()*.getUid()*.get()*.value as Set == ['a@ict', 'b@ict'] as Set + + when: + op('export calendar in collection').execute(ctx, Params.of(collection: 'events', uid: 'nope')) + + then: + thrown(OperationException.NotFound) + } + + def "'export calendar in collection' adds a VTIMEZONE for each referenced TZID that lacks one"() { + given: + def ics = event('tz@ict', 'Melbourne').replace('DTSTART:20260910T100000Z', 'DTSTART;TZID=Australia/Melbourne:20260910T100000') + op('import calendar in collection').execute(ctx, Params.of(collection: 'events', file: write(dir, 'tz.ics', ics).toString())) + + when: + def calendar = (op('export calendar in collection').execute(ctx, Params.of(collection: 'events', uid: 'tz@ict')) as Result.CalendarData).calendar() + def zones = calendar.getComponents('VTIMEZONE') + + then: + zones*.getProperty('TZID')*.get()*.value == ['Australia/Melbourne'] + + and: 'a calendar that already carries its zones is unchanged' + CalendarOperations.withTimeZones(calendar).is(calendar) + } + + def "'import calendar in collection' accepts several objects that reference a TZID with no VTIMEZONE"() { + given: 'the connector alone fails on this input with a NullPointerException' + def ics = event('tz@ict', 'Melbourne').replace('DTSTART:20260910T100000Z', 'DTSTART;TZID=Australia/Melbourne:20260910T100000') + .replace('END:VCALENDAR', todo('t@ict', 'Todo').readLines()[3..-2].join('\n') + '\nEND:VCALENDAR') + + when: + def result = op('import calendar in collection').execute(ctx, Params.of(collection: 'events', file: write(dir, 'two.ics', ics).toString())) + + then: + (result as Result.Identifiers).ids() as Set == ['tz@ict', 't@ict'] as Set + } + + def "'remove calendar in collection' removes one object by UID"() { + given: + op('import calendar in collection').execute(ctx, Params.of(collection: 'events', file: write(dir, 'a.ics', event('a@ict', 'First')).toString())) + + when: + def result = op('remove calendar in collection').execute(ctx, Params.of(collection: 'events', uid: 'a@ict')) + + then: + (result as Result.Status).message() == "Removed calendar 'a@ict'" + ctx.calendarStore().getCollection('events', 'work').listObjectUIDs() == [] + + when: + op('remove calendar in collection').execute(ctx, Params.of(collection: 'events', uid: 'a@ict')) + + then: + thrown(OperationException.NotFound) + + when: + op('remove calendar in collection').execute(ctx, Params.of(collection: 'events')) + + then: + thrown(OperationException.Usage) + } +} diff --git a/src/test/groovy/org/ical4j/command/ops/CardOperationsTest.groovy b/src/test/groovy/org/ical4j/command/ops/CardOperationsTest.groovy new file mode 100644 index 0000000..64ee16f --- /dev/null +++ b/src/test/groovy/org/ical4j/command/ops/CardOperationsTest.groovy @@ -0,0 +1,80 @@ +package org.ical4j.command.ops + +import spock.lang.Specification +import spock.lang.TempDir + +import java.nio.file.Path + +import static org.ical4j.command.ops.Fixtures.* + +class CardOperationsTest extends Specification { + + @TempDir + Path dir + + Context ctx + + def setup() { + ctx = context(dir) + op('add collection in workspace').execute(ctx, Params.of(collection: 'people', type: 'card')) + } + + def "'import card in collection' merges a file and reports the UIDs"() { + given: + def file = write(dir, 'a.vcf', card('a@ict', 'Ada Lovelace')) + + when: + def result = op('import card in collection').execute(ctx, Params.of(collection: 'people', file: file.toString())) + + then: + (result as Result.Identifiers).ids() == ['a@ict'] + ctx.cardStore().getCollection('people', 'work').listObjectUIDs() == ['a@ict'] + + when: + op('import card in collection').execute(ctx, Params.of(collection: 'people', file: write(dir, 'bad.vcf', 'nope').toString())) + + then: + thrown(OperationException.InvalidData) + } + + def "'export card in collection' returns one card by UID or the whole collection"() { + given: + op('import card in collection').execute(ctx, Params.of(collection: 'people', file: write(dir, 'a.vcf', card('a@ict', 'Ada Lovelace')).toString())) + + when: + def one = op('export card in collection').execute(ctx, Params.of(collection: 'people', uid: 'a@ict')) as Result.CardData + + then: + one.card().getUid().value == 'a@ict' + + when: + def all = op('export card in collection').execute(ctx, Params.of(collection: 'people')) as Result.CardData + + then: + all.card() != null + + when: + op('export card in collection').execute(ctx, Params.of(collection: 'people', uid: 'nope')) + + then: + thrown(OperationException.NotFound) + } + + def "'remove card in collection' removes one card by UID"() { + given: + op('import card in collection').execute(ctx, Params.of(collection: 'people', file: write(dir, 'a.vcf', card('a@ict', 'Ada Lovelace')).toString())) + + when: + def result = op('remove card in collection').execute(ctx, Params.of(collection: 'people', uid: 'a@ict')) + + then: + (result as Result.Status).message() == "Removed card 'a@ict'" + ctx.cardStore().getCollection('people', 'work').listObjectUIDs() == [] + + when: + op('remove card in collection').execute(ctx, Params.of(collection: 'people', uid: 'a@ict')) + + then: + thrown(OperationException.NotFound) + } +} diff --git a/src/test/groovy/org/ical4j/command/ops/CollectionOperationsTest.groovy b/src/test/groovy/org/ical4j/command/ops/CollectionOperationsTest.groovy new file mode 100644 index 0000000..fd9c85e --- /dev/null +++ b/src/test/groovy/org/ical4j/command/ops/CollectionOperationsTest.groovy @@ -0,0 +1,105 @@ +package org.ical4j.command.ops + +import spock.lang.Specification +import spock.lang.TempDir + +import java.nio.file.Path + +import static org.ical4j.command.ops.Fixtures.context +import static org.ical4j.command.ops.Fixtures.op + +class CollectionOperationsTest extends Specification { + + @TempDir + Path dir + + def "'add collection in workspace' creates a collection of the requested type once"() { + given: + def ctx = context(dir) + + when: + def result = op('add collection in workspace').execute(ctx, Params.of(collection: 'events')) + + then: + (result as Result.Status).message() == "Added calendar collection 'events'" + dir.resolve('calendars/work/events').toFile().directory + + when: + op('add collection in workspace').execute(ctx, Params.of(collection: 'people', type: 'card')) + + then: + dir.resolve('vcards/work/people').toFile().directory + + when: + op('add collection in workspace').execute(ctx, Params.of(collection: 'events')) + + then: + thrown(OperationException.AlreadyExists) + + when: + op('add collection in workspace').execute(ctx, Params.empty()) + + then: + thrown(OperationException.Usage) + } + + def "'get collection in workspace' describes a collection and reports missing ones"() { + given: + def ctx = context(dir) + op('add collection in workspace').execute(ctx, Params.of(collection: 'events')) + + when: + def result = op('get collection in workspace').execute(ctx, Params.of(collection: 'events')) as Result.Descriptor + + then: + result.attributes().name == 'events' + result.attributes().type == 'calendar' + result.attributes().objects == '0' + + when: + op('add collection in workspace').execute(ctx, Params.of(collection: 'notes', description: 'Scratch notes')) + + then: + (op('get collection in workspace').execute(ctx, Params.of(collection: 'notes')) as Result.Descriptor).attributes().description == 'Scratch notes' + + when: + op('get collection in workspace').execute(ctx, Params.of(collection: 'missing')) + + then: + thrown(OperationException.NotFound) + } + + def "'remove collection in workspace' deletes the collection directory"() { + given: + def ctx = context(dir) + op('add collection in workspace').execute(ctx, Params.of(collection: 'events')) + + when: + def result = op('remove collection in workspace').execute(ctx, Params.of(collection: 'events')) + + then: + (result as Result.Status).message() == "Removed calendar collection 'events'" + !dir.resolve('calendars/work/events').toFile().exists() + + when: + op('remove collection in workspace').execute(ctx, Params.of(collection: 'events')) + + then: + thrown(OperationException.NotFound) + } + + def "'list collection in workspace' lists calendar and card collections of the active workspace only"() { + given: + def ctx = context(dir) + op('add collection in workspace').execute(ctx, Params.of(collection: 'events')) + op('add collection in workspace').execute(ctx, Params.of(collection: 'people', type: 'card')) + op('add collection in workspace').execute(context(dir, 'other'), Params.of(collection: 'elsewhere')) + + when: + def result = op('list collection in workspace').execute(ctx, Params.empty()) as Result.Descriptors + + then: + result.items()*.attributes()*.name as Set == ['events', 'people'] as Set + result.items().find { it.attributes().name == 'people' }.attributes().type == 'card' + } +} diff --git a/src/test/groovy/org/ical4j/command/ops/Fixtures.groovy b/src/test/groovy/org/ical4j/command/ops/Fixtures.groovy new file mode 100644 index 0000000..20a46df --- /dev/null +++ b/src/test/groovy/org/ical4j/command/ops/Fixtures.groovy @@ -0,0 +1,64 @@ +package org.ical4j.command.ops + +import org.ical4j.connector.local.LocalCalendarStore +import org.ical4j.connector.local.LocalCardStore + +import java.nio.file.Path + +/** Shared fixtures for handler specs: local stores under a temp dir and sample data. */ +class Fixtures { + + static Context context(Path dir, String workspace = 'work') { + Context.builder().activeWorkspace(workspace) + .calendarStore(new LocalCalendarStore(dir.resolve('calendars').toFile())) + .cardStore(new LocalCardStore(dir.resolve('vcards').toFile())) + .build() + } + + static Operation op(String tuple) { + Operations.standard().require(OperationId.parse(tuple)) + } + + static String event(String uid, String summary, String start = '20260910T100000Z') { + """BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//ict test//EN +BEGIN:VEVENT +UID:$uid +DTSTAMP:20260905T000000Z +DTSTART:$start +SUMMARY:$summary +END:VEVENT +END:VCALENDAR +""" + } + + static String todo(String uid, String summary) { + """BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//ict test//EN +BEGIN:VTODO +UID:$uid +DTSTAMP:20260905T000000Z +SUMMARY:$summary +END:VTODO +END:VCALENDAR +""" + } + + static String card(String uid, String name) { + """BEGIN:VCARD +VERSION:4.0 +UID:$uid +FN:$name +N:${name.split(' ').reverse().join(';')};;; +END:VCARD +""" + } + + static Path write(Path dir, String name, String content) { + def f = dir.resolve(name) + f.toFile().text = content + f + } +} diff --git a/src/test/groovy/org/ical4j/command/ops/ListOperationsTest.groovy b/src/test/groovy/org/ical4j/command/ops/ListOperationsTest.groovy new file mode 100644 index 0000000..34032ad --- /dev/null +++ b/src/test/groovy/org/ical4j/command/ops/ListOperationsTest.groovy @@ -0,0 +1,65 @@ +package org.ical4j.command.ops + +import spock.lang.Specification +import spock.lang.TempDir + +import java.nio.file.Path + +import static org.ical4j.command.ops.Fixtures.* + +class ListOperationsTest extends Specification { + + @TempDir + Path dir + + Context ctx + + def setup() { + ctx = context(dir) + op('add collection in workspace').execute(ctx, Params.of(collection: 'work')) + op('add collection in workspace').execute(ctx, Params.of(collection: 'people', type: 'card')) + op('import calendar in collection').execute(ctx, Params.of(collection: 'work', file: write(dir, 'e1.ics', event('e1@ict', 'Standup', '20260910T090000Z')).toString())) + op('import calendar in collection').execute(ctx, Params.of(collection: 'work', file: write(dir, 'e2.ics', event('e2@ict', 'Review', '20260911T090000Z')).toString())) + op('import calendar in collection').execute(ctx, Params.of(collection: 'work', file: write(dir, 't1.ics', todo('t1@ict', 'Write spec')).toString())) + op('import card in collection').execute(ctx, Params.of(collection: 'people', file: write(dir, 'c1.vcf', card('c1@ict', 'Ada Lovelace')).toString())) + } + + def "'list event in collection' describes only the events"() { + when: + def result = op('list event in collection').execute(ctx, Params.of(collection: 'work')) as Result.Descriptors + + then: + result.items()*.attributes()*.uid as Set == ['e1@ict', 'e2@ict'] as Set + result.items().find { it.attributes().uid == 'e1@ict' }.attributes() == [uid: 'e1@ict', summary: 'Standup', start: '20260910T090000Z'] + } + + def "'list action in collection' describes only the to-dos"() { + when: + def result = op('list action in collection').execute(ctx, Params.of(collection: 'work')) as Result.Descriptors + + then: + result.items()*.attributes()*.uid == ['t1@ict'] + result.items()[0].attributes().summary == 'Write spec' + } + + def "'list note in collection' is empty when there are no journals"() { + expect: + (op('list note in collection').execute(ctx, Params.of(collection: 'work')) as Result.Descriptors).items().empty + } + + def "'list entity in collection' describes the cards"() { + when: + def result = op('list entity in collection').execute(ctx, Params.of(collection: 'people')) as Result.Descriptors + + then: + result.items()*.attributes() == [[uid: 'c1@ict', name: 'Ada Lovelace']] + } + + def 'listing an unknown collection is a not-found error'() { + when: + op('list event in collection').execute(ctx, Params.of(collection: 'nope')) + + then: + thrown(OperationException.NotFound) + } +} diff --git a/src/test/groovy/org/ical4j/command/ops/OperationTest.groovy b/src/test/groovy/org/ical4j/command/ops/OperationTest.groovy new file mode 100644 index 0000000..cd8e7ab --- /dev/null +++ b/src/test/groovy/org/ical4j/command/ops/OperationTest.groovy @@ -0,0 +1,163 @@ +package org.ical4j.command.ops + +import org.ical4j.command.vocab.EntityType +import org.ical4j.command.vocab.Locus +import org.ical4j.command.vocab.SerializationFamily +import org.ical4j.command.vocab.Verb +import spock.lang.Specification + +class OperationTest extends Specification { + + def 'identity renders verb-first and allows every kind of subject'() { + expect: + OperationId.of(verb, subject, locus).toString() == text + + where: + verb | subject | locus | text + Verb.LIST | EntityType.EVENT | Locus.COLLECTION | 'list event in collection' + Verb.ADD | Locus.COLLECTION | Locus.WORKSPACE | 'add collection in workspace' + Verb.IMPORT | SerializationFamily.CALENDAR | Locus.COLLECTION | 'import calendar in collection' + Verb.GENERATE | EntityType.EVENT | Locus.NONE | 'generate event' + Verb.SEND | SerializationFamily.CALENDAR | Locus.CHANNEL | 'send calendar in channel' + Verb.LIST | Locus.WORKSPACE | Locus.NONE | 'list workspace' + } + + def 'identities parse from their text form'() { + expect: + OperationId.parse(text) == OperationId.of(verb, subject, locus) + + where: + text | verb | subject | locus + 'list event in collection' | Verb.LIST | EntityType.EVENT | Locus.COLLECTION + 'add collection in workspace' | Verb.ADD | Locus.COLLECTION | Locus.WORKSPACE + 'import calendar in collection' | Verb.IMPORT | SerializationFamily.CALENDAR | Locus.COLLECTION + 'generate event' | Verb.GENERATE | EntityType.EVENT | Locus.NONE + ' list workspace ' | Verb.LIST | Locus.WORKSPACE | Locus.NONE + } + + def 'parsing rejects words outside the vocabulary'() { + when: + OperationId.parse(text) + + then: + thrown(IllegalArgumentException) + + where: + text << ['fetch event in collection', 'list widget in collection', 'list event in nowhere', + 'list event at collection', 'list', 'list none', 'list channel'] + } + + def 'a non-container locus cannot be a subject'() { + when: + OperationId.of(Verb.LIST, subject, Locus.NONE) + + then: + thrown(IllegalArgumentException) + + where: + subject << [Locus.NONE, Locus.CHANNEL] + } + + def 'parameter descriptors validate themselves'() { + when: + build() + + then: + thrown(IllegalArgumentException) + + where: + build << [ + { Param.string('Collection', 'x') }, + { Param.choice('type', 'x', []) }, + { Param.choice('type', 'x', ['a', 'b']).defaultTo('c') }, + { new Param('a', ParamType.STRING, true, 'd', 'x', false, []) }, + ] + } + + def 'enum choices derive from an enum class'() { + expect: + Param.choice('type', 'x', SerializationFamily).choices() == ['calendar', 'card'] + } + + def 'operations reject duplicate parameter names and blank descriptions'() { + when: + Operation.define(Verb.LIST, EntityType.EVENT, Locus.COLLECTION) + .description(description).params(*params) + .handler({ c, p -> new Result.Status('ok') }).build() + + then: + thrown(IllegalArgumentException) + + where: + description | params + '' | [] + 'ok' | [Param.string('a', 'x'), Param.string('a', 'y')] + } + + def 'execute resolves defaults and required parameters before the handler runs'() { + given: + def op = Operation.define(Verb.LIST, EntityType.EVENT, Locus.COLLECTION) + .description('List events') + .params(Param.string('collection', 'x').asRequired(), + Param.choice('format', 'x', ['text', 'json']).defaultTo('text'), + Param.bool('uids-only', 'x')) + .handler({ ctx, p -> new Result.Status("${p.require('collection')}/${p.string('format').get()}/${p.bool('uids-only')}") }) + .build() + def ctx = Context.builder().activeWorkspace('w').build() + + expect: + (op.execute(ctx, Params.of(collection: 'work')) as Result.Status).message() == 'work/text/false' + (op.execute(ctx, Params.of(collection: 'work', format: 'json', 'uids-only': 'true')) as Result.Status).message() == 'work/json/true' + + when: + op.execute(ctx, Params.empty()) + + then: + thrown(OperationException.Usage) + + when: + op.execute(ctx, Params.of(collection: 'work', format: 'xml')) + + then: + thrown(OperationException.Usage) + } + + def 'exposure defaults to every surface and can be restricted'() { + given: + def all = Operation.define(Verb.LIST, EntityType.EVENT, Locus.COLLECTION).description('x') + .handler({ c, p -> new Result.Status('ok') }).build() + def cli = Operation.define(Verb.REMOVE, EntityType.EVENT, Locus.COLLECTION).description('x') + .only(Surface.CLI).handler({ c, p -> new Result.Status('ok') }).build() + + expect: + all.exposedTo(Surface.CLI) && all.exposedTo(Surface.MCP) + cli.exposedTo(Surface.CLI) && !cli.exposedTo(Surface.MCP) + } + + def 'typed access converts strings and lists'() { + given: + def p = Params.of(n: '42', bad: 'x', many: ['a', 'b'], one: 'c') + + expect: + p.integer('n').get() == 42 + p.strings('many') == ['a', 'b'] + p.strings('one') == ['c'] + p.string('many').get() == 'a' + !p.has('missing') + p.string('missing', 'dflt') == 'dflt' + + when: + p.integer('bad') + + then: + thrown(OperationException.Usage) + } + + def 'context refuses stores that were not configured'() { + when: + Context.builder().build().calendarStore() + + then: + thrown(OperationException) + } +} diff --git a/src/test/groovy/org/ical4j/command/ops/RegistryConformanceTest.groovy b/src/test/groovy/org/ical4j/command/ops/RegistryConformanceTest.groovy new file mode 100644 index 0000000..5713b69 --- /dev/null +++ b/src/test/groovy/org/ical4j/command/ops/RegistryConformanceTest.groovy @@ -0,0 +1,67 @@ +package org.ical4j.command.ops + +import org.ical4j.command.vocab.EntityType +import org.ical4j.command.vocab.Locus +import org.ical4j.command.vocab.Verb +import spock.lang.Specification +import spock.lang.TempDir + +import java.nio.file.Files +import java.nio.file.Path + +/** + * The admission bar (design D8): an operation may sit in the standard registry only if a + * Spock specification names its tuple, as the literal text of {@link OperationId#toString()}, + * for example {@code 'add collection in workspace'}. Specs get the operation with + * {@code Operations.standard().require(OperationId.parse('add collection in workspace'))}, so + * the literal is the natural way to refer to it. + */ +class RegistryConformanceTest extends Specification { + + static final Path TEST_SOURCES = Path.of('src/test/groovy') + + def 'every operation in the standard registry is named by a specification'() { + given: + def registry = Operations.standard() + + expect: + missing(registry, TEST_SOURCES, getClass().simpleName) == [] + } + + def 'every operation in the standard registry is exposed to at least one surface'() { + expect: + Operations.standard().all().findAll { it.exposure().empty }*.id()*.toString() == [] + } + + def 'the scanner reports unreferenced tuples and accepts referenced ones'(@TempDir Path sources) { + given: + def registry = Registry.builder() + .add(op(Verb.LIST, EntityType.EVENT, Locus.COLLECTION)) + .add(op(Verb.ADD, Locus.COLLECTION, Locus.WORKSPACE)) + .build() + def spec = sources.resolve('org/x/ListEventsTest.groovy') + Files.createDirectories(spec.parent) + Files.writeString(spec, "def op = Operations.standard().require(OperationId.parse('list event in collection'))") + def self = sources.resolve('org/x/RegistryConformanceTest.groovy') + Files.writeString(self, "'add collection in workspace' // the conformance test itself does not count") + + expect: + missing(registry, sources, 'RegistryConformanceTest') == ['add collection in workspace'] + } + + /** Tuples in the registry that no spec under {@code sources} (other than the excluded one) mentions. */ + static List missing(Registry registry, Path sources, String excludedSimpleName) { + def texts = [] + if (Files.isDirectory(sources)) { + Files.walk(sources).withCloseable { stream -> + stream.filter { it.toString().endsWith('.groovy') && it.fileName.toString() != "${excludedSimpleName}.groovy" } + .forEach { texts << Files.readString(it) } + } + } + registry.all()*.id()*.toString().findAll { tuple -> !texts.any { it.contains("'$tuple'") || it.contains("\"$tuple\"") } } + } + + private static Operation op(Verb verb, def subject, Locus locus) { + Operation.define(verb, subject, locus).description('x').handler({ c, p -> new Result.Status('ok') }).build() + } +} diff --git a/src/test/groovy/org/ical4j/command/ops/RegistryTest.groovy b/src/test/groovy/org/ical4j/command/ops/RegistryTest.groovy new file mode 100644 index 0000000..e90ec29 --- /dev/null +++ b/src/test/groovy/org/ical4j/command/ops/RegistryTest.groovy @@ -0,0 +1,68 @@ +package org.ical4j.command.ops + +import org.ical4j.command.vocab.EntityType +import org.ical4j.command.vocab.Locus +import org.ical4j.command.vocab.Verb +import spock.lang.Specification + +class RegistryTest extends Specification { + + static Operation op(Verb verb, EntityType type, Locus locus, Surface... only) { + def b = Operation.define(verb, type, locus).description("$verb $type") + .handler({ c, p -> new Result.Status("$verb $type") }) + if (only) b.only(only) + b.build() + } + + def 'registering the same tuple twice fails naming the tuple'() { + given: + def builder = Registry.builder().add(op(Verb.LIST, EntityType.EVENT, Locus.COLLECTION)) + + when: + builder.add(op(Verb.LIST, EntityType.EVENT, Locus.COLLECTION)) + + then: + def e = thrown(IllegalStateException) + e.message.contains('list event in collection') + } + + def 'lookups honour registration order and surface exposure'() { + given: + def registry = Registry.builder() + .add(op(Verb.REMOVE, EntityType.EVENT, Locus.COLLECTION, Surface.CLI)) + .add(op(Verb.LIST, EntityType.EVENT, Locus.COLLECTION)) + .add(op(Verb.LIST, EntityType.NOTE, Locus.COLLECTION)) + .build() + + expect: + registry.size() == 3 + registry.all()*.id()*.toString() == ['remove event in collection', 'list event in collection', 'list note in collection'] + registry.forSurface(Surface.MCP)*.id()*.toString() == ['list event in collection', 'list note in collection'] + registry.byVerb(Surface.CLI).keySet()*.name() == ['LIST', 'REMOVE'] + registry.byVerb(Surface.CLI)[Verb.LIST]*.id()*.subjectKey() == ['event', 'note'] + registry.byVerb(Surface.MCP).keySet()*.name() == ['LIST'] + registry.find(OperationId.of(Verb.LIST, EntityType.EVENT, Locus.COLLECTION)).present + !registry.find(OperationId.of(Verb.GET, EntityType.EVENT, Locus.COLLECTION)).present + } + + def 'execute by identity resolves parameters and reports unknown tuples'() { + given: + def registry = Registry.builder().add(op(Verb.LIST, EntityType.EVENT, Locus.COLLECTION)).build() + def ctx = Context.builder().build() + + expect: + (registry.execute(OperationId.of(Verb.LIST, EntityType.EVENT, Locus.COLLECTION), ctx, Params.empty()) as Result.Status).message() == 'LIST EVENT' + + when: + registry.execute(OperationId.of(Verb.GET, EntityType.EVENT, Locus.COLLECTION), ctx, Params.empty()) + + then: + thrown(OperationException.NotFound) + } + + def 'an empty registry has nothing for any surface'() { + expect: + Registry.empty().forSurface(Surface.CLI).empty + Registry.empty().byVerb(Surface.MCP).isEmpty() + } +} diff --git a/src/test/groovy/org/ical4j/command/ops/RendererTest.groovy b/src/test/groovy/org/ical4j/command/ops/RendererTest.groovy new file mode 100644 index 0000000..1dd7242 --- /dev/null +++ b/src/test/groovy/org/ical4j/command/ops/RendererTest.groovy @@ -0,0 +1,109 @@ +package org.ical4j.command.ops + +import com.fasterxml.jackson.databind.ObjectMapper +import net.fortuna.ical4j.data.CalendarBuilder +import net.fortuna.ical4j.vcard.VCardBuilder +import spock.lang.Specification + +import static org.ical4j.command.ops.Fixtures.card +import static org.ical4j.command.ops.Fixtures.event + +class RendererTest extends Specification { + + def renderer = new Renderer() + + static Object parse(String json) { new ObjectMapper().readValue(json, Object) } + + def 'status, identifiers and descriptors render as text lines and JSON values'() { + expect: + renderer.render(result, Format.TEXT) == text + parse(renderer.render(result, Format.JSON)) == json + + where: + result | text | json + new Result.Status('Done') | 'Done\n' | [status: 'Done'] + new Result.Identifiers(['a', 'b']) | 'a\nb\n' | ['a', 'b'] + new Result.Identifiers([]) | '' | [] + new Result.Descriptor([name: 'events', type: 'calendar']) | 'name: events\ntype: calendar\n' | [name: 'events', type: 'calendar'] + new Result.Descriptors([]) | '' | [] + } + + def 'descriptor lists render as an aligned table over the union of columns'() { + given: + def result = new Result.Descriptors([ + new Result.Descriptor([uid: 'e1', summary: 'Standup', start: '20260910T090000Z']), + new Result.Descriptor([uid: 'e22', summary: 'A much longer summary']), + ]) + + expect: + renderer.render(result, Format.TEXT) == '''\ +uid summary start +e1 Standup 20260910T090000Z +e22 A much longer summary +''' + parse(renderer.render(result, Format.JSON)) == [ + [uid: 'e1', summary: 'Standup', start: '20260910T090000Z'], + [uid: 'e22', summary: 'A much longer summary']] + } + + def 'calendar data renders as iCalendar, jCal and xCal'() { + given: + def result = new Result.CalendarData(new CalendarBuilder().build(new StringReader(event('a@ict', 'First')))) + + when: + def text = renderer.render(result, Format.TEXT) + def json = parse(renderer.render(result, Format.JSON)) + def xml = renderer.render(result, Format.XML) + + then: + text.startsWith('BEGIN:VCALENDAR') + text.contains('UID:a@ict') + json[0] == 'vcalendar' + json[2][0][0] == 'vevent' + xml.startsWith('') + xml.contains('a@ict') + } + + def 'card data renders as vCard, jCard and xCard'() { + given: + def result = new Result.CardData(new VCardBuilder(new StringReader(card('c1@ict', 'Ada Lovelace'))).build()) + + when: + def text = renderer.render(result, Format.TEXT) + def json = parse(renderer.render(result, Format.JSON)) + def xml = renderer.render(result, Format.XML) + + then: + text.startsWith('BEGIN:VCARD') + text.contains('FN:Ada Lovelace') + json[0] == 'vcard' + json[1].find { it[0] == 'fn' }[3] == 'Ada Lovelace' + xml.contains('vcard-4.0') + xml.contains('Ada Lovelace') + } + + def 'validation renders the report format or a clean bill'() { + given: + def clean = new Result.Validation([]) + def dirty = new Result.Validation([new Result.ValidationEntry('WARNING', 'context', 'message')]) + + expect: + renderer.render(clean, Format.TEXT) == 'No errors.\n' + renderer.render(dirty, Format.TEXT) == '- WARNING: context - message\n' + parse(renderer.render(clean, Format.JSON)) == [valid: true, entries: []] + parse(renderer.render(dirty, Format.JSON)) == [valid: false, entries: [[severity: 'WARNING', context: 'context', message: 'message']]] + } + + def 'XML is refused for results that have no XML form'() { + when: + renderer.render(new Result.Status('x'), Format.XML) + + then: + thrown(OperationException.Usage) + } + + def 'pretty printing indents JSON'() { + expect: + new Renderer(true).render(new Result.Descriptor([a: '1']), Format.JSON).contains('\n "a"') + } +} diff --git a/src/test/groovy/org/ical4j/command/smoke/SmokeSuiteTest.groovy b/src/test/groovy/org/ical4j/command/smoke/SmokeSuiteTest.groovy new file mode 100644 index 0000000..cb830c1 --- /dev/null +++ b/src/test/groovy/org/ical4j/command/smoke/SmokeSuiteTest.groovy @@ -0,0 +1,27 @@ +package org.ical4j.command.smoke + +import org.ical4j.command.ops.Operations +import spock.lang.Specification + +import java.nio.file.Path + +/** + * The native smoke suite must invoke every registered operation (design D8). The suite enforces + * this itself when it runs; checking here as well makes `./gradlew test` fail first, without a + * native toolchain. + */ +class SmokeSuiteTest extends Specification { + + def 'every operation in the standard registry has a smoke step'() { + expect: + SmokeSuite.missing() == [] as Set + } + + def 'every step that claims an operation names a real one'() { + given: + def registered = Operations.standard().all()*.id()*.toString() as Set + + expect: + SmokeSuite.steps(Path.of('fixtures'))*.covers().findAll { it != null && !registered.contains(it) } == [] + } +}