From aef1df595fd313962d469c6915cb8ddb5585cd33 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Tue, 12 May 2026 17:10:46 -0500 Subject: [PATCH] chore: first commit --- .github/workflows/ci.yml | 171 +++++++++++++ .github/workflows/homebrew-bump.yml | 69 ++++++ .github/workflows/release.yml | 231 ++++++++++++++++++ .gitignore | 14 ++ CHANGELOG.md | 45 ++++ Dockerfile | 21 ++ LICENSE | 21 ++ README.md | 147 +++++++++++ homebrew/floci.rb.template | 47 ++++ installer/install.ps1 | 56 +++++ installer/install.sh | 77 ++++++ pom.xml | 161 ++++++++++++ scoop/floci.json.template | 24 ++ src/main/java/io/floci/cli/FlociCli.java | 72 ++++++ src/main/java/io/floci/cli/GlobalOptions.java | 52 ++++ .../floci/cli/commands/CompletionCommand.java | 43 ++++ .../io/floci/cli/commands/DoctorCommand.java | 106 ++++++++ .../io/floci/cli/commands/LogsCommand.java | 61 +++++ .../io/floci/cli/commands/RestartCommand.java | 41 ++++ .../floci/cli/commands/ServicesCommand.java | 58 +++++ .../io/floci/cli/commands/StartCommand.java | 114 +++++++++ .../io/floci/cli/commands/StatusCommand.java | 98 ++++++++ .../io/floci/cli/commands/StopCommand.java | 73 ++++++ .../io/floci/cli/commands/VersionCommand.java | 71 ++++++ .../io/floci/cli/commands/WaitCommand.java | 79 ++++++ .../cli/commands/config/ConfigCommand.java | 23 ++ .../commands/config/ConfigProfileCommand.java | 118 +++++++++ .../commands/config/ConfigShowCommand.java | 70 ++++++ .../config/ConfigValidateCommand.java | 94 +++++++ .../commands/snapshot/SnapshotCommand.java | 26 ++ .../snapshot/SnapshotDeleteCommand.java | 38 +++ .../snapshot/SnapshotExportCommand.java | 33 +++ .../snapshot/SnapshotImportCommand.java | 33 +++ .../snapshot/SnapshotListCommand.java | 50 ++++ .../snapshot/SnapshotLoadCommand.java | 43 ++++ .../snapshot/SnapshotSaveCommand.java | 46 ++++ .../java/io/floci/cli/config/Profile.java | 23 ++ .../io/floci/cli/config/ProfileStore.java | 61 +++++ .../io/floci/cli/docker/DockerClient.java | 181 ++++++++++++++ .../io/floci/cli/docker/DockerException.java | 7 + src/main/java/io/floci/cli/doctor/Check.java | 6 + .../java/io/floci/cli/doctor/CheckResult.java | 20 ++ .../java/io/floci/cli/doctor/CheckStatus.java | 5 + .../doctor/checks/AwsCliEndpointCheck.java | 31 +++ .../doctor/checks/AwsCliS3PathStyleCheck.java | 33 +++ .../doctor/checks/ContainerRunningCheck.java | 30 +++ .../cli/doctor/checks/DockerDaemonCheck.java | 21 ++ .../doctor/checks/DockerInstalledCheck.java | 23 ++ .../cli/doctor/checks/DockerSocketCheck.java | 27 ++ .../cli/doctor/checks/DockerVersionCheck.java | 38 +++ .../doctor/checks/EndpointReachableCheck.java | 25 ++ .../cli/doctor/checks/ImagePresentCheck.java | 26 ++ .../cli/doctor/checks/ImageVersionCheck.java | 76 ++++++ .../cli/doctor/checks/PortAvailableCheck.java | 50 ++++ .../cli/doctor/checks/SdkGoEndpointCheck.java | 30 +++ .../cli/doctor/checks/SdkRustS3XmlCheck.java | 30 +++ .../io/floci/cli/http/FlociException.java | 7 + .../io/floci/cli/http/FlociHttpClient.java | 160 ++++++++++++ src/main/java/io/floci/cli/output/Ansi.java | 36 +++ .../io/floci/cli/output/OutputFormat.java | 5 + .../java/io/floci/cli/output/Printer.java | 62 +++++ .../floci-cli/native-image.properties | 4 + .../io.floci/floci-cli/reflect-config.json | 16 ++ .../io.floci/floci-cli/resource-config.json | 9 + .../cli/unit/DockerVersionCheckTest.java | 29 +++ .../floci/cli/unit/FlociCliParsingTest.java | 34 +++ .../floci/cli/unit/ImageVersionCheckTest.java | 22 ++ .../cli/unit/PortAvailableCheckTest.java | 16 ++ .../floci/cli/unit/WaitCommandParseTest.java | 28 +++ 69 files changed, 3697 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/homebrew-bump.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 homebrew/floci.rb.template create mode 100644 installer/install.ps1 create mode 100644 installer/install.sh create mode 100644 pom.xml create mode 100644 scoop/floci.json.template create mode 100644 src/main/java/io/floci/cli/FlociCli.java create mode 100644 src/main/java/io/floci/cli/GlobalOptions.java create mode 100644 src/main/java/io/floci/cli/commands/CompletionCommand.java create mode 100644 src/main/java/io/floci/cli/commands/DoctorCommand.java create mode 100644 src/main/java/io/floci/cli/commands/LogsCommand.java create mode 100644 src/main/java/io/floci/cli/commands/RestartCommand.java create mode 100644 src/main/java/io/floci/cli/commands/ServicesCommand.java create mode 100644 src/main/java/io/floci/cli/commands/StartCommand.java create mode 100644 src/main/java/io/floci/cli/commands/StatusCommand.java create mode 100644 src/main/java/io/floci/cli/commands/StopCommand.java create mode 100644 src/main/java/io/floci/cli/commands/VersionCommand.java create mode 100644 src/main/java/io/floci/cli/commands/WaitCommand.java create mode 100644 src/main/java/io/floci/cli/commands/config/ConfigCommand.java create mode 100644 src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java create mode 100644 src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java create mode 100644 src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java create mode 100644 src/main/java/io/floci/cli/commands/snapshot/SnapshotCommand.java create mode 100644 src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java create mode 100644 src/main/java/io/floci/cli/commands/snapshot/SnapshotExportCommand.java create mode 100644 src/main/java/io/floci/cli/commands/snapshot/SnapshotImportCommand.java create mode 100644 src/main/java/io/floci/cli/commands/snapshot/SnapshotListCommand.java create mode 100644 src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java create mode 100644 src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java create mode 100644 src/main/java/io/floci/cli/config/Profile.java create mode 100644 src/main/java/io/floci/cli/config/ProfileStore.java create mode 100644 src/main/java/io/floci/cli/docker/DockerClient.java create mode 100644 src/main/java/io/floci/cli/docker/DockerException.java create mode 100644 src/main/java/io/floci/cli/doctor/Check.java create mode 100644 src/main/java/io/floci/cli/doctor/CheckResult.java create mode 100644 src/main/java/io/floci/cli/doctor/CheckStatus.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/AwsCliEndpointCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/AwsCliS3PathStyleCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/DockerDaemonCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/DockerInstalledCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/DockerVersionCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/SdkGoEndpointCheck.java create mode 100644 src/main/java/io/floci/cli/doctor/checks/SdkRustS3XmlCheck.java create mode 100644 src/main/java/io/floci/cli/http/FlociException.java create mode 100644 src/main/java/io/floci/cli/http/FlociHttpClient.java create mode 100644 src/main/java/io/floci/cli/output/Ansi.java create mode 100644 src/main/java/io/floci/cli/output/OutputFormat.java create mode 100644 src/main/java/io/floci/cli/output/Printer.java create mode 100644 src/main/resources/META-INF/native-image/io.floci/floci-cli/native-image.properties create mode 100644 src/main/resources/META-INF/native-image/io.floci/floci-cli/reflect-config.json create mode 100644 src/main/resources/META-INF/native-image/io.floci/floci-cli/resource-config.json create mode 100644 src/test/java/io/floci/cli/unit/DockerVersionCheckTest.java create mode 100644 src/test/java/io/floci/cli/unit/FlociCliParsingTest.java create mode 100644 src/test/java/io/floci/cli/unit/ImageVersionCheckTest.java create mode 100644 src/test/java/io/floci/cli/unit/PortAvailableCheckTest.java create mode 100644 src/test/java/io/floci/cli/unit/WaitCommandParseTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..65146c3 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,171 @@ +name: CI + +on: + push: + branches: [main] + paths: + - 'src/**' + - 'pom.xml' + - '.github/workflows/ci.yml' + pull_request: + paths: + - 'src/**' + - 'pom.xml' + - '.github/workflows/ci.yml' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: Build and Test (JVM) + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + java-version: '25' + distribution: 'temurin' + cache: maven + + - name: Run unit tests + run: mvn test -B + + native-linux-amd64: + name: Native image — linux/amd64 + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '24' + distribution: 'graalvm-community' + cache: maven + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Build native binary + run: mvn clean package -Pnative -DskipTests -B + + - name: Smoke test — version + run: ./target/floci version + + - name: Smoke test — doctor + run: ./target/floci doctor || true # non-zero is ok in CI (docker may not be running) + + - uses: actions/upload-artifact@v4 + with: + name: floci-linux-amd64 + path: target/floci + retention-days: 7 + + native-linux-arm64: + name: Native image — linux/arm64 + runs-on: ubuntu-24.04-arm + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '24' + distribution: 'graalvm-community' + cache: maven + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Build native binary + run: mvn clean package -Pnative -DskipTests -B + + - name: Smoke test — version + run: ./target/floci version + + - uses: actions/upload-artifact@v4 + with: + name: floci-linux-arm64 + path: target/floci + retention-days: 7 + + native-macos-amd64: + name: Native image — macos/amd64 + runs-on: macos-13 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '24' + distribution: 'graalvm-community' + cache: maven + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Build native binary + run: mvn clean package -Pnative -DskipTests -B + + - name: Smoke test — version + run: ./target/floci version + + - uses: actions/upload-artifact@v4 + with: + name: floci-darwin-amd64 + path: target/floci + retention-days: 7 + + native-macos-arm64: + name: Native image — macos/arm64 + runs-on: macos-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '24' + distribution: 'graalvm-community' + cache: maven + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Build native binary + run: mvn clean package -Pnative -DskipTests -B + + - name: Smoke test — version + run: ./target/floci version + + - uses: actions/upload-artifact@v4 + with: + name: floci-darwin-arm64 + path: target/floci + retention-days: 7 + + native-windows-amd64: + name: Native image — windows/amd64 + runs-on: windows-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '24' + distribution: 'graalvm-community' + cache: maven + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Build native binary + run: mvn clean package -Pnative -DskipTests -B + + - name: Smoke test — version + run: target\floci.exe version + + - uses: actions/upload-artifact@v4 + with: + name: floci-windows-amd64 + path: target/floci.exe + retention-days: 7 diff --git a/.github/workflows/homebrew-bump.yml b/.github/workflows/homebrew-bump.yml new file mode 100644 index 0000000..58ca750 --- /dev/null +++ b/.github/workflows/homebrew-bump.yml @@ -0,0 +1,69 @@ +name: Homebrew Bump + +# Triggered after release.yml succeeds on a version tag. +# Opens a PR in floci-io/homebrew-floci with the new version and SHA256. +# +# Required secrets: HOMEBREW_BUMP_TOKEN (PAT with repo scope on homebrew-floci repo) + +on: + workflow_run: + workflows: [Release] + types: [completed] + +permissions: + contents: read + +jobs: + bump: + name: Bump Homebrew formula + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'success' }} + timeout-minutes: 10 + steps: + - name: Extract version from tag + id: version + run: | + TAG="${{ github.event.workflow_run.head_branch }}" + echo "version=${TAG}" >> "$GITHUB_OUTPUT" + + - name: Download release checksums + run: | + VERSION="${{ steps.version.outputs.version }}" + curl -fsSL "https://github.com/floci-io/floci-cli/releases/download/${VERSION}/sha256sums.txt" \ + -o sha256sums.txt + cat sha256sums.txt + + - name: Extract per-platform SHA256 + id: sha + run: | + echo "darwin_amd64=$(grep 'floci-darwin-amd64' sha256sums.txt | awk '{print $1}')" >> "$GITHUB_OUTPUT" + echo "darwin_arm64=$(grep 'floci-darwin-arm64' sha256sums.txt | awk '{print $1}')" >> "$GITHUB_OUTPUT" + echo "linux_amd64=$(grep 'floci-linux-amd64' sha256sums.txt | awk '{print $1}')" >> "$GITHUB_OUTPUT" + echo "linux_arm64=$(grep 'floci-linux-arm64' sha256sums.txt | awk '{print $1}')" >> "$GITHUB_OUTPUT" + + - name: Checkout homebrew tap + uses: actions/checkout@v4 + with: + repository: floci-io/homebrew-floci + token: ${{ secrets.HOMEBREW_BUMP_TOKEN }} + path: homebrew-floci + + - name: Update formula + run: | + VERSION="${{ steps.version.outputs.version }}" + FORMULA="homebrew-floci/Formula/floci.rb" + sed -i "s/version \".*\"/version \"${VERSION}\"/" "$FORMULA" + sed -i "/darwin-amd64/ { n; s/sha256 \".*\"/sha256 \"${{ steps.sha.outputs.darwin_amd64 }}\"/ }" "$FORMULA" + sed -i "/darwin-arm64/ { n; s/sha256 \".*\"/sha256 \"${{ steps.sha.outputs.darwin_arm64 }}\"/ }" "$FORMULA" + sed -i "/linux-amd64/ { n; s/sha256 \".*\"/sha256 \"${{ steps.sha.outputs.linux_amd64 }}\"/ }" "$FORMULA" + sed -i "/linux-arm64/ { n; s/sha256 \".*\"/sha256 \"${{ steps.sha.outputs.linux_arm64 }}\"/ }" "$FORMULA" + + - name: Open PR + uses: peter-evans/create-pull-request@v7 + with: + token: ${{ secrets.HOMEBREW_BUMP_TOKEN }} + path: homebrew-floci + commit-message: "floci ${{ steps.version.outputs.version }}" + title: "floci ${{ steps.version.outputs.version }}" + body: "Automated bump from floci-cli release workflow." + branch: "bump-${{ steps.version.outputs.version }}" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..445a7ca --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,231 @@ +name: Release + +# Triggered when a SemVer tag (e.g. 0.1.0) is pushed. +# Builds native binaries for all 5 platform targets, creates a GitHub Release, +# and pushes Docker image floci/cli:. +# +# Required secrets: DOCKERHUB_USERNAME, DOCKERHUB_TOKEN + +on: + push: + tags: + - '[0-9]+.[0-9]+.[0-9]+' + +permissions: + contents: write + packages: write + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-linux-amd64: + name: Build — linux/amd64 + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '24' + distribution: 'graalvm-community' + cache: maven + github-token: ${{ secrets.GITHUB_TOKEN }} + - run: mvn clean package -Pnative -DskipTests -B + - run: mv target/floci target/floci-linux-amd64 + - uses: actions/upload-artifact@v4 + with: + name: floci-linux-amd64 + path: target/floci-linux-amd64 + + build-linux-arm64: + name: Build — linux/arm64 + runs-on: ubuntu-24.04-arm + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '24' + distribution: 'graalvm-community' + cache: maven + github-token: ${{ secrets.GITHUB_TOKEN }} + - run: mvn clean package -Pnative -DskipTests -B + - run: mv target/floci target/floci-linux-arm64 + - uses: actions/upload-artifact@v4 + with: + name: floci-linux-arm64 + path: target/floci-linux-arm64 + + build-darwin-amd64: + name: Build — darwin/amd64 + runs-on: macos-13 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '24' + distribution: 'graalvm-community' + cache: maven + github-token: ${{ secrets.GITHUB_TOKEN }} + - run: mvn clean package -Pnative -DskipTests -B + - run: mv target/floci target/floci-darwin-amd64 + - uses: actions/upload-artifact@v4 + with: + name: floci-darwin-amd64 + path: target/floci-darwin-amd64 + + build-darwin-arm64: + name: Build — darwin/arm64 + runs-on: macos-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '24' + distribution: 'graalvm-community' + cache: maven + github-token: ${{ secrets.GITHUB_TOKEN }} + - run: mvn clean package -Pnative -DskipTests -B + - run: mv target/floci target/floci-darwin-arm64 + - uses: actions/upload-artifact@v4 + with: + name: floci-darwin-arm64 + path: target/floci-darwin-arm64 + + build-windows-amd64: + name: Build — windows/amd64 + runs-on: windows-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + - uses: graalvm/setup-graalvm@v1 + with: + java-version: '24' + distribution: 'graalvm-community' + cache: maven + github-token: ${{ secrets.GITHUB_TOKEN }} + - run: mvn clean package -Pnative -DskipTests -B + - run: mv target/floci.exe target/floci-windows-amd64.exe + - uses: actions/upload-artifact@v4 + with: + name: floci-windows-amd64 + path: target/floci-windows-amd64.exe + + build-jar: + name: Build — JVM jar + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + java-version: '25' + distribution: 'temurin' + cache: maven + - run: mvn clean package -DskipTests -B + - uses: actions/upload-artifact@v4 + with: + name: floci-jar + path: target/floci.jar + + release: + name: Create GitHub Release + needs: [build-linux-amd64, build-linux-arm64, build-darwin-amd64, build-darwin-arm64, build-windows-amd64, build-jar] + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + + - name: Extract version + id: version + run: echo "version=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT" + + - uses: actions/download-artifact@v4 + with: + path: dist/ + + - name: Generate checksums + run: | + cd dist + find . -type f \( -name "floci-*" \) | sort | xargs sha256sum > sha256sums.txt + cat sha256sums.txt + + - name: Create Release + uses: softprops/action-gh-release@v2 + with: + name: "floci ${{ steps.version.outputs.version }}" + body: | + ## Installation + + **Homebrew:** + ```sh + brew install floci-io/floci/floci + ``` + + **Direct download (Linux/macOS):** + ```sh + curl -fsSL https://floci.io/install.sh | sh + ``` + + **Windows:** + ```powershell + iwr https://floci.io/install.ps1 | iex + ``` + + **JVM fallback** (requires Java 21+): `floci.jar` + + See [CHANGELOG.md](CHANGELOG.md) for what's new. + files: | + dist/floci-linux-amd64/floci-linux-amd64 + dist/floci-linux-arm64/floci-linux-arm64 + dist/floci-darwin-amd64/floci-darwin-amd64 + dist/floci-darwin-arm64/floci-darwin-arm64 + dist/floci-windows-amd64/floci-windows-amd64.exe + dist/floci-jar/floci.jar + dist/sha256sums.txt + + docker: + name: Push Docker image + needs: [build-linux-amd64, build-linux-arm64] + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + + - name: Extract version + id: version + run: echo "version=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT" + + - uses: actions/download-artifact@v4 + with: + name: floci-linux-amd64 + path: docker/amd64/ + + - uses: actions/download-artifact@v4 + with: + name: floci-linux-arm64 + path: docker/arm64/ + + - run: chmod +x docker/amd64/floci-linux-amd64 docker/arm64/floci-linux-arm64 + + - uses: docker/setup-buildx-action@v3 + + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: | + floci/cli:${{ steps.version.outputs.version }} + floci/cli:latest + build-args: VERSION=${{ steps.version.outputs.version }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d3950dc --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +target/ +*.class +*.jar +*.iml +.idea/ +.vscode/ +.zed/ +.DS_Store +.claude/ +CLAUDE.md +*.log + + +*local* \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..8d7430d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,45 @@ +# Changelog + +All notable changes to `floci-cli` will be documented in this file. + +The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +This project uses [Semantic Versioning](https://semver.org/). + +## [Unreleased] + +## [0.1.0] — 2024-xx-xx + +### Added + +- `floci start` — launches the Floci container with configurable port, persist directory, services, and image pull policy +- `floci stop` — stops and optionally removes the container +- `floci restart` — stop + start in sequence +- `floci status` — shows container state, endpoint reachability, and server version +- `floci logs` — streams container logs with `--follow`, `--tail`, `--since` options +- `floci wait` — polls `/_floci/health` until ready, with configurable timeout +- `floci version` — prints CLI version, server version, and image digest +- `floci services` — lists enabled services from the running instance +- `floci doctor` — runs 13 environment checks: Docker installation, daemon, socket, version, port availability, image presence and version, container state, endpoint reachability, AWS CLI endpoint configuration, S3 path-style config, Rust SDK XML warning, Go SDK endpoint warning +- `floci config show` — displays the active configuration and profile +- `floci config validate` — validates a docker-compose.yml for Floci compatibility +- `floci config profile list|show|create|delete` — manages profiles in `~/.floci/profiles/` +- `floci snapshot save|load|list|delete` — thin wrapper over `/_floci/snapshots/*` (stubs pending server implementation) +- `floci snapshot export|import` — stubs pending server implementation +- `floci completion bash|zsh` — generates shell completion scripts +- Global flags: `--endpoint`, `--container`, `--profile`, `--output text|json|yaml`, `--quiet`, `--verbose`, `--no-color` +- GraalVM native binary for linux/amd64, linux/arm64, darwin/amd64, darwin/arm64, windows/amd64 +- CI matrix across all 5 platforms with native smoke tests +- Homebrew formula template and automated bump workflow +- Scoop bucket template +- `curl | sh` installer for Linux and macOS +- PowerShell installer for Windows +- Docker image `floci/cli:` + +### Known Limitations + +- `floci snapshot export` and `floci snapshot import` are stubs — server-side endpoints not yet implemented +- `floci logs --service` filter is not yet supported (requires server-side log routing) +- Shell completion for `fish` and `powershell` is not yet generated by Picocli + +[Unreleased]: https://github.com/floci-io/floci-cli/compare/0.1.0...HEAD +[0.1.0]: https://github.com/floci-io/floci-cli/releases/tag/0.1.0 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a06beed --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +# floci/cli Docker image +# Usage: docker run --rm floci/cli:latest version +# +# The binary expects the Docker socket to be mounted if running lifecycle commands: +# docker run --rm -v /var/run/docker.sock:/var/run/docker.sock floci/cli status + +FROM scratch + +ARG VERSION=dev +LABEL org.opencontainers.image.title="Floci CLI" +LABEL org.opencontainers.image.description="Official CLI for the Floci local AWS emulator" +LABEL org.opencontainers.image.version="${VERSION}" +LABEL org.opencontainers.image.source="https://github.com/floci-io/floci-cli" +LABEL org.opencontainers.image.licenses="MIT" + +# Multi-arch: TARGETARCH is set by buildx (amd64 or arm64) +ARG TARGETARCH + +COPY docker/${TARGETARCH}/floci-linux-${TARGETARCH} /floci + +ENTRYPOINT ["/floci"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3acdf52 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Floci Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..87b23c7 --- /dev/null +++ b/README.md @@ -0,0 +1,147 @@ +# floci-cli + +Official command-line interface for [Floci](https://floci.io) — the free, open-source local AWS emulator. + +``` +floci start +floci doctor +export AWS_ENDPOINT_URL=http://localhost:4566 +aws s3 mb s3://my-bucket +``` + +## Installation + +### Homebrew (macOS / Linux) + +```sh +brew install floci-io/floci/floci +``` + +### Install script (Linux / macOS) + +```sh +curl -fsSL https://floci.io/install.sh | sh +``` + +### Windows (PowerShell) + +```powershell +iwr https://floci.io/install.ps1 | iex +``` + +### Scoop (Windows) + +```powershell +scoop bucket add floci https://github.com/floci-io/scoop-floci +scoop install floci +``` + +### Docker + +```sh +docker run --rm floci/cli:latest version +# With Docker socket for lifecycle commands: +docker run --rm -v /var/run/docker.sock:/var/run/docker.sock floci/cli status +``` + +### JVM fallback + +Download `floci.jar` from the [latest release](https://github.com/floci-io/floci-cli/releases/latest) and run: + +```sh +java -jar floci.jar version +``` + +--- + +## Quick Start + +```sh +# Start Floci +floci start + +# Check environment +floci doctor + +# Point the AWS CLI at Floci +export AWS_ENDPOINT_URL=http://localhost:4566 + +# Use AWS services normally +aws s3 mb s3://my-bucket +aws dynamodb create-table --table-name users \ + --attribute-definitions AttributeName=id,AttributeType=S \ + --key-schema AttributeName=id,KeyType=HASH \ + --billing-mode PAY_PER_REQUEST + +# Stop Floci +floci stop +``` + +--- + +## Command Reference + +| Command | Description | +|---------|-------------| +| `floci start` | Launch the Floci container | +| `floci stop` | Stop (and optionally remove) the container | +| `floci restart` | Stop then start | +| `floci status` | Show container state and server health | +| `floci logs` | Stream container logs | +| `floci wait` | Poll until Floci is ready (CI-friendly) | +| `floci version` | Show CLI and server versions | +| `floci services` | List enabled AWS services | +| `floci doctor` | Run environment diagnostics | +| `floci config show` | Show active configuration | +| `floci config validate` | Validate a docker-compose.yml | +| `floci config profile` | Manage named profiles | +| `floci snapshot save/load/list/delete` | Manage state snapshots | +| `floci completion bash\|zsh` | Generate shell completion | + +All commands support `--help`. Global flags: + +``` +--endpoint Floci server URL (default: http://localhost:4566, env: FLOCI_ENDPOINT) +--container Container name (default: floci, env: FLOCI_CONTAINER) +--output text|json|yaml Output format (default: text) +--quiet, -q Suppress non-error output +--verbose, -v Debug logging to stderr +--no-color Disable ANSI colors +``` + +--- + +## CI Usage + +```sh +floci start --detach +floci wait --timeout 60s +pytest # or your test command +floci stop --remove +``` + +With Docker Compose: + +```yaml +services: + floci: + image: floci/floci:latest + ports: + - "4566:4566" + volumes: + - /var/run/docker.sock:/var/run/docker.sock +``` + +--- + +## Scope + +`floci-cli` manages Floci's lifecycle, config, state, and diagnostics. +It does **not** wrap the AWS CLI or manage AWS resources. +Use `aws` with `AWS_ENDPOINT_URL=http://localhost:4566` for resource operations. + +--- + +## License + +MIT — see [LICENSE](LICENSE). diff --git a/homebrew/floci.rb.template b/homebrew/floci.rb.template new file mode 100644 index 0000000..e736df6 --- /dev/null +++ b/homebrew/floci.rb.template @@ -0,0 +1,47 @@ +class Floci < Formula + desc "Official CLI for the Floci local AWS emulator" + homepage "https://floci.io" + version "{{VERSION}}" + license "MIT" + + on_macos do + on_arm do + url "https://github.com/floci-io/floci-cli/releases/download/{{VERSION}}/floci-darwin-arm64" + sha256 "{{SHA256_DARWIN_ARM64}}" + end + on_intel do + url "https://github.com/floci-io/floci-cli/releases/download/{{VERSION}}/floci-darwin-amd64" + sha256 "{{SHA256_DARWIN_AMD64}}" + end + end + + on_linux do + on_arm do + url "https://github.com/floci-io/floci-cli/releases/download/{{VERSION}}/floci-linux-arm64" + sha256 "{{SHA256_LINUX_ARM64}}" + end + on_intel do + url "https://github.com/floci-io/floci-cli/releases/download/{{VERSION}}/floci-linux-amd64" + sha256 "{{SHA256_LINUX_AMD64}}" + end + end + + def install + bin.install Dir["floci*"].first => "floci" + end + + def caveats + <<~EOS + Set AWS_ENDPOINT_URL to point the AWS CLI at Floci: + export AWS_ENDPOINT_URL=http://localhost:4566 + + Quick start: + floci start + floci doctor + EOS + end + + test do + system "#{bin}/floci", "version" + end +end diff --git a/installer/install.ps1 b/installer/install.ps1 new file mode 100644 index 0000000..1917f14 --- /dev/null +++ b/installer/install.ps1 @@ -0,0 +1,56 @@ +# Floci CLI Windows installer +# Usage: iwr https://floci.io/install.ps1 | iex + +[CmdletBinding()] +param( + [string]$Version = "latest", + [string]$InstallDir = "$env:LOCALAPPDATA\floci\bin" +) + +$ErrorActionPreference = "Stop" +$Repo = "floci-io/floci-cli" + +function Get-LatestVersion { + $response = Invoke-RestMethod "https://api.github.com/repos/$Repo/releases/latest" + return $response.tag_name +} + +function Main { + Write-Host "Installing Floci CLI..." -ForegroundColor Cyan + + if ($Version -eq "latest") { + $Version = Get-LatestVersion + } + + $Arch = if ([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture -eq "Arm64") { "arm64" } else { "amd64" } + $Platform = "windows-$Arch" + $FileName = "floci-$Platform.exe" + $DownloadUrl = "https://github.com/$Repo/releases/download/$Version/$FileName" + + Write-Host "Downloading floci $Version for $Platform..." + + if (-not (Test-Path $InstallDir)) { + New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null + } + + $Destination = Join-Path $InstallDir "floci.exe" + Invoke-WebRequest -Uri $DownloadUrl -OutFile $Destination -UseBasicParsing + + # Add to PATH if not already there + $CurrentPath = [Environment]::GetEnvironmentVariable("Path", "User") + if ($CurrentPath -notlike "*$InstallDir*") { + [Environment]::SetEnvironmentVariable("Path", "$CurrentPath;$InstallDir", "User") + Write-Host "Added $InstallDir to user PATH (restart your terminal)" + } + + Write-Host "" + Write-Host "Floci CLI $Version installed to $Destination" -ForegroundColor Green + Write-Host "" + Write-Host "Quick start:" + Write-Host " floci start" + Write-Host " floci doctor" + Write-Host ' $env:AWS_ENDPOINT_URL="http://localhost:4566"' + Write-Host " aws s3 mb s3://my-bucket" +} + +Main diff --git a/installer/install.sh b/installer/install.sh new file mode 100644 index 0000000..53eb283 --- /dev/null +++ b/installer/install.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env sh +# Floci CLI installer — curl -fsSL https://floci.io/install.sh | sh +set -e + +VERSION="${FLOCI_CLI_VERSION:-latest}" +INSTALL_DIR="${FLOCI_INSTALL_DIR:-/usr/local/bin}" +BINARY="floci" +REPO="floci-io/floci-cli" + +detect_platform() { + OS=$(uname -s | tr '[:upper:]' '[:lower:]') + ARCH=$(uname -m) + case "$ARCH" in + x86_64) ARCH="amd64" ;; + aarch64|arm64) ARCH="arm64" ;; + *) echo "Unsupported architecture: $ARCH" >&2; exit 1 ;; + esac + case "$OS" in + linux) PLATFORM="linux-${ARCH}" ;; + darwin) PLATFORM="darwin-${ARCH}" ;; + *) echo "Unsupported OS: $OS" >&2; exit 1 ;; + esac + echo "$PLATFORM" +} + +fetch_latest_version() { + curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" \ + | grep '"tag_name"' | sed 's/.*"tag_name": "\(.*\)".*/\1/' +} + +main() { + echo "Installing Floci CLI..." + + PLATFORM=$(detect_platform) + if [ "$VERSION" = "latest" ]; then + VERSION=$(fetch_latest_version) + fi + + DOWNLOAD_URL="https://github.com/${REPO}/releases/download/${VERSION}/floci-${PLATFORM}" + TMP=$(mktemp) + + echo "Downloading floci ${VERSION} for ${PLATFORM}..." + curl -fsSL "$DOWNLOAD_URL" -o "$TMP" + chmod +x "$TMP" + + # Verify checksum if sha256sum is available + if command -v sha256sum >/dev/null 2>&1; then + SUMS_URL="https://github.com/${REPO}/releases/download/${VERSION}/sha256sums.txt" + EXPECTED=$(curl -fsSL "$SUMS_URL" | grep "floci-${PLATFORM}" | awk '{print $1}') + ACTUAL=$(sha256sum "$TMP" | awk '{print $1}') + if [ "$EXPECTED" != "$ACTUAL" ]; then + echo "Checksum mismatch! Expected: $EXPECTED Got: $ACTUAL" >&2 + rm -f "$TMP" + exit 1 + fi + echo "Checksum verified." + fi + + # Install + if [ -w "$INSTALL_DIR" ]; then + mv "$TMP" "${INSTALL_DIR}/${BINARY}" + else + echo "Installing to ${INSTALL_DIR} requires sudo..." + sudo mv "$TMP" "${INSTALL_DIR}/${BINARY}" + fi + + echo "" + echo "Floci CLI ${VERSION} installed to ${INSTALL_DIR}/${BINARY}" + echo "" + echo "Quick start:" + echo " floci start # launch Floci" + echo " floci doctor # check your environment" + echo " export AWS_ENDPOINT_URL=http://localhost:4566" + echo " aws s3 mb s3://my-bucket # use the AWS CLI against Floci" +} + +main "$@" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..f47b3d0 --- /dev/null +++ b/pom.xml @@ -0,0 +1,161 @@ + + + 4.0.0 + + io.floci + floci-cli + 0.1.0 + jar + + Floci CLI + Official command-line interface for Floci — the free, open-source local AWS emulator + https://github.com/floci-io/floci-cli + + + + MIT License + https://opensource.org/licenses/MIT + + + + + 25 + UTF-8 + 4.7.6 + 2.18.3 + 5.11.4 + io.floci.cli.FlociCli + + + + + + info.picocli + picocli + ${picocli.version} + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + ${jackson.version} + + + + + org.junit.jupiter + junit-jupiter + ${junit.version} + test + + + org.junit.jupiter + junit-jupiter-params + ${junit.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.15.0 + + ${maven.compiler.release} + + + + info.picocli + picocli-codegen + ${picocli.version} + + + + -Aproject=${project.groupId}/${project.artifactId} + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.5 + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + package + + shade + + + false + + + ${main.class} + + + + floci + + + + + + + + + + native + + + native + + + + + + org.graalvm.buildtools + native-maven-plugin + 0.10.4 + true + + + build-native + + compile-no-fork + + package + + + + floci + ${main.class} + + --enable-url-protocols=http,https + --no-fallback + -H:+ReportExceptionStackTraces + -H:IncludeResources=.*\.properties + + + + + + + + diff --git a/scoop/floci.json.template b/scoop/floci.json.template new file mode 100644 index 0000000..93bf2f0 --- /dev/null +++ b/scoop/floci.json.template @@ -0,0 +1,24 @@ +{ + "version": "{{VERSION}}", + "description": "Official CLI for the Floci local AWS emulator", + "homepage": "https://floci.io", + "license": "MIT", + "architecture": { + "64bit": { + "url": "https://github.com/floci-io/floci-cli/releases/download/{{VERSION}}/floci-windows-amd64.exe", + "hash": "{{SHA256_WINDOWS_AMD64}}", + "bin": "floci-windows-amd64.exe" + } + }, + "bin": [["floci-windows-amd64.exe", "floci"]], + "checkver": { + "github": "https://github.com/floci-io/floci-cli" + }, + "autoupdate": { + "architecture": { + "64bit": { + "url": "https://github.com/floci-io/floci-cli/releases/download/$version/floci-windows-amd64.exe" + } + } + } +} diff --git a/src/main/java/io/floci/cli/FlociCli.java b/src/main/java/io/floci/cli/FlociCli.java new file mode 100644 index 0000000..527b659 --- /dev/null +++ b/src/main/java/io/floci/cli/FlociCli.java @@ -0,0 +1,72 @@ +package io.floci.cli; + +import io.floci.cli.commands.*; +import io.floci.cli.commands.config.ConfigCommand; +import io.floci.cli.commands.snapshot.SnapshotCommand; +import io.floci.cli.output.Ansi; +import picocli.CommandLine; +import picocli.CommandLine.*; + +@Command( + name = "floci", + description = "Manage your local Floci AWS emulator%n%n" + + " floci start — launch the container%n" + + " floci stop — stop the container%n" + + " floci status — show health and version%n" + + " floci doctor — diagnose environment issues%n" + + " floci logs — stream container logs%n", + mixinStandardHelpOptions = true, + versionProvider = FlociCli.VersionProvider.class, + subcommands = { + StartCommand.class, + StopCommand.class, + RestartCommand.class, + StatusCommand.class, + LogsCommand.class, + WaitCommand.class, + VersionCommand.class, + ServicesCommand.class, + DoctorCommand.class, + ConfigCommand.class, + SnapshotCommand.class, + CompletionCommand.class, + HelpCommand.class + } +) +public class FlociCli implements Runnable { + + static class VersionProvider implements IVersionProvider { + @Override + public String[] getVersion() { + return new String[]{"floci " + VersionCommand.CLI_VERSION}; + } + } + + static class ExceptionHandler implements IExecutionExceptionHandler { + @Override + public int handleExecutionException(Exception ex, CommandLine cmd, ParseResult parseResult) { + System.err.println(Ansi.red("Error: ") + ex.getMessage()); + if (Boolean.getBoolean("floci.verbose")) { + ex.printStackTrace(System.err); + } + return 1; + } + } + + public static void main(String[] args) { + // Honor NO_COLOR and non-TTY environments + if (System.getenv("NO_COLOR") != null || System.console() == null) { + Ansi.disable(); + } + int exitCode = new CommandLine(new FlociCli()) + .setExecutionExceptionHandler(new ExceptionHandler()) + .setCaseInsensitiveEnumValuesAllowed(true) + .execute(args); + System.exit(exitCode); + } + + @Override + public void run() { + new CommandLine(this).usage(System.out); + } +} diff --git a/src/main/java/io/floci/cli/GlobalOptions.java b/src/main/java/io/floci/cli/GlobalOptions.java new file mode 100644 index 0000000..649d1f1 --- /dev/null +++ b/src/main/java/io/floci/cli/GlobalOptions.java @@ -0,0 +1,52 @@ +package io.floci.cli; + +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.Option; + +public class GlobalOptions { + + @Option(names = {"--endpoint"}, + description = "Floci server endpoint URL", + defaultValue = "${FLOCI_ENDPOINT:-http://localhost:4566}", + paramLabel = "") + public String endpoint; + + @Option(names = {"--container"}, + description = "Floci container name", + defaultValue = "${FLOCI_CONTAINER:-floci}", + paramLabel = "") + public String container; + + @Option(names = {"--profile"}, + description = "Config profile from ~/.floci/profiles/", + paramLabel = "") + public String profile; + + @Option(names = {"--output", "-o"}, + description = "Output format: text, json, yaml", + defaultValue = "text", + paramLabel = "text|json|yaml") + public OutputFormat output; + + @Option(names = {"--quiet", "-q"}, description = "Suppress non-error output") + public boolean quiet; + + @Option(names = {"--verbose", "-v"}, description = "Debug logging to stderr") + public boolean verbose; + + @Option(names = {"--no-color"}, description = "Disable ANSI colors") + public boolean noColor; + + public Printer printer() { + if (noColor || !isStdoutTty()) { + Ansi.disable(); + } + return new Printer(System.out, System.err, output, quiet); + } + + private static boolean isStdoutTty() { + return System.console() != null; + } +} diff --git a/src/main/java/io/floci/cli/commands/CompletionCommand.java b/src/main/java/io/floci/cli/commands/CompletionCommand.java new file mode 100644 index 0000000..6fe2219 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/CompletionCommand.java @@ -0,0 +1,43 @@ +package io.floci.cli.commands; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.output.Printer; +import picocli.AutoComplete; +import picocli.CommandLine; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "completion", + description = "Generate shell completion scripts", + mixinStandardHelpOptions = true +) +public class CompletionCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Parameters(index = "0", description = "Shell type: bash, zsh, fish, powershell", paramLabel = "bash|zsh|fish|powershell") + String shell; + + @Override + public Integer call() { + Printer printer = global.printer(); + CommandLine root = new CommandLine(new io.floci.cli.FlociCli()); + + String script = switch (shell.toLowerCase()) { + case "bash" -> AutoComplete.bash("floci", root); + case "zsh" -> AutoComplete.bash("floci", root); // zsh is bash-compatible; picocli bash script works for zsh too + default -> { + printer.error("Shell '" + shell + "' not supported. Supported: bash, zsh\n" + + "For fish and powershell, track https://github.com/floci-io/floci-cli/issues"); + yield null; + } + }; + + if (script == null) return 1; + System.out.print(script); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/DoctorCommand.java b/src/main/java/io/floci/cli/commands/DoctorCommand.java new file mode 100644 index 0000000..98fca5a --- /dev/null +++ b/src/main/java/io/floci/cli/commands/DoctorCommand.java @@ -0,0 +1,106 @@ +package io.floci.cli.commands; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; +import io.floci.cli.doctor.CheckStatus; +import io.floci.cli.doctor.checks.*; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + +@Command( + name = "doctor", + description = "Run environment diagnostics for Floci", + mixinStandardHelpOptions = true +) +public class DoctorCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Option(names = {"--check"}, description = "Run only a specific check by name", paramLabel = "") + String checkName; + + @Option(names = {"--fix"}, description = "Attempt to auto-fix fixable issues") + boolean fix; + + private static final List ALL_CHECKS = List.of( + new DockerInstalledCheck(), + new DockerDaemonCheck(), + new DockerSocketCheck(), + new DockerVersionCheck(), + new PortAvailableCheck(), + new ImagePresentCheck(), + new ImageVersionCheck(), + new ContainerRunningCheck(), + new EndpointReachableCheck(), + new AwsCliEndpointCheck(), + new AwsCliS3PathStyleCheck(), + new SdkRustS3XmlCheck(), + new SdkGoEndpointCheck() + ); + + @Override + public Integer call() { + Printer printer = global.printer(); + List results = new ArrayList<>(); + + printer.println(Ansi.bold("Floci Doctor") + " — checking your environment"); + printer.println(""); + + for (Check check : ALL_CHECKS) { + CheckResult result = check.run(global.endpoint, global.container); + if (checkName != null && !result.name().equals(checkName)) continue; + results.add(result); + printResult(printer, result); + } + + if (printer.format() != OutputFormat.text) { + List> structured = new ArrayList<>(); + for (CheckResult r : results) { + Map m = new LinkedHashMap<>(); + m.put("name", r.name()); + m.put("status", r.status().name()); + m.put("message", r.message()); + if (r.fix() != null) m.put("fix", r.fix()); + structured.add(m); + } + printer.structured(structured); + return 0; + } + + long fails = results.stream().filter(r -> r.status() == CheckStatus.fail).count(); + long warns = results.stream().filter(r -> r.status() == CheckStatus.warn).count(); + + printer.println(""); + if (fails == 0 && warns == 0) { + printer.println(Ansi.green("All checks passed.")); + } else { + printer.println(fails + " issue(s) found (" + fails + " fail, " + warns + " warn)." + + (fix ? "" : " Run with --fix to auto-resolve fixable issues.")); + } + + return fails > 0 ? 1 : 0; + } + + private void printResult(Printer printer, CheckResult r) { + String icon = switch (r.status()) { + case ok -> Ansi.green("✓"); + case warn -> Ansi.yellow("⚠"); + case fail -> Ansi.red("✗"); + }; + String namePadded = String.format("%-26s", r.name()); + printer.println(" " + icon + " " + namePadded + " " + r.message()); + if (r.fix() != null) { + printer.println(" " + Ansi.gray("Fix: " + r.fix())); + } + } +} diff --git a/src/main/java/io/floci/cli/commands/LogsCommand.java b/src/main/java/io/floci/cli/commands/LogsCommand.java new file mode 100644 index 0000000..bfa6eff --- /dev/null +++ b/src/main/java/io/floci/cli/commands/LogsCommand.java @@ -0,0 +1,61 @@ +package io.floci.cli.commands; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "logs", + description = "Fetch logs from the Floci container", + mixinStandardHelpOptions = true +) +public class LogsCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Option(names = {"--follow", "-f"}, description = "Follow log output") + boolean follow; + + @Option(names = {"--tail"}, description = "Number of lines from the end (0 = all)", defaultValue = "100", paramLabel = "") + int tail; + + @Option(names = {"--since"}, description = "Show logs since duration (e.g. 5m, 1h) or timestamp", paramLabel = "") + String since; + + @Option(names = {"--service"}, description = "Filter to a specific service (not yet supported; requires server-side filtering)", paramLabel = "") + String service; + + @Override + public Integer call() { + Printer printer = global.printer(); + DockerClient docker = new DockerClient(); + + try { + var info = docker.inspectContainer(global.container); + if (info.isEmpty()) { + printer.error("Container '" + global.container + "' not found.\nRun 'floci start' to launch one."); + return 1; + } + } catch (DockerException e) { + printer.error("Failed to inspect container: " + e.getMessage()); + return 1; + } + + if (service != null) { + printer.warn("--service filtering is not yet supported. Showing all container logs."); + } + + try { + docker.streamLogs(global.container, follow, tail, since); + return 0; + } catch (DockerException e) { + printer.error("Failed to fetch logs: " + e.getMessage()); + return 1; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/RestartCommand.java b/src/main/java/io/floci/cli/commands/RestartCommand.java new file mode 100644 index 0000000..050d068 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/RestartCommand.java @@ -0,0 +1,41 @@ +package io.floci.cli.commands; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "restart", + description = "Stop and restart the Floci container", + mixinStandardHelpOptions = true +) +public class RestartCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + + StopCommand stop = new StopCommand(); + stop.global = global; + stop.remove = false; + stop.timeout = 10; + int stopResult = stop.call(); + if (stopResult != 0) return stopResult; + + // Minimal wait to avoid port-already-in-use races + try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + + StartCommand start = new StartCommand(); + start.global = global; + start.port = 4566; + start.pull = "missing"; + start.image = "floci/floci:latest"; + start.detach = false; + return start.call(); + } +} diff --git a/src/main/java/io/floci/cli/commands/ServicesCommand.java b/src/main/java/io/floci/cli/commands/ServicesCommand.java new file mode 100644 index 0000000..03f79a2 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/ServicesCommand.java @@ -0,0 +1,58 @@ +package io.floci.cli.commands; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.http.FlociHttpClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + +@Command( + name = "services", + description = "List services available in the running Floci instance", + mixinStandardHelpOptions = true +) +public class ServicesCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Option(names = {"--mode"}, description = "Filter mode: docker, in-process, all (default: all)", defaultValue = "all", paramLabel = "docker|in-process|all") + String mode; + + @Override + public Integer call() { + Printer printer = global.printer(); + FlociHttpClient client = new FlociHttpClient(global.endpoint); + + List services; + try { + var health = client.health(); + services = Arrays.asList(health.services()); + } catch (Exception e) { + printer.error("Could not reach Floci at " + global.endpoint + ".\nIs Floci running? Try 'floci start'."); + return 1; + } + + if (printer.format() != OutputFormat.text) { + printer.structured(Map.of("services", services, "count", services.size())); + return 0; + } + + printer.println(Ansi.bold("Floci Services") + " " + Ansi.gray("(" + services.size() + " enabled)")); + printer.println(""); + for (String svc : services) { + printer.println(" " + Ansi.green("✓") + " " + svc); + } + if (services.isEmpty()) { + printer.println(" " + Ansi.gray("(no services reported)")); + } + + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/StartCommand.java b/src/main/java/io/floci/cli/commands/StartCommand.java new file mode 100644 index 0000000..ec5f350 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/StartCommand.java @@ -0,0 +1,114 @@ +package io.floci.cli.commands; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; + +@Command( + name = "start", + description = "Start the Floci container", + mixinStandardHelpOptions = true +) +public class StartCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Option(names = {"--port"}, description = "Host port to bind (default: 4566)", defaultValue = "4566", paramLabel = "") + int port; + + @Option(names = {"--persist"}, description = "Host directory for persistent state", paramLabel = "") + String persistDir; + + @Option(names = {"--services"}, description = "Comma-separated list of services to enable", paramLabel = "") + String services; + + @Option(names = {"--detach"}, description = "Return immediately without waiting for readiness") + boolean detach; + + @Option(names = {"--image"}, description = "Image reference to use (default: floci/floci:latest)", defaultValue = "floci/floci:latest", paramLabel = "") + String image; + + @Option(names = {"--pull"}, description = "Image pull policy: always, missing, never", defaultValue = "missing", paramLabel = "always|missing|never") + String pull; + + @Override + public Integer call() { + Printer printer = global.printer(); + DockerClient docker = new DockerClient(); + + // Verify docker is available + if (!DockerClient.isInstalled()) { + printer.error("docker binary not found in PATH.\nInstall Docker Desktop from https://docs.docker.com/get-docker/"); + return 1; + } + + // Check if container already exists + try { + var existing = docker.inspectContainer(global.container); + if (existing.isPresent()) { + String state = existing.get().state(); + if ("running".equals(state)) { + printer.error("Container '" + global.container + "' is already running.\nRun 'floci stop' first or pass --container to use a different name."); + return 1; + } + // Remove stopped container so we can start fresh + printer.println(Ansi.gray("Removing stopped container '" + global.container + "'...")); + docker.removeContainer(global.container); + } + } catch (DockerException e) { + printer.error("Failed to inspect container: " + e.getMessage()); + return 1; + } + + // Pull image if needed + try { + printer.println(Ansi.gray("Checking image " + image + " (policy: " + pull + ")...")); + docker.pull(image, pull); + } catch (DockerException e) { + printer.error("Failed to pull image: " + e.getMessage() + "\nRun 'floci start --pull never' to skip pulling."); + return 1; + } + + // Build docker run arguments + List args = new ArrayList<>(); + args.addAll(List.of("-d", "--name", global.container)); + args.addAll(List.of("-p", port + ":4566")); + args.addAll(List.of("-v", "/var/run/docker.sock:/var/run/docker.sock")); + if (persistDir != null) { + args.addAll(List.of("-v", persistDir + ":/var/lib/floci")); + } + if (services != null && !services.isBlank()) { + args.addAll(List.of("-e", "FLOCI_SERVICES=" + services)); + } + args.add(image); + + try { + printer.println("Starting " + Ansi.gold("Floci") + " container..."); + String id = docker.startContainer(args); + printer.println(Ansi.green("Container started") + " (" + id.substring(0, Math.min(12, id.length())) + ")"); + } catch (DockerException e) { + printer.error("Failed to start container: " + e.getMessage()); + return 1; + } + + if (detach) { + printer.println(Ansi.gray("Detached. Run 'floci wait' to poll for readiness.")); + return 0; + } + + // Wait for readiness + printer.println(Ansi.gray("Waiting for Floci to be ready...")); + WaitCommand wait = new WaitCommand(); + wait.global = global; + wait.timeout = "30s"; + return wait.call(); + } +} diff --git a/src/main/java/io/floci/cli/commands/StatusCommand.java b/src/main/java/io/floci/cli/commands/StatusCommand.java new file mode 100644 index 0000000..a14b950 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/StatusCommand.java @@ -0,0 +1,98 @@ +package io.floci.cli.commands; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.http.FlociHttpClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Callable; + +@Command( + name = "status", + description = "Show Floci container and server status", + mixinStandardHelpOptions = true +) +public class StatusCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + DockerClient docker = new DockerClient(); + + // Gather container info + String containerState = "not found"; + String containerImage = ""; + String containerPorts = ""; + try { + Optional info = docker.inspectContainer(global.container); + if (info.isPresent()) { + containerState = info.get().state(); + containerImage = info.get().image(); + containerPorts = info.get().ports(); + } + } catch (DockerException e) { + containerState = "error: " + e.getMessage(); + } + + // Gather server info + String serverVersion = "unavailable"; + String serverEdition = ""; + boolean reachable = false; + FlociHttpClient client = new FlociHttpClient(global.endpoint); + try { + var health = client.health(); + serverVersion = health.version(); + serverEdition = health.edition(); + reachable = true; + } catch (Exception ignored) {} + + Map data = new LinkedHashMap<>(); + data.put("container", global.container); + data.put("state", containerState); + data.put("image", containerImage); + data.put("ports", containerPorts); + data.put("endpoint", global.endpoint); + data.put("reachable", reachable); + data.put("version", serverVersion); + data.put("edition", serverEdition); + + if (printer.format() != OutputFormat.text) { + printer.structured(data); + return 0; + } + + printer.println(Ansi.bold("Floci Status")); + printer.println(""); + String stateColor = switch (containerState) { + case "running" -> Ansi.green(containerState); + case "not found" -> Ansi.gray(containerState); + default -> Ansi.red(containerState); + }; + printer.println(" Container: " + global.container + " " + stateColor); + if (!containerImage.isBlank()) printer.println(" Image: " + containerImage); + if (!containerPorts.isBlank()) printer.println(" Ports: " + containerPorts); + printer.println(" Endpoint: " + global.endpoint); + printer.println(" Reachable: " + (reachable ? Ansi.green("yes") : Ansi.red("no"))); + if (reachable) { + printer.println(" Version: " + serverVersion); + if (!serverEdition.isBlank()) printer.println(" Edition: " + serverEdition); + } + + if (!reachable && !"running".equals(containerState)) { + printer.println(""); + printer.println(Ansi.gray("Run 'floci start' to launch Floci.")); + } + + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/StopCommand.java b/src/main/java/io/floci/cli/commands/StopCommand.java new file mode 100644 index 0000000..4526775 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/StopCommand.java @@ -0,0 +1,73 @@ +package io.floci.cli.commands; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "stop", + description = "Stop the Floci container", + mixinStandardHelpOptions = true +) +public class StopCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Option(names = {"--remove", "-r"}, description = "Remove the container after stopping") + boolean remove; + + @Option(names = {"--timeout"}, description = "Seconds to wait before forcefully killing (default: 10)", defaultValue = "10", paramLabel = "") + int timeout; + + @Override + public Integer call() { + Printer printer = global.printer(); + DockerClient docker = new DockerClient(); + + try { + var info = docker.inspectContainer(global.container); + if (info.isEmpty()) { + printer.error("Container '" + global.container + "' not found.\nRun 'floci start' to launch one."); + return 1; + } + if (!"running".equals(info.get().state())) { + printer.println(Ansi.yellow("Container '" + global.container + "' is not running (state: " + info.get().state() + ")")); + if (remove) { + docker.removeContainer(global.container); + printer.println("Container removed."); + } + return 0; + } + } catch (DockerException e) { + printer.error("Failed to inspect container: " + e.getMessage()); + return 1; + } + + try { + printer.println("Stopping " + Ansi.gold("Floci") + " container '" + global.container + "'..."); + docker.stopContainer(global.container, timeout); + printer.println(Ansi.green("Stopped.")); + } catch (DockerException e) { + printer.error("Failed to stop container: " + e.getMessage()); + return 1; + } + + if (remove) { + try { + docker.removeContainer(global.container); + printer.println("Container removed."); + } catch (DockerException e) { + printer.error("Failed to remove container: " + e.getMessage()); + return 1; + } + } + + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/VersionCommand.java b/src/main/java/io/floci/cli/commands/VersionCommand.java new file mode 100644 index 0000000..7fde322 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/VersionCommand.java @@ -0,0 +1,71 @@ +package io.floci.cli.commands; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.http.FlociHttpClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Callable; + +@Command( + name = "version", + description = "Show CLI version, connected server version, and image digest", + mixinStandardHelpOptions = true +) +public class VersionCommand implements Callable { + + public static final String CLI_VERSION = "0.1.0"; + + @Mixin + GlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + + String serverVersion = null; + String serverEdition = null; + String imageDigest = null; + + FlociHttpClient client = new FlociHttpClient(global.endpoint); + try { + var info = client.info(); + serverVersion = info.version(); + serverEdition = info.edition(); + } catch (Exception ignored) {} + + // Try to read image digest from Docker (best-effort) + try { + var docker = new io.floci.cli.docker.DockerClient(); + imageDigest = docker.imageDigest("floci/floci").orElse(null); + } catch (Exception ignored) {} + + Map data = new LinkedHashMap<>(); + data.put("cli", CLI_VERSION); + data.put("server", Optional.ofNullable(serverVersion).orElse("unavailable")); + data.put("edition", Optional.ofNullable(serverEdition).orElse("")); + if (imageDigest != null) data.put("digest", imageDigest); + + if (printer.format() != OutputFormat.text) { + printer.structured(data); + return 0; + } + + printer.println(Ansi.bold("Floci CLI") + " " + Ansi.gold(CLI_VERSION)); + if (serverVersion != null) { + printer.println("Server: " + serverVersion + (serverEdition != null ? " (" + serverEdition + ")" : "")); + } else { + printer.println("Server: " + Ansi.gray("not reachable at " + global.endpoint)); + } + if (imageDigest != null) { + printer.println("Image: " + imageDigest); + } + + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/WaitCommand.java b/src/main/java/io/floci/cli/commands/WaitCommand.java new file mode 100644 index 0000000..d25a3e4 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/WaitCommand.java @@ -0,0 +1,79 @@ +package io.floci.cli.commands; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.http.FlociHttpClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.Callable; + +@Command( + name = "wait", + description = "Wait until Floci is ready to accept requests", + mixinStandardHelpOptions = true +) +public class WaitCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Option(names = {"--timeout"}, description = "Maximum time to wait (e.g. 30s, 2m)", defaultValue = "30s", paramLabel = "") + String timeout; + + @Option(names = {"--service"}, description = "Wait until a specific service is enabled", paramLabel = "") + String service; + + @Override + public Integer call() { + Printer printer = global.printer(); + long timeoutMillis = parseDuration(timeout); + FlociHttpClient client = new FlociHttpClient(global.endpoint); + Instant deadline = Instant.now().plusMillis(timeoutMillis); + + while (Instant.now().isBefore(deadline)) { + if (isReady(client, service)) { + printer.println(Ansi.green("Floci is ready") + " (" + global.endpoint + ")"); + return 0; + } + printSpinner(printer, deadline); + try { Thread.sleep(500); } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + + printer.error("Timed out waiting for Floci after " + timeout + ".\nIs the container running? Try 'floci status'."); + return 1; + } + + private boolean isReady(FlociHttpClient client, String requiredService) { + try { + var health = client.health(); + if (requiredService == null) return true; + for (String s : health.services()) { + if (s.equalsIgnoreCase(requiredService)) return true; + } + return false; + } catch (Exception e) { + return false; + } + } + + private void printSpinner(Printer printer, Instant deadline) { + long remaining = Duration.between(Instant.now(), deadline).toSeconds(); + printer.print("\r" + Ansi.gray("Waiting... (" + remaining + "s remaining)") + " "); + } + + public static long parseDuration(String s) { + if (s == null || s.isBlank()) return 30_000; + s = s.trim().toLowerCase(); + if (s.endsWith("ms")) return Long.parseLong(s.substring(0, s.length() - 2)); + if (s.endsWith("s")) return Long.parseLong(s.substring(0, s.length() - 1)) * 1000; + if (s.endsWith("m")) return Long.parseLong(s.substring(0, s.length() - 1)) * 60_000; + if (s.endsWith("h")) return Long.parseLong(s.substring(0, s.length() - 1)) * 3_600_000; + return Long.parseLong(s) * 1000; + } +} diff --git a/src/main/java/io/floci/cli/commands/config/ConfigCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigCommand.java new file mode 100644 index 0000000..21a3d94 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/config/ConfigCommand.java @@ -0,0 +1,23 @@ +package io.floci.cli.commands.config; + +import picocli.CommandLine; +import picocli.CommandLine.*; + +@Command( + name = "config", + description = "Manage Floci configuration", + mixinStandardHelpOptions = true, + subcommands = { + ConfigShowCommand.class, + ConfigValidateCommand.class, + ConfigProfileCommand.class, + HelpCommand.class + } +) +public class ConfigCommand implements Runnable { + + @Override + public void run() { + new CommandLine(this).usage(System.out); + } +} diff --git a/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java new file mode 100644 index 0000000..ae43479 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/config/ConfigProfileCommand.java @@ -0,0 +1,118 @@ +package io.floci.cli.commands.config; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.config.Profile; +import io.floci.cli.config.ProfileStore; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.Callable; + +@Command( + name = "profile", + description = "Manage Floci configuration profiles", + mixinStandardHelpOptions = true, + subcommands = {HelpCommand.class} +) +public class ConfigProfileCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Parameters(index = "0", description = "Action: list, show, create, delete", paramLabel = "list|show|create|delete") + String action; + + @Parameters(index = "1", description = "Profile name (required for show, create, delete)", arity = "0..1", paramLabel = "") + String name; + + @Override + public Integer call() { + Printer printer = global.printer(); + ProfileStore store = new ProfileStore(); + + return switch (action.toLowerCase()) { + case "list" -> listProfiles(printer, store); + case "show" -> showProfile(printer, store); + case "create" -> createProfile(printer, store); + case "delete" -> deleteProfile(printer, store); + default -> { + printer.error("Unknown action '" + action + "'. Use: list, show, create, delete"); + yield 1; + } + }; + } + + private int listProfiles(Printer printer, ProfileStore store) { + try { + List profiles = store.list(); + if (profiles.isEmpty()) { + printer.println(Ansi.gray("No profiles found. Create one with: floci config profile create ")); + return 0; + } + printer.println(Ansi.bold("Profiles:")); + for (Profile p : profiles) { + printer.println(" " + p.name + Ansi.gray(" " + (p.endpoint != null ? p.endpoint : ""))); + } + return 0; + } catch (IOException e) { + printer.error("Could not list profiles: " + e.getMessage()); + return 1; + } + } + + private int showProfile(Printer printer, ProfileStore store) { + if (name == null) { printer.error("Profile name required."); return 1; } + try { + var profile = store.get(name); + if (profile.isEmpty()) { printer.error("Profile '" + name + "' not found."); return 1; } + Profile p = profile.get(); + printer.println(Ansi.bold("Profile: ") + p.name); + if (p.endpoint != null) printer.println(" endpoint: " + p.endpoint); + if (p.container != null) printer.println(" container: " + p.container); + if (p.image != null) printer.println(" image: " + p.image); + if (p.port != null) printer.println(" port: " + p.port); + if (p.persistDir != null) printer.println(" persistDir: " + p.persistDir); + if (p.services != null) printer.println(" services: " + p.services); + return 0; + } catch (IOException e) { + printer.error("Could not read profile: " + e.getMessage()); + return 1; + } + } + + private int createProfile(Printer printer, ProfileStore store) { + if (name == null) { printer.error("Profile name required."); return 1; } + try { + if (store.get(name).isPresent()) { + printer.error("Profile '" + name + "' already exists. Delete it first or edit " + store.profileFile(name)); + return 1; + } + Profile p = new Profile(name); + store.save(p); + printer.println(Ansi.green("Created") + " profile '" + name + "' at " + store.profileFile(name)); + printer.println(Ansi.gray("Edit the file to customize endpoint, container, image, etc.")); + return 0; + } catch (IOException e) { + printer.error("Could not create profile: " + e.getMessage()); + return 1; + } + } + + private int deleteProfile(Printer printer, ProfileStore store) { + if (name == null) { printer.error("Profile name required."); return 1; } + try { + if (!store.delete(name)) { + printer.error("Profile '" + name + "' not found."); + return 1; + } + printer.println(Ansi.green("Deleted") + " profile '" + name + "'"); + return 0; + } catch (IOException e) { + printer.error("Could not delete profile: " + e.getMessage()); + return 1; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java new file mode 100644 index 0000000..8e59a8f --- /dev/null +++ b/src/main/java/io/floci/cli/commands/config/ConfigShowCommand.java @@ -0,0 +1,70 @@ +package io.floci.cli.commands.config; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.config.Profile; +import io.floci.cli.config.ProfileStore; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Callable; + +@Command( + name = "show", + description = "Show the active configuration", + mixinStandardHelpOptions = true +) +public class ConfigShowCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + ProfileStore store = new ProfileStore(); + + Profile active = new Profile(global.profile != null ? global.profile : "default"); + active.endpoint = global.endpoint; + active.container = global.container; + active.output = global.output != null ? global.output.name() : "text"; + + if (global.profile != null) { + try { + Optional loaded = store.get(global.profile); + if (loaded.isPresent()) { + active = loaded.get(); + } else { + printer.warn("Profile '" + global.profile + "' not found. Using defaults."); + } + } catch (IOException e) { + printer.warn("Could not load profile: " + e.getMessage()); + } + } + + Map data = new LinkedHashMap<>(); + data.put("profile", active.name); + data.put("endpoint", active.endpoint != null ? active.endpoint : global.endpoint); + data.put("container", active.container != null ? active.container : global.container); + data.put("output", active.output); + + if (printer.format() != OutputFormat.text) { + printer.structured(data); + return 0; + } + + printer.println(Ansi.bold("Active Configuration")); + printer.println(""); + printer.println(" Profile: " + active.name); + printer.println(" Endpoint: " + (active.endpoint != null ? active.endpoint : global.endpoint)); + printer.println(" Container: " + (active.container != null ? active.container : global.container)); + printer.println(" Output: " + (active.output != null ? active.output : "text")); + + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java new file mode 100644 index 0000000..604caff --- /dev/null +++ b/src/main/java/io/floci/cli/commands/config/ConfigValidateCommand.java @@ -0,0 +1,94 @@ +package io.floci.cli.commands.config; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.regex.Pattern; + +@Command( + name = "validate", + description = "Validate a docker-compose.yml file for Floci compatibility", + mixinStandardHelpOptions = true +) +public class ConfigValidateCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Option(names = {"--file", "-f"}, description = "Path to docker-compose file", paramLabel = "") + String file; + + @Override + public Integer call() { + Printer printer = global.printer(); + + Path composeFile = resolveComposeFile(); + if (composeFile == null) { + printer.error("No docker-compose file found. Pass --file or run in a directory with docker-compose.yml."); + return 1; + } + + String content; + try { + content = Files.readString(composeFile); + } catch (IOException e) { + printer.error("Could not read " + composeFile + ": " + e.getMessage()); + return 1; + } + + printer.println(Ansi.bold("Validating") + " " + composeFile); + printer.println(""); + + List issues = new ArrayList<>(); + List warnings = new ArrayList<>(); + + // Check for docker.sock mount + if (!content.contains("/var/run/docker.sock")) { + issues.add("Missing /var/run/docker.sock volume mount — required for Lambda, EC2, EKS, MSK, ECR, CodeBuild"); + } + + // Check port mapping + if (!Pattern.compile("4566\\s*:\\s*4566").matcher(content).find()) { + issues.add("Port mapping 4566:4566 not found — Floci listens on 4566 by default"); + } + + // Check for floci image + if (!content.contains("floci/floci") && !content.contains("ghcr.io/floci-io/floci")) { + warnings.add("Floci image reference not detected — ensure your service uses floci/floci or ghcr.io/floci-io/floci"); + } + + for (String issue : issues) { + printer.println(" " + Ansi.red("✗") + " " + issue); + } + for (String warn : warnings) { + printer.println(" " + Ansi.yellow("⚠") + " " + warn); + } + if (issues.isEmpty() && warnings.isEmpty()) { + printer.println(" " + Ansi.green("✓") + " Compose file looks good"); + } + + printer.println(""); + if (!issues.isEmpty()) { + printer.println(issues.size() + " error(s) found."); + return 1; + } + return 0; + } + + private Path resolveComposeFile() { + if (file != null) return Path.of(file); + for (String name : List.of("docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml")) { + Path p = Path.of(name); + if (Files.exists(p)) return p; + } + return null; + } +} diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotCommand.java new file mode 100644 index 0000000..7a65c9b --- /dev/null +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotCommand.java @@ -0,0 +1,26 @@ +package io.floci.cli.commands.snapshot; + +import picocli.CommandLine; +import picocli.CommandLine.*; + +@Command( + name = "snapshot", + description = "Manage Floci state snapshots", + mixinStandardHelpOptions = true, + subcommands = { + SnapshotSaveCommand.class, + SnapshotLoadCommand.class, + SnapshotListCommand.class, + SnapshotDeleteCommand.class, + SnapshotExportCommand.class, + SnapshotImportCommand.class, + HelpCommand.class + } +) +public class SnapshotCommand implements Runnable { + + @Override + public void run() { + new CommandLine(this).usage(System.out); + } +} diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java new file mode 100644 index 0000000..432f035 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java @@ -0,0 +1,38 @@ +package io.floci.cli.commands.snapshot; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.http.FlociException; +import io.floci.cli.http.FlociHttpClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "delete", + description = "Delete a snapshot", + mixinStandardHelpOptions = true +) +public class SnapshotDeleteCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Parameters(index = "0", description = "Snapshot name", paramLabel = "") + String name; + + @Override + public Integer call() { + Printer printer = global.printer(); + FlociHttpClient client = new FlociHttpClient(global.endpoint); + try { + client.deleteSnapshot(name); + printer.println(Ansi.green("Snapshot deleted:") + " " + name); + return 0; + } catch (FlociException e) { + printer.error("Failed to delete snapshot: " + e.getMessage()); + return 1; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotExportCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotExportCommand.java new file mode 100644 index 0000000..f1e4f71 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotExportCommand.java @@ -0,0 +1,33 @@ +package io.floci.cli.commands.snapshot; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "export", + description = "Export a snapshot to a tarball file", + mixinStandardHelpOptions = true +) +public class SnapshotExportCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Parameters(index = "0", description = "Snapshot name", paramLabel = "") + String name; + + @Option(names = {"--file", "-f"}, description = "Destination file path", required = true, paramLabel = "") + String outputFile; + + @Override + public Integer call() { + Printer printer = global.printer(); + // TODO: implement GET /_floci/snapshots//export streaming to file + printer.error("snapshot export requires floci-server >= 1.6.0\n" + + "See TODO.md for the required server-side API contract."); + return 1; + } +} diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotImportCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotImportCommand.java new file mode 100644 index 0000000..887e55d --- /dev/null +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotImportCommand.java @@ -0,0 +1,33 @@ +package io.floci.cli.commands.snapshot; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "import", + description = "Import a snapshot from a tarball file", + mixinStandardHelpOptions = true +) +public class SnapshotImportCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Option(names = {"--file", "-f"}, description = "Source tarball path", required = true, paramLabel = "") + String inputFile; + + @Option(names = {"--name"}, description = "Name for the imported snapshot", paramLabel = "") + String name; + + @Override + public Integer call() { + Printer printer = global.printer(); + // TODO: implement POST /_floci/snapshots/import with multipart upload + printer.error("snapshot import requires floci-server >= 1.6.0\n" + + "See TODO.md for the required server-side API contract."); + return 1; + } +} diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotListCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotListCommand.java new file mode 100644 index 0000000..143c97d --- /dev/null +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotListCommand.java @@ -0,0 +1,50 @@ +package io.floci.cli.commands.snapshot; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.http.FlociException; +import io.floci.cli.http.FlociHttpClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "list", + description = "List available snapshots", + mixinStandardHelpOptions = true +) +public class SnapshotListCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + FlociHttpClient client = new FlociHttpClient(global.endpoint); + try { + var node = client.listSnapshots(); + if (printer.format() != OutputFormat.text) { + printer.structured(node); + return 0; + } + if (node.isArray() && node.size() == 0) { + printer.println(Ansi.gray("No snapshots found.")); + return 0; + } + printer.println(Ansi.bold("Snapshots:")); + node.forEach(s -> printer.println(" " + s.asText())); + return 0; + } catch (FlociException e) { + if (e.getMessage().contains("404") || e.getMessage().contains("501")) { + printer.error("Snapshot API not available on this server version.\n" + + "See TODO.md for the required server-side API contract."); + } else { + printer.error("Failed to list snapshots: " + e.getMessage()); + } + return 1; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java new file mode 100644 index 0000000..d771091 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java @@ -0,0 +1,43 @@ +package io.floci.cli.commands.snapshot; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.http.FlociException; +import io.floci.cli.http.FlociHttpClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "load", + description = "Restore a saved snapshot", + mixinStandardHelpOptions = true +) +public class SnapshotLoadCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Parameters(index = "0", description = "Snapshot name", paramLabel = "") + String name; + + @Override + public Integer call() { + Printer printer = global.printer(); + FlociHttpClient client = new FlociHttpClient(global.endpoint); + try { + client.loadSnapshot(name); + printer.println(Ansi.green("Snapshot loaded:") + " " + name); + return 0; + } catch (FlociException e) { + if (e.getMessage().contains("404") || e.getMessage().contains("501")) { + printer.error("Snapshot API not available on this server version.\n" + + "See TODO.md for the required server-side API contract."); + } else { + printer.error("Failed to load snapshot: " + e.getMessage()); + } + return 1; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java new file mode 100644 index 0000000..6603ebf --- /dev/null +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java @@ -0,0 +1,46 @@ +package io.floci.cli.commands.snapshot; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.http.FlociException; +import io.floci.cli.http.FlociHttpClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "save", + description = "Save the current Floci state as a named snapshot", + mixinStandardHelpOptions = true +) +public class SnapshotSaveCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Parameters(index = "0", description = "Snapshot name", paramLabel = "") + String name; + + @Option(names = {"--message", "-m"}, description = "Optional description", paramLabel = "") + String message; + + @Override + public Integer call() { + Printer printer = global.printer(); + FlociHttpClient client = new FlociHttpClient(global.endpoint); + try { + client.postSnapshot(name); + printer.println(Ansi.green("Snapshot saved:") + " " + name); + return 0; + } catch (FlociException e) { + if (e.getMessage().contains("404") || e.getMessage().contains("501")) { + printer.error("Snapshot API not available on this server version.\n" + + "See TODO.md for the required server-side API contract."); + } else { + printer.error("Failed to save snapshot: " + e.getMessage()); + } + return 1; + } + } +} diff --git a/src/main/java/io/floci/cli/config/Profile.java b/src/main/java/io/floci/cli/config/Profile.java new file mode 100644 index 0000000..c4d5dc9 --- /dev/null +++ b/src/main/java/io/floci/cli/config/Profile.java @@ -0,0 +1,23 @@ +package io.floci.cli.config; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Profile { + public String name; + public String endpoint; + public String container; + public String image; + public Integer port; + public String persistDir; + public String services; + public String output; + + public Profile() {} + + public Profile(String name) { + this.name = name; + this.endpoint = "http://localhost:4566"; + this.container = "floci"; + } +} diff --git a/src/main/java/io/floci/cli/config/ProfileStore.java b/src/main/java/io/floci/cli/config/ProfileStore.java new file mode 100644 index 0000000..f201d25 --- /dev/null +++ b/src/main/java/io/floci/cli/config/ProfileStore.java @@ -0,0 +1,61 @@ +package io.floci.cli.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class ProfileStore { + + private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); + + private final Path profilesDir; + + public ProfileStore() { + this(Path.of(System.getProperty("user.home"), ".floci", "profiles")); + } + + public ProfileStore(Path profilesDir) { + this.profilesDir = profilesDir; + } + + public List list() throws IOException { + if (!Files.exists(profilesDir)) return List.of(); + List profiles = new ArrayList<>(); + try (var stream = Files.list(profilesDir)) { + stream.filter(p -> p.toString().endsWith(".yaml") || p.toString().endsWith(".yml")) + .forEach(p -> { + try { + Profile profile = YAML.readValue(p.toFile(), Profile.class); + profiles.add(profile); + } catch (IOException ignored) {} + }); + } + return profiles; + } + + public Optional get(String name) throws IOException { + Path file = profileFile(name); + if (!Files.exists(file)) return Optional.empty(); + return Optional.of(YAML.readValue(file.toFile(), Profile.class)); + } + + public void save(Profile profile) throws IOException { + Files.createDirectories(profilesDir); + YAML.writeValue(profileFile(profile.name).toFile(), profile); + } + + public boolean delete(String name) throws IOException { + Path file = profileFile(name); + return Files.deleteIfExists(file); + } + + public Path profileFile(String name) { + return profilesDir.resolve(name + ".yaml"); + } +} diff --git a/src/main/java/io/floci/cli/docker/DockerClient.java b/src/main/java/io/floci/cli/docker/DockerClient.java new file mode 100644 index 0000000..e4f6205 --- /dev/null +++ b/src/main/java/io/floci/cli/docker/DockerClient.java @@ -0,0 +1,181 @@ +package io.floci.cli.docker; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** + * Thin subprocess wrapper around the docker CLI. + * Subprocess invocation avoids reflection config needed by docker-java on native image. + */ +public class DockerClient { + + public record ContainerInfo( + String id, + String name, + String image, + String status, + String state, + String ports) {} + + public record ImageInfo(String id, String repository, String tag, String digest) {} + + public String dockerVersion() throws DockerException { + return run("docker", "version", "--format", "{{.Server.Version}}").trim(); + } + + public boolean isDaemonReachable() { + try { + int code = runProcess("docker", "info", "--format", "{{.ServerVersion}}").waitFor(); + return code == 0; + } catch (Exception e) { + return false; + } + } + + public Optional inspectContainer(String name) throws DockerException { + try { + String out = run("docker", "inspect", "--format", + "{{.Id}}|{{.Name}}|{{.Config.Image}}|{{.Status}}|{{.State.Status}}|{{range $p, $b := .NetworkSettings.Ports}}{{$p}} {{end}}", + name); + if (out.isBlank()) return Optional.empty(); + String[] parts = out.trim().split("\\|", -1); + return Optional.of(new ContainerInfo( + parts.length > 0 ? parts[0] : "", + parts.length > 1 ? parts[1].replaceFirst("^/", "") : name, + parts.length > 2 ? parts[2] : "", + parts.length > 3 ? parts[3] : "", + parts.length > 4 ? parts[4] : "", + parts.length > 5 ? parts[5].trim() : "")); + } catch (DockerException e) { + if (e.getMessage() != null && e.getMessage().contains("No such")) { + return Optional.empty(); + } + throw e; + } + } + + public boolean isImagePresent(String image) throws DockerException { + try { + String out = run("docker", "images", "-q", image); + return !out.isBlank(); + } catch (DockerException e) { + return false; + } + } + + public Optional imageDigest(String image) throws DockerException { + try { + String out = run("docker", "inspect", "--format", "{{index .RepoDigests 0}}", image); + return out.isBlank() ? Optional.empty() : Optional.of(out.trim()); + } catch (DockerException e) { + return Optional.empty(); + } + } + + public void pull(String image, String policy) throws DockerException { + if ("never".equalsIgnoreCase(policy)) return; + if ("missing".equalsIgnoreCase(policy) && isImagePresent(image)) return; + runStreaming("docker", "pull", image); + } + + public String startContainer(List args) throws DockerException { + List cmd = new ArrayList<>(); + cmd.add("docker"); + cmd.add("run"); + cmd.addAll(args); + return run(cmd.toArray(String[]::new)).trim(); + } + + public void stopContainer(String name, int timeout) throws DockerException { + run("docker", "stop", "--time", String.valueOf(timeout), name); + } + + public void removeContainer(String name) throws DockerException { + run("docker", "rm", name); + } + + public void streamLogs(String name, boolean follow, int tail, String since) throws DockerException { + List cmd = new ArrayList<>(List.of("docker", "logs")); + if (follow) cmd.add("--follow"); + if (tail > 0) { cmd.add("--tail"); cmd.add(String.valueOf(tail)); } + if (since != null && !since.isBlank()) { cmd.add("--since"); cmd.add(since); } + cmd.add(name); + runStreaming(cmd.toArray(String[]::new)); + } + + private String run(String... cmd) throws DockerException { + try { + Process proc = runProcess(cmd); + String stdout = new String(proc.getInputStream().readAllBytes()); + String stderr = new String(proc.getErrorStream().readAllBytes()); + int code = proc.waitFor(); + if (code != 0) { + throw new DockerException(stderr.isBlank() ? stdout : stderr); + } + return stdout; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new DockerException("Interrupted"); + } catch (IOException e) { + if (e.getMessage() != null && e.getMessage().contains("No such file")) { + throw new DockerException("docker binary not found in PATH. Install Docker Desktop or Docker Engine."); + } + throw new DockerException(e.getMessage()); + } + } + + private void runStreaming(String... cmd) throws DockerException { + try { + Process proc = runProcess(cmd); + Thread out = new Thread(() -> { + try (var reader = new BufferedReader(new InputStreamReader(proc.getInputStream()))) { + reader.lines().forEach(System.out::println); + } catch (IOException ignored) {} + }); + Thread err = new Thread(() -> { + try (var reader = new BufferedReader(new InputStreamReader(proc.getErrorStream()))) { + reader.lines().forEach(System.err::println); + } catch (IOException ignored) {} + }); + out.start(); + err.start(); + int code = proc.waitFor(); + out.join(); + err.join(); + if (code != 0) { + throw new DockerException("docker command failed with exit code " + code); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new DockerException("Interrupted"); + } catch (IOException e) { + throw new DockerException(e.getMessage()); + } + } + + private Process runProcess(String... cmd) throws IOException { + return new ProcessBuilder(cmd) + .redirectErrorStream(false) + .start(); + } + + public static boolean isInstalled() { + try { + Process p = new ProcessBuilder("docker", "--version").start(); + return p.waitFor() == 0; + } catch (Exception e) { + return false; + } + } + + public static String socketPath() { + String os = System.getProperty("os.name", "").toLowerCase(); + if (os.contains("win")) return "\\\\.\\pipe\\docker_engine"; + return System.getenv().getOrDefault("DOCKER_SOCK", "/var/run/docker.sock"); + } +} diff --git a/src/main/java/io/floci/cli/docker/DockerException.java b/src/main/java/io/floci/cli/docker/DockerException.java new file mode 100644 index 0000000..4a0bf6f --- /dev/null +++ b/src/main/java/io/floci/cli/docker/DockerException.java @@ -0,0 +1,7 @@ +package io.floci.cli.docker; + +public class DockerException extends Exception { + public DockerException(String message) { + super(message); + } +} diff --git a/src/main/java/io/floci/cli/doctor/Check.java b/src/main/java/io/floci/cli/doctor/Check.java new file mode 100644 index 0000000..e0a9f5b --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/Check.java @@ -0,0 +1,6 @@ +package io.floci.cli.doctor; + +@FunctionalInterface +public interface Check { + CheckResult run(String endpoint, String container); +} diff --git a/src/main/java/io/floci/cli/doctor/CheckResult.java b/src/main/java/io/floci/cli/doctor/CheckResult.java new file mode 100644 index 0000000..0b081fa --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/CheckResult.java @@ -0,0 +1,20 @@ +package io.floci.cli.doctor; + +public record CheckResult( + String name, + CheckStatus status, + String message, + String fix) { + + public static CheckResult ok(String name, String message) { + return new CheckResult(name, CheckStatus.ok, message, null); + } + + public static CheckResult warn(String name, String message, String fix) { + return new CheckResult(name, CheckStatus.warn, message, fix); + } + + public static CheckResult fail(String name, String message, String fix) { + return new CheckResult(name, CheckStatus.fail, message, fix); + } +} diff --git a/src/main/java/io/floci/cli/doctor/CheckStatus.java b/src/main/java/io/floci/cli/doctor/CheckStatus.java new file mode 100644 index 0000000..bb832ad --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/CheckStatus.java @@ -0,0 +1,5 @@ +package io.floci.cli.doctor; + +public enum CheckStatus { + ok, warn, fail +} diff --git a/src/main/java/io/floci/cli/doctor/checks/AwsCliEndpointCheck.java b/src/main/java/io/floci/cli/doctor/checks/AwsCliEndpointCheck.java new file mode 100644 index 0000000..542859b --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/AwsCliEndpointCheck.java @@ -0,0 +1,31 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +public class AwsCliEndpointCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + // Check if aws CLI is installed first + if (!isAwsCliInstalled()) { + return CheckResult.ok("aws.cli.endpoint", "aws CLI not installed — skipped"); + } + String envVar = System.getenv("AWS_ENDPOINT_URL"); + if (envVar != null && !envVar.isBlank()) { + return CheckResult.ok("aws.cli.endpoint", "AWS_ENDPOINT_URL=" + envVar); + } + return CheckResult.warn("aws.cli.endpoint", + "AWS_ENDPOINT_URL is not set", + "export AWS_ENDPOINT_URL=" + endpoint); + } + + private boolean isAwsCliInstalled() { + try { + Process p = new ProcessBuilder("aws", "--version").start(); + return p.waitFor() == 0; + } catch (Exception e) { + return false; + } + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/AwsCliS3PathStyleCheck.java b/src/main/java/io/floci/cli/doctor/checks/AwsCliS3PathStyleCheck.java new file mode 100644 index 0000000..25d69e6 --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/AwsCliS3PathStyleCheck.java @@ -0,0 +1,33 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class AwsCliS3PathStyleCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + Path awsConfig = Path.of(System.getProperty("user.home"), ".aws", "config"); + if (!Files.exists(awsConfig)) { + return CheckResult.ok("aws.cli.s3.pathstyle", "~/.aws/config not found — skipped"); + } + try { + String content = Files.readString(awsConfig); + if (content.contains("addressing_style") && content.contains("path")) { + return CheckResult.ok("aws.cli.s3.pathstyle", "S3 path-style addressing configured"); + } + return CheckResult.warn("aws.cli.s3.pathstyle", + "~/.aws/config missing 's3.addressing_style = path' — virtual-hosted S3 requests may fail", + "Add to ~/.aws/config:\n" + + " [default]\n" + + " s3 =\n" + + " addressing_style = path"); + } catch (IOException e) { + return CheckResult.warn("aws.cli.s3.pathstyle", "Could not read ~/.aws/config", null); + } + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java b/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java new file mode 100644 index 0000000..36dde6e --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/ContainerRunningCheck.java @@ -0,0 +1,30 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +public class ContainerRunningCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + try { + var info = new DockerClient().inspectContainer(container); + if (info.isEmpty()) { + return CheckResult.warn("container.running", + "Container '" + container + "' not found", + "floci start"); + } + String state = info.get().state(); + if ("running".equals(state)) { + return CheckResult.ok("container.running", "Container '" + container + "' is running"); + } + return CheckResult.fail("container.running", + "Container '" + container + "' exists but state is '" + state + "'", + "floci start (or 'floci stop && floci start' to restart)"); + } catch (DockerException e) { + return CheckResult.warn("container.running", "Could not inspect container: " + e.getMessage(), null); + } + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/DockerDaemonCheck.java b/src/main/java/io/floci/cli/doctor/checks/DockerDaemonCheck.java new file mode 100644 index 0000000..bd6a1c8 --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/DockerDaemonCheck.java @@ -0,0 +1,21 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.docker.DockerClient; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +public class DockerDaemonCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + DockerClient docker = new DockerClient(); + if (docker.isDaemonReachable()) { + return CheckResult.ok("docker.daemon", "Daemon reachable"); + } + String os = System.getProperty("os.name", "").toLowerCase(); + String fix = os.contains("mac") + ? "Start Docker Desktop from your Applications folder" + : "Start Docker: sudo systemctl start docker"; + return CheckResult.fail("docker.daemon", "Docker daemon not reachable", fix); + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/DockerInstalledCheck.java b/src/main/java/io/floci/cli/doctor/checks/DockerInstalledCheck.java new file mode 100644 index 0000000..5278cf3 --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/DockerInstalledCheck.java @@ -0,0 +1,23 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.docker.DockerClient; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +public class DockerInstalledCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + if (!DockerClient.isInstalled()) { + return CheckResult.fail("docker.installed", + "docker binary not found in PATH", + "Install Docker Desktop from https://docs.docker.com/get-docker/"); + } + try { + String version = new DockerClient().dockerVersion(); + return CheckResult.ok("docker.installed", "Docker " + version + " detected"); + } catch (Exception e) { + return CheckResult.ok("docker.installed", "Docker detected"); + } + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java b/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java new file mode 100644 index 0000000..15d2810 --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/DockerSocketCheck.java @@ -0,0 +1,27 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.docker.DockerClient; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +import java.nio.file.Files; +import java.nio.file.Path; + +public class DockerSocketCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + String socketPath = DockerClient.socketPath(); + String os = System.getProperty("os.name", "").toLowerCase(); + if (os.contains("win")) { + return CheckResult.ok("docker.socket", "Windows named pipe (" + socketPath + ")"); + } + if (Files.exists(Path.of(socketPath))) { + return CheckResult.ok("docker.socket", socketPath + " accessible"); + } + String fix = os.contains("mac") + ? "Open Docker Desktop — the socket is created when Docker Desktop is running" + : "sudo chmod 666 /var/run/docker.sock OR add your user to the docker group"; + return CheckResult.fail("docker.socket", socketPath + " not found or not accessible", fix); + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/DockerVersionCheck.java b/src/main/java/io/floci/cli/doctor/checks/DockerVersionCheck.java new file mode 100644 index 0000000..dc081a3 --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/DockerVersionCheck.java @@ -0,0 +1,38 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +public class DockerVersionCheck implements Check { + + private static final int MIN_MAJOR = 20; + private static final int MIN_MINOR = 10; + + @Override + public CheckResult run(String endpoint, String container) { + try { + String raw = new DockerClient().dockerVersion(); + if (meetsMinimum(raw)) { + return CheckResult.ok("docker.version", "Docker " + raw + " (>= 20.10)"); + } + return CheckResult.warn("docker.version", + "Docker " + raw + " is below the recommended minimum (20.10)", + "Upgrade Docker: https://docs.docker.com/engine/install/"); + } catch (DockerException e) { + return CheckResult.warn("docker.version", "Could not determine Docker version", null); + } + } + + public static boolean meetsMinimum(String version) { + try { + String[] parts = version.split("[.\\-]"); + int major = Integer.parseInt(parts[0]); + int minor = parts.length > 1 ? Integer.parseInt(parts[1]) : 0; + return major > MIN_MAJOR || (major == MIN_MAJOR && minor >= MIN_MINOR); + } catch (NumberFormatException e) { + return true; // assume ok if we can't parse + } + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java b/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java new file mode 100644 index 0000000..4fcedcd --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/EndpointReachableCheck.java @@ -0,0 +1,25 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; +import io.floci.cli.http.FlociHttpClient; + +public class EndpointReachableCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + FlociHttpClient client = new FlociHttpClient(endpoint); + if (client.isReachable()) { + try { + var health = client.health(); + return CheckResult.ok("endpoint.reachable", + endpoint + " is reachable (server v" + health.version() + ")"); + } catch (Exception e) { + return CheckResult.ok("endpoint.reachable", endpoint + " is reachable"); + } + } + return CheckResult.fail("endpoint.reachable", + "GET /_floci/health at " + endpoint + " did not return 200", + "Is Floci running? Try 'floci start'."); + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java b/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java new file mode 100644 index 0000000..0b24382 --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java @@ -0,0 +1,26 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +public class ImagePresentCheck implements Check { + + private static final String IMAGE = "floci/floci"; + + @Override + public CheckResult run(String endpoint, String container) { + try { + DockerClient docker = new DockerClient(); + if (docker.isImagePresent(IMAGE)) { + return CheckResult.ok("image.present", IMAGE + " image present locally"); + } + return CheckResult.fail("image.present", + IMAGE + " not pulled locally", + "floci start --pull always"); + } catch (DockerException e) { + return CheckResult.warn("image.present", "Could not check image presence: " + e.getMessage(), null); + } + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java new file mode 100644 index 0000000..a21553a --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java @@ -0,0 +1,76 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +public class ImageVersionCheck implements Check { + + private static final String IMAGE = "floci/floci"; + private static final String MIN_VERSION = "1.5.0"; + + @Override + public CheckResult run(String endpoint, String container) { + try { + DockerClient docker = new DockerClient(); + if (!docker.isImagePresent(IMAGE)) { + return CheckResult.warn("image.version", IMAGE + " not present — version cannot be checked", + "floci start --pull always"); + } + // Try reading version label from the image + String version = readImageLabel(docker, IMAGE); + if (version == null) { + return CheckResult.ok("image.version", "Image version unknown (no label); assuming compatible"); + } + if (meetsMinimum(version, MIN_VERSION)) { + return CheckResult.ok("image.version", "Server image version " + version + " (>= " + MIN_VERSION + ")"); + } + return CheckResult.warn("image.version", + "Server image version " + version + " is below minimum " + MIN_VERSION, + "docker pull " + IMAGE + ":latest"); + } catch (DockerException e) { + return CheckResult.warn("image.version", "Could not check image version: " + e.getMessage(), null); + } + } + + private String readImageLabel(DockerClient docker, String image) { + try { + String raw = runDockerInspect(image); + return raw.isBlank() ? null : raw.trim(); + } catch (Exception e) { + return null; + } + } + + private String runDockerInspect(String image) throws Exception { + Process p = new ProcessBuilder("docker", "inspect", "--format", + "{{index .Config.Labels \"org.opencontainers.image.version\"}}", image).start(); + String out = new String(p.getInputStream().readAllBytes()).trim(); + p.waitFor(); + return out; + } + + public static boolean meetsMinimum(String version, String minimum) { + try { + int[] v = parseSemVer(version); + int[] m = parseSemVer(minimum); + for (int i = 0; i < 3; i++) { + if (v[i] > m[i]) return true; + if (v[i] < m[i]) return false; + } + return true; + } catch (Exception e) { + return true; + } + } + + private static int[] parseSemVer(String v) { + String[] parts = v.replaceAll("[^0-9.]", "").split("\\.", 3); + int[] result = new int[3]; + for (int i = 0; i < Math.min(parts.length, 3); i++) { + try { result[i] = Integer.parseInt(parts[i]); } catch (NumberFormatException ignored) {} + } + return result; + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java b/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java new file mode 100644 index 0000000..3f3b5d5 --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/PortAvailableCheck.java @@ -0,0 +1,50 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.URI; + +public class PortAvailableCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + int port = extractPort(endpoint); + // If a Floci container is already listening on the port, that's fine + DockerClient docker = new DockerClient(); + try { + var info = docker.inspectContainer(container); + if (info.isPresent() && "running".equals(info.get().state())) { + return CheckResult.ok("port.available", "Port " + port + " in use by container '" + container + "' (expected)"); + } + } catch (DockerException ignored) {} + + if (isPortFree(port)) { + return CheckResult.ok("port.available", "Port " + port + " free"); + } + return CheckResult.fail("port.available", + "Port " + port + " is occupied by another process", + "Run 'lsof -i :" + port + "' to identify the process, or start Floci with --port "); + } + + private static boolean isPortFree(int port) { + try (ServerSocket s = new ServerSocket(port)) { + return true; + } catch (IOException e) { + return false; + } + } + + public static int extractPort(String endpoint) { + try { + int port = URI.create(endpoint).getPort(); + return port > 0 ? port : 4566; + } catch (Exception e) { + return 4566; + } + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/SdkGoEndpointCheck.java b/src/main/java/io/floci/cli/doctor/checks/SdkGoEndpointCheck.java new file mode 100644 index 0000000..18d8277 --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/SdkGoEndpointCheck.java @@ -0,0 +1,30 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class SdkGoEndpointCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + Path goMod = Path.of("go.mod"); + if (!Files.exists(goMod)) { + return CheckResult.ok("sdk.go.endpoint", "No go.mod in CWD — skipped"); + } + try { + String content = Files.readString(goMod); + if (!content.contains("aws-sdk-go-v2")) { + return CheckResult.ok("sdk.go.endpoint", "aws-sdk-go-v2 not in go.mod — skipped"); + } + return CheckResult.warn("sdk.go.endpoint", + "aws-sdk-go-v2 detected — use BaseEndpoint instead of deprecated EndpointResolver", + "See https://aws.github.io/aws-sdk-go-v2/docs/configuring-sdk/endpoints/ for migration guide"); + } catch (IOException e) { + return CheckResult.warn("sdk.go.endpoint", "Could not read go.mod", null); + } + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/SdkRustS3XmlCheck.java b/src/main/java/io/floci/cli/doctor/checks/SdkRustS3XmlCheck.java new file mode 100644 index 0000000..3c6a572 --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/SdkRustS3XmlCheck.java @@ -0,0 +1,30 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class SdkRustS3XmlCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + Path cargoToml = Path.of("Cargo.toml"); + if (!Files.exists(cargoToml)) { + return CheckResult.ok("sdk.rust.s3.xml", "No Cargo.toml in CWD — skipped"); + } + try { + String content = Files.readString(cargoToml); + if (!content.contains("aws-sdk-s3")) { + return CheckResult.ok("sdk.rust.s3.xml", "aws-sdk-s3 not in Cargo.toml — skipped"); + } + return CheckResult.warn("sdk.rust.s3.xml", + "aws-sdk-s3 detected — known issue: XmlDecodeError on S3 error responses", + "See https://github.com/floci-io/floci/issues/11 for workaround"); + } catch (IOException e) { + return CheckResult.warn("sdk.rust.s3.xml", "Could not read Cargo.toml", null); + } + } +} diff --git a/src/main/java/io/floci/cli/http/FlociException.java b/src/main/java/io/floci/cli/http/FlociException.java new file mode 100644 index 0000000..222d7b9 --- /dev/null +++ b/src/main/java/io/floci/cli/http/FlociException.java @@ -0,0 +1,7 @@ +package io.floci.cli.http; + +public class FlociException extends Exception { + public FlociException(String message) { + super(message); + } +} diff --git a/src/main/java/io/floci/cli/http/FlociHttpClient.java b/src/main/java/io/floci/cli/http/FlociHttpClient.java new file mode 100644 index 0000000..dc7d42b --- /dev/null +++ b/src/main/java/io/floci/cli/http/FlociHttpClient.java @@ -0,0 +1,160 @@ +package io.floci.cli.http; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.Map; +import java.util.Optional; + +public class FlociHttpClient { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final String endpoint; + private final HttpClient http; + + public FlociHttpClient(String endpoint) { + this.endpoint = endpoint.endsWith("/") ? endpoint.substring(0, endpoint.length() - 1) : endpoint; + this.http = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(5)) + .build(); + } + + public HealthInfo health() throws FlociException { + JsonNode node = getJson("/_floci/health"); + return new HealthInfo( + node.path("version").asText("unknown"), + node.path("edition").asText("community"), + node.path("services").isArray() + ? MAPPER.convertValue(node.path("services"), String[].class) + : new String[0]); + } + + public Optional healthOptional() { + try { + return Optional.of(health()); + } catch (Exception e) { + return Optional.empty(); + } + } + + public ServerInfo info() throws FlociException { + JsonNode node = getJson("/_floci/info"); + return new ServerInfo( + node.path("version").asText("unknown"), + node.path("edition").asText("community")); + } + + public InitState initState() throws FlociException { + JsonNode node = getJson("/_floci/init"); + JsonNode completed = node.path("completed"); + return new InitState( + completed.path("boot").asBoolean(), + completed.path("start").asBoolean(), + completed.path("ready").asBoolean(), + completed.path("shutdown").asBoolean()); + } + + public boolean isReachable() { + try { + HttpRequest req = HttpRequest.newBuilder() + .uri(URI.create(endpoint + "/_floci/health")) + .timeout(Duration.ofSeconds(3)) + .GET() + .build(); + HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.discarding()); + return resp.statusCode() == 200; + } catch (Exception e) { + return false; + } + } + + public Map postSnapshot(String name) throws FlociException { + return postJson("/_floci/snapshots/" + name, "{}"); + } + + public Map loadSnapshot(String name) throws FlociException { + return postJson("/_floci/snapshots/" + name + "/load", "{}"); + } + + public JsonNode listSnapshots() throws FlociException { + return getJson("/_floci/snapshots"); + } + + public void deleteSnapshot(String name) throws FlociException { + deleteRequest("/_floci/snapshots/" + name); + } + + private JsonNode getJson(String path) throws FlociException { + try { + HttpRequest req = HttpRequest.newBuilder() + .uri(URI.create(endpoint + path)) + .timeout(Duration.ofSeconds(10)) + .header("Accept", "application/json") + .GET() + .build(); + HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString()); + if (resp.statusCode() >= 400) { + throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path); + } + return MAPPER.readTree(resp.body()); + } catch (FlociException e) { + throw e; + } catch (java.net.ConnectException e) { + throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try 'floci status' or 'floci start'."); + } catch (Exception e) { + throw new FlociException("Request failed: " + e.getMessage()); + } + } + + @SuppressWarnings("unchecked") + private Map postJson(String path, String body) throws FlociException { + try { + HttpRequest req = HttpRequest.newBuilder() + .uri(URI.create(endpoint + path)) + .timeout(Duration.ofSeconds(30)) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body)) + .build(); + HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString()); + if (resp.statusCode() >= 400) { + throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path); + } + if (resp.body() == null || resp.body().isBlank()) return Map.of(); + return MAPPER.readValue(resp.body(), Map.class); + } catch (FlociException e) { + throw e; + } catch (java.net.ConnectException e) { + throw new FlociException("Connection refused at " + endpoint + ". Is Floci running? Try 'floci start'."); + } catch (Exception e) { + throw new FlociException("Request failed: " + e.getMessage()); + } + } + + private void deleteRequest(String path) throws FlociException { + try { + HttpRequest req = HttpRequest.newBuilder() + .uri(URI.create(endpoint + path)) + .timeout(Duration.ofSeconds(10)) + .DELETE() + .build(); + HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.discarding()); + if (resp.statusCode() >= 400) { + throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path); + } + } catch (FlociException e) { + throw e; + } catch (Exception e) { + throw new FlociException("Request failed: " + e.getMessage()); + } + } + + public record HealthInfo(String version, String edition, String[] services) {} + public record ServerInfo(String version, String edition) {} + public record InitState(boolean boot, boolean start, boolean ready, boolean shutdown) {} +} diff --git a/src/main/java/io/floci/cli/output/Ansi.java b/src/main/java/io/floci/cli/output/Ansi.java new file mode 100644 index 0000000..82a1be5 --- /dev/null +++ b/src/main/java/io/floci/cli/output/Ansi.java @@ -0,0 +1,36 @@ +package io.floci.cli.output; + +public final class Ansi { + + public static final String RESET = ""; + public static final String BOLD = ""; + public static final String GREEN = ""; + public static final String YELLOW = ""; + public static final String RED = ""; + public static final String CYAN = ""; + public static final String GRAY = ""; + public static final String GOLD = ""; + + private static boolean enabled = true; + + private Ansi() {} + + public static void disable() { + enabled = false; + } + + public static String apply(String code, String text) { + if (!enabled) return text; + return code + text + RESET; + } + + public static String green(String text) { return apply(GREEN, text); } + public static String yellow(String text) { return apply(YELLOW, text); } + public static String red(String text) { return apply(RED, text); } + public static String cyan(String text) { return apply(CYAN, text); } + public static String gray(String text) { return apply(GRAY, text); } + public static String bold(String text) { return apply(BOLD, text); } + public static String gold(String text) { return apply(GOLD, text); } + + public static boolean isEnabled() { return enabled; } +} diff --git a/src/main/java/io/floci/cli/output/OutputFormat.java b/src/main/java/io/floci/cli/output/OutputFormat.java new file mode 100644 index 0000000..dd26868 --- /dev/null +++ b/src/main/java/io/floci/cli/output/OutputFormat.java @@ -0,0 +1,5 @@ +package io.floci.cli.output; + +public enum OutputFormat { + text, json, yaml +} diff --git a/src/main/java/io/floci/cli/output/Printer.java b/src/main/java/io/floci/cli/output/Printer.java new file mode 100644 index 0000000..f403a1c --- /dev/null +++ b/src/main/java/io/floci/cli/output/Printer.java @@ -0,0 +1,62 @@ +package io.floci.cli.output; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; + +import java.io.PrintStream; + +public final class Printer { + + private static final ObjectMapper JSON = new ObjectMapper() + .enable(SerializationFeature.INDENT_OUTPUT); + + private static final ObjectMapper YAML = new ObjectMapper( + YAMLFactory.builder() + .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER) + .build()); + + private final PrintStream out; + private final PrintStream err; + private final OutputFormat format; + private final boolean quiet; + + public Printer(PrintStream out, PrintStream err, OutputFormat format, boolean quiet) { + this.out = out; + this.err = err; + this.format = format; + this.quiet = quiet; + } + + public void println(String line) { + if (!quiet) out.println(line); + } + + public void print(String text) { + if (!quiet) out.print(text); + } + + public void error(String message) { + err.println(Ansi.red("Error: ") + message); + } + + public void warn(String message) { + err.println(Ansi.yellow("Warning: ") + message); + } + + public void structured(Object data) { + try { + switch (format) { + case json -> out.println(JSON.writeValueAsString(data)); + case yaml -> out.print(YAML.writeValueAsString(data)); + default -> out.println(data.toString()); + } + } catch (Exception e) { + error("Failed to serialize output: " + e.getMessage()); + } + } + + public OutputFormat format() { return format; } + public boolean isQuiet() { return quiet; } +} diff --git a/src/main/resources/META-INF/native-image/io.floci/floci-cli/native-image.properties b/src/main/resources/META-INF/native-image/io.floci/floci-cli/native-image.properties new file mode 100644 index 0000000..939a40e --- /dev/null +++ b/src/main/resources/META-INF/native-image/io.floci/floci-cli/native-image.properties @@ -0,0 +1,4 @@ +Args = --enable-url-protocols=http,https \ + --no-fallback \ + -H:+ReportExceptionStackTraces \ + -H:IncludeResources=.*\\.properties diff --git a/src/main/resources/META-INF/native-image/io.floci/floci-cli/reflect-config.json b/src/main/resources/META-INF/native-image/io.floci/floci-cli/reflect-config.json new file mode 100644 index 0000000..fd6c4f1 --- /dev/null +++ b/src/main/resources/META-INF/native-image/io.floci/floci-cli/reflect-config.json @@ -0,0 +1,16 @@ +[ + { + "name": "io.floci.cli.config.Profile", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allDeclaredConstructors": true + }, + { + "name": "com.fasterxml.jackson.databind.ser.std.ToStringSerializer", + "allDeclaredMethods": true + }, + { + "name": "com.fasterxml.jackson.databind.deser.std.StringDeserializer", + "allDeclaredMethods": true + } +] diff --git a/src/main/resources/META-INF/native-image/io.floci/floci-cli/resource-config.json b/src/main/resources/META-INF/native-image/io.floci/floci-cli/resource-config.json new file mode 100644 index 0000000..f4da2d7 --- /dev/null +++ b/src/main/resources/META-INF/native-image/io.floci/floci-cli/resource-config.json @@ -0,0 +1,9 @@ +{ + "resources": { + "includes": [ + {"pattern": ".*\\.properties"}, + {"pattern": ".*\\.yaml"}, + {"pattern": ".*\\.yml"} + ] + } +} diff --git a/src/test/java/io/floci/cli/unit/DockerVersionCheckTest.java b/src/test/java/io/floci/cli/unit/DockerVersionCheckTest.java new file mode 100644 index 0000000..1658125 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/DockerVersionCheckTest.java @@ -0,0 +1,29 @@ +package io.floci.cli.unit; + +import io.floci.cli.doctor.checks.DockerVersionCheck; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.junit.jupiter.api.Assertions.*; + +class DockerVersionCheckTest { + + @ParameterizedTest + @CsvSource({ + "24.0.7, true", + "20.10.0, true", + "20.10, true", + "20.9.0, false", + "19.03.0, false", + "26.1.3, true" + }) + void testVersionParsing(String version, boolean expected) { + assertEquals(expected, DockerVersionCheck.meetsMinimum(version)); + } + + @Test + void testUnparseable() { + assertTrue(DockerVersionCheck.meetsMinimum("dev"), "unparseable version should pass"); + } +} diff --git a/src/test/java/io/floci/cli/unit/FlociCliParsingTest.java b/src/test/java/io/floci/cli/unit/FlociCliParsingTest.java new file mode 100644 index 0000000..201f317 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/FlociCliParsingTest.java @@ -0,0 +1,34 @@ +package io.floci.cli.unit; + +import io.floci.cli.FlociCli; +import org.junit.jupiter.api.Test; +import picocli.CommandLine; + +import static org.junit.jupiter.api.Assertions.*; + +class FlociCliParsingTest { + + @Test + void helpExitsZero() { + int code = new CommandLine(new FlociCli()).execute("--help"); + assertEquals(0, code); + } + + @Test + void versionFlag() { + int code = new CommandLine(new FlociCli()).execute("--version"); + assertEquals(0, code); + } + + @Test + void unknownCommandExitsNonZero() { + int code = new CommandLine(new FlociCli()).execute("nonexistent-subcommand"); + assertNotEquals(0, code); + } + + @Test + void subcommandHelpExitsZero() { + int code = new CommandLine(new FlociCli()).execute("doctor", "--help"); + assertEquals(0, code); + } +} diff --git a/src/test/java/io/floci/cli/unit/ImageVersionCheckTest.java b/src/test/java/io/floci/cli/unit/ImageVersionCheckTest.java new file mode 100644 index 0000000..035b577 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/ImageVersionCheckTest.java @@ -0,0 +1,22 @@ +package io.floci.cli.unit; + +import io.floci.cli.doctor.checks.ImageVersionCheck; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.junit.jupiter.api.Assertions.*; + +class ImageVersionCheckTest { + + @ParameterizedTest + @CsvSource({ + "1.5.0, 1.5.0, true", + "1.5.1, 1.5.0, true", + "2.0.0, 1.5.0, true", + "1.4.9, 1.5.0, false", + "1.5.0-SNAPSHOT, 1.5.0, true" + }) + void testSemVerComparison(String version, String minimum, boolean expected) { + assertEquals(expected, ImageVersionCheck.meetsMinimum(version, minimum)); + } +} diff --git a/src/test/java/io/floci/cli/unit/PortAvailableCheckTest.java b/src/test/java/io/floci/cli/unit/PortAvailableCheckTest.java new file mode 100644 index 0000000..1291174 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/PortAvailableCheckTest.java @@ -0,0 +1,16 @@ +package io.floci.cli.unit; + +import io.floci.cli.doctor.checks.PortAvailableCheck; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PortAvailableCheckTest { + + @Test + void testPortExtraction() { + assertEquals(4566, PortAvailableCheck.extractPort("http://localhost:4566")); + assertEquals(8080, PortAvailableCheck.extractPort("http://localhost:8080")); + assertEquals(4566, PortAvailableCheck.extractPort("invalid")); + } +} diff --git a/src/test/java/io/floci/cli/unit/WaitCommandParseTest.java b/src/test/java/io/floci/cli/unit/WaitCommandParseTest.java new file mode 100644 index 0000000..ce5e299 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/WaitCommandParseTest.java @@ -0,0 +1,28 @@ +package io.floci.cli.unit; + +import io.floci.cli.commands.WaitCommand; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.junit.jupiter.api.Assertions.*; + +class WaitCommandParseTest { + + @ParameterizedTest + @CsvSource({ + "30s, 30000", + "2m, 120000", + "1h, 3600000", + "500ms, 500", + "10, 10000" + }) + void testDurationParsing(String input, long expectedMillis) { + assertEquals(expectedMillis, WaitCommand.parseDuration(input.trim())); + } + + @Test + void testNullDuration() { + assertEquals(30_000, WaitCommand.parseDuration(null)); + } +}