diff --git a/.env b/.env new file mode 100644 index 0000000..1f2a01c --- /dev/null +++ b/.env @@ -0,0 +1,2 @@ +export CDK_TOKEN=a +export CDK_BASE_URL=http://localhost:8080/api diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..de0f009 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +pkg/** linguist-generated diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..2d837b6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,30 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG] My issue" +labels: triage +assignees: '' + +--- +Before submitting a bug report, please make sure that you are using the latest version of the CLI and read the [CONTRIBUTING.md](../../CONTRIBUTING.md#reporting-bugs) carefully. + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior and manifests used. + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** +- OS/Arch: [e.g. MacOS M2, Linux x86_64, Windows] +- Version of CLI : [e.g. 0.1.0] +- Version of Console : [e.g. 1.22.0] +- CLI source : [e.g. Release binaries, Docker, Local build] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..4541a26 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,22 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FEAT] Feature request" +labels: triage +assignees: '' + +--- + +Before submitting a feature request, please make sure that you are using the latest version of the CLI and read the [CONTRIBUTING.md](../../CONTRIBUTING.md#suggesting-enhancements) carefully. + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml new file mode 100644 index 0000000..a9a7eda --- /dev/null +++ b/.github/release-drafter.yml @@ -0,0 +1,68 @@ +name-template: '$RESOLVED_VERSION' +tag-template: '$RESOLVED_VERSION' + +version-resolver: + major: + labels: + - 'major' + minor: + labels: + - 'minor' + patch: + labels: + - 'patch' + default: minor + +categories: + - title: 'Features' + label: 'enhancement' + - title: 'Bug Fixes' + label: 'bug' + - title: 'Module updates' + label: 'module-upgrade' + - title: 'Dependency updates' + label: 'dependencies' + +exclude-labels: + - 'skip' + +autolabeler: + - label: 'module-upgrade' + title: + - '/\[Bump\].*\[version\]/' + branch: + - '/update_.+/' + - label: 'bug' + title: + - '/.*\[fix\].*/' + - label: 'patch' + title: + - '/.*\[fix\].*/' + - label: 'enhancement' + title: + - '/.*\[feat\].*/' + - label: 'minor' + title: + - '/.*\[feat\].*/' + - label: 'skip' + title: + - '/.*\[skip\].*/' + - label: 'major' + title: + - '/.*\[breaking\].*/' + +replacers: + - search: '/\[feat\]/g' + replace: '' + - search: '/\[fix\]/g' + replace: '' + - search: '/\[skip\]/g' + replace: '' + - search: '/\[breaking\]/g' + replace: '' + +template: | + # What's Changed + + $CHANGES + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f090ced --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,77 @@ +name: Build and Test + +on: + push: + branches: + - main + pull_request: + types: [opened, reopened, synchronize, labeled] + +env: + GO_VERSION: 1.22.0 + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.ref != format('refs/heads/{0}', 'main') }} + +jobs: + update_release_draft: + runs-on: ubuntu-latest + if: ${{ github.ref == format('refs/heads/{0}', 'main') }} + steps: + - uses: release-drafter/release-drafter@v6.0.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + unit-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: ${{ env.GO_VERSION }} + - name: go test + run: go test ./... + + integration-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: run test + run: ./test_final_exec.sh + + docker-test: + runs-on: ubuntu-latest + env: + IMAGE_NAME: "conduktor-ctl" + PLATFORMS: "linux/amd64,linux/arm64" + steps: + - uses: actions/checkout@v3 + - uses: docker/setup-buildx-action@v3 + with: + platforms: ${{ env.PLATFORMS }} + + - uses: docker/setup-qemu-action@v3 + with: + platforms: ${{ env.PLATFORMS }} + + - uses: docker/metadata-action@v4 + id: docker_meta + with: + images: conduktor/${{ env.IMAGE_NAME }} + tags: type=sha + + - name: Build ${{ env.IMAGE_NAME }} + id: build + uses: docker/build-push-action@v5 + with: + context: . + platforms: ${{ env.PLATFORMS }} + push: false + file: docker/Dockerfile + tags: ${{ steps.docker_meta.outputs.tags }} + labels: ${{ steps.docker_meta.outputs.labels }} + github-token: ${{ secrets.GITHUB_TOKEN }} + build-args: | + hash=${{ github.sha }} + version=${{ github.ref_name }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..946f3ec --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,118 @@ +name: Release +run-name: Release ${{ github.event.release.tag_name }} by ${{ github.actor }} + +on: + release: + types: [published] + +env: + GO_VERSION: 1.22.0 + +jobs: + unit-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: ${{ env.GO_VERSION }} + - name: go test + run: go test ./... + + integration-test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: run test + run: ./test_final_exec.sh + + build-exec: + needs: [unit-test, integration-test] + runs-on: ubuntu-latest + strategy: + matrix: + # build and publish in parallel: linux/386, linux/amd64, linux/arm64, windows/386, windows/amd64, darwin/amd64, darwin/arm64 + goos: [linux, windows, darwin] + goarch: [amd64, arm64] + steps: + - uses: actions/checkout@v4 + - uses: wangyoucao577/go-release-action@v1.48 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + goos: ${{ matrix.goos }} + goarch: ${{ matrix.goarch }} + goversion: "${{ env.GO_VERSION }}" + ldflags: -X 'github.com/conduktor/ctl/cmd.version=${{ github.event.release.tag_name }}' -X 'github.com/conduktor/ctl/cmd.hash=${{ github.sha }}' + project_path: "./" + binary_name: "conduktor" + + build-docker: + name: Build and publish conduktor-ctl image + needs: [unit-test, integration-test] + runs-on: ubuntu-latest + env: + IMAGE_NAME: "conduktor-ctl" + LABEL_IMAGE_TITLE: "Conduktor ctl" + LABEL_IMAGE_DESCRIPTION: "Conduktor command line tools" + LABEL_IMAGE_AUTHORS: "Conduktor " + LABEL_IMAGE_URL: "https://hub.docker.com/r/conduktor/conduktor-ctl" + LABEL_IMAGE_DOCUMENTATION: "https://docs.conduktor.io/conduktor" + LABEL_IMAGE_VENDOR: "Conduktor.io" + LABEL_IMAGE_LICENSE: "Apache-2.0" + PLATFORMS: "linux/amd64,linux/arm64" + steps: + - uses: actions/checkout@v3 + + - name: "Set latest" + shell: bash + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + latest_release_version=$(gh release view -R ${{ github.repository }} --json tagName -q .tagName) + is_latest=$(test "${{ github.event.release.tag_name }}" == "${latest_release_version}" && echo true || echo false) + echo "IS_LATEST=${is_latest}" >> $GITHUB_ENV + + - uses: docker/setup-buildx-action@v3 + with: + platforms: ${{ env.PLATFORMS }} + + - uses: docker/setup-qemu-action@v3 + with: + platforms: ${{ env.PLATFORMS }} + + - uses: docker/login-action@v2 + with: + username: ${{ secrets.CONDUKTORBOT_DOCKER_HUB_USERNAME }} + password: ${{ secrets.CONDUKTORBOT_DOCKER_HUB_PAT }} + + - uses: docker/metadata-action@v4 + id: docker_meta + with: + images: docker.io/conduktor/${{ env.IMAGE_NAME }} + tags: | + type=raw,value=${{ github.event.release.tag_name }} + type=raw,value=latest,enable=${{ env.IS_LATEST }} + labels: | + org.opencontainers.image.title=${{ env.LABEL_IMAGE_TITLE }} + org.opencontainers.image.description=${{ env.LABEL_IMAGE_DESCRIPTION }} + org.opencontainers.image.authors=${{ env.LABEL_IMAGE_AUTHORS }} + org.opencontainers.image.documentation=${{ env.LABEL_IMAGE_DOCUMENTATION }} + org.opencontainers.image.vendor=${{ env.LABEL_IMAGE_VENDOR }} + org.opencontainers.image.licenses=${{ env.LABEL_IMAGE_LICENSE }} + org.opencontainers.image.url=${{ env.LABEL_IMAGE_URL }} + org.opencontainers.image.version=${{ github.event.release.tag_name }} + + - name: Build ${{ env.IMAGE_NAME }} + id: build + uses: docker/build-push-action@v5 + with: + context: . + platforms: ${{ env.PLATFORMS }} + push: ${{ github.event.release.prerelease == false }} # only push on final release + file: docker/Dockerfile + tags: ${{ steps.docker_meta.outputs.tags }} + labels: ${{ steps.docker_meta.outputs.labels }} + github-token: ${{ secrets.GITHUB_TOKEN }} + build-args: | + hash=${{ github.sha }} + version=${{ github.event.release.tag_name }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..374e3f7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,254 @@ +# Binaries +ctl +conduktor + +ctl.iml +# Created by https://www.toptal.com/developers/gitignore/api/go,intellij,visualstudiocode,vim,linux,macos,windows +# Edit at https://www.toptal.com/developers/gitignore?templates=go,intellij,visualstudiocode,vim,linux,macos,windows + +### Go ### +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# Go workspace file +go.work + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# End of https://www.toptal.com/developers/gitignore/api/go,intellij,visualstudiocode,vim,linux,macos,windows diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..fa4a4fc --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,132 @@ + +# Contributing to conduktor-ctl + +First off, thanks for taking the time to contribute! ❤️ + +All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉 + +> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about: +> - Star the project +> - Tweet about it +> - Refer this project in your project's readme +> - Mention the project at local meetups and tell your friends/colleagues + + +## Table of Contents + +- [I Have a Question](#i-have-a-question) +- [I Want To Contribute](#i-want-to-contribute) +- [Reporting Bugs](#reporting-bugs) +- [Suggesting Enhancements](#suggesting-enhancements) +- [Your First Code Contribution](#your-first-code-contribution) +- [Improving The Documentation](#improving-the-documentation) +- [Styleguides](#styleguides) +- [Commit Messages](#commit-messages) +- [Join The Project Team](#join-the-project-team) + + + +## I Have a Question + +> If you want to ask a question, we assume that you have read the available [Documentation](https://docs.conduktor.io/). + +Before you ask a question, it is best to search for existing [Issues](https://github.com/conduktor/ctl/issues) that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first. + +If you then still feel the need to ask a question and need clarification, we recommend the following: + +- Open an [Issue](https://github.com/conduktor/ctl/issues/new). +- Provide as much context as you can about what you're running into. +- Provide project and platform versions (go, docker, etc), depending on what seems relevant. + +We will then take care of the issue as soon as possible. + +## I Want To Contribute + +### Reporting Bugs + + +#### Before Submitting a Bug Report + +A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible. + +- Make sure that you are using the latest version. +- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation](https://docs.conduktor.io/). If you are looking for support, you might want to check [this section](#i-have-a-question)). +- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/conduktor/ctlissues?q=label%3Abug). +- Collect information about the bug: + - Version of the conduktor-ctl you are using + - Version of Conduktor Console you are targeting + - Stack trace (Traceback) + - OS, Platform and Version (Windows, Linux, macOS, x86, ARM) + - Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant. + - Possibly your input and the output + - Can you reliably reproduce the issue? And can you also reproduce it with older versions? + + +#### How Do I Submit a Good Bug Report? + +> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to [security@conduktor.io](). + +We use GitHub issues to track bugs and errors. If you run into an issue with the project: + +- Open an [Issue](https://github.com/conduktor/ctl/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.) +- Explain the behavior you would expect and the actual behavior. +- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case. +- Provide the information you collected in the previous section. + +You can also contact us at [support@conduktor.io]() if you need help with the issue. + + +### Suggesting Enhancements + +This section guides you through submitting an enhancement suggestion for conduktor-ctl, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions. + + +#### Before Submitting an Enhancement + +- Make sure that you are using the latest version. +- Read the [documentation](https://docs.conduktor.io/) carefully and find out if the functionality is already covered, maybe by an individual configuration. +- Perform a [search](https://github.com/conduktor/ctl/issues) to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one. +- Search for similar suggestions in the [Conduktor Roadmap](https://product.conduktor.help/) and Submit an idea if it is not already there. +- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset. + + +#### How Do I Submit a Good Enhancement Suggestion? + +Enhancement suggestions are tracked as [GitHub issues](https://github.com/conduktor/ctl/issues) or in [Conduktor Roadmap](https://product.conduktor.help/). + +- Use a **clear and descriptive title** for the issue to identify the suggestion. +- Provide a **step-by-step description of the suggested enhancement** in as many details as possible. +- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you. +- **Explain why this enhancement would be useful** to most conduktor-ctl users. You may also want to point out the other projects that solved it better and which could serve as inspiration. + +### Your First Code Contribution + +To run the project locally, you will need Go 1.22+ installed and configured on your machine. +Here some useful commands to get you started: + +Build and run the project locally: +``` +read CDK_TOKEN +export CDK_TOKEN +export CDK_BASE_URL=http://localhost:8080 +go run . +``` + +Run unit tests: +``` +go test ./... +``` + +Run integration tests: +``` +./test_final_exec.sh +``` + +Don't forget to run the tests to make sure everything is working as expected before submitting a pull request. + +## Styleguides +### Commit Messages +Use explicit commit message that follows the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification. This convention makes it easier to understand the changes in a project and to automate the versioning process. + + + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c319da3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..129fc81 --- /dev/null +++ b/README.md @@ -0,0 +1,104 @@ +# Conduktor ctl +![Release](https://img.shields.io/github/v/release/conduktor/ctl?sort=semver&logo=github) +![License](https://img.shields.io/github/license/conduktor/ctl) +[![Roadmap](https://img.shields.io/badge/Roadmap-click%20here-blueviolet)](https://product.conduktor.help/tabs/1-in-development) +[![twitter](https://img.shields.io/twitter/follow/getconduktor.svg?style=social)](https://twitter.com/getconduktor) + +This repository contain Conduktor CLI source code. +Conduktor CLI is a command line tool to interact with Conduktor Console. +It is strongly inspired by Kubernetes kubectl CLI tool and reuse some of it's concepts. + + +## How to install + +### From binaries (Linux, MacOS, Windows) + +Look for assets of the last release at https://github.com/conduktor/ctl/releases + +### Using Docker image +How to get the latest docker image: +``` +docker pull conduktor/conduktor-ctl:latest +``` + +### From source +You will need Go 1.22+ installed and configured on your machine. + +To build simply run +``` +go build -o conduktor . +``` +You will find the `conduktor` binary at the root of the project. + +## Usage + +To run the CLI you will need to provide the Conduktor Console URL and an API access token. + +### Configure + +To use Conduktor CLI, you need to define 2 environment variables: +- The URL of Conduktor Console +- Your API token (either a User Token or Application Token). You can generate an API token on `/settings/public-api-keys` page of your Console instance. +````yaml +CDK_BASE_URL=http://localhost:8080 +CDK_TOKEN= +```` + +### Commands Usage +```` +Usage: + conduktor [command] +Available Commands: + apply Upsert a resource on Conduktor + completion Generate the autocompletion script for the specified shell + delete Delete resource of a given kind and name + get Get resource of a given kind + help Help about any command + version Display the version of conduktor +Flags: + -h, --help Help for conduktor + -v, --verbose Show more information for debugging +```` + +You can find more usage details on our [documentation](https://docs.conduktor.io/platform/reference/cli-reference/) + + +#### How to use behind teleport +If you are using Conduktor behind a teleport proxy, you will need to provide the certificate and key to the CLI using `CDK_CERT` and `CDK_KEY` environment variables. + +First login to your teleport proxy, for example: +``` +tsh login --proxy="$TELEPORT_SERVER" --auth="$TELEPORT_AUTH_METHOD" +tsh apps login console +export CDK_CERT=$(tsh apps config --format=cert) +export CDK_KEY=$(tsh apps config --format=key) +conduktor get application +``` + +### Development + +How to run: +``` +read CDK_TOKEN +export CDK_TOKEN +export CDK_BASE_URL=http://localhost:8080 +go run . +``` + +How to run unit test: +``` +go test ./... +``` + +How to run integration test: +``` +./test_final_exec.sh +``` + +## Contributing + +Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us. + +## License + +This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details. diff --git a/client/api_error.go b/client/api_error.go new file mode 100644 index 0000000..305e685 --- /dev/null +++ b/client/api_error.go @@ -0,0 +1,14 @@ +package client + +type ApiError struct { + Title string + Msg string +} + +func (e *ApiError) String() string { + if e.Msg == "" { + return e.Title + } else { + return e.Msg + } +} diff --git a/client/client.go b/client/client.go new file mode 100644 index 0000000..1dab5b4 --- /dev/null +++ b/client/client.go @@ -0,0 +1,169 @@ +package client + +import ( + "crypto/tls" + "encoding/json" + "fmt" + "github.com/conduktor/ctl/printutils" + "github.com/conduktor/ctl/resource" + "github.com/conduktor/ctl/utils" + "github.com/go-resty/resty/v2" + "os" + "strings" +) + +type Client struct { + token string + baseUrl string + client *resty.Client +} + +func Make(token string, baseUrl string, debug bool, key, cert string) (*Client, error) { + restyClient := resty.New().SetDebug(debug).SetHeader("Authorization", "Bearer "+token) + if (key == "" && cert != "") || (key != "" && cert == "") { + return nil, fmt.Errorf("key and cert must be provided together") + } else if key != "" && cert != "" { + certificate, err := tls.LoadX509KeyPair(cert, key) + restyClient.SetCertificates(certificate) + if err != nil { + return nil, err + } + } + + return &Client{ + token: token, + baseUrl: baseUrl, + client: restyClient, + }, nil +} + +func MakeFromEnv() *Client { + token := os.Getenv("CDK_TOKEN") + if token == "" { + fmt.Fprintln(os.Stderr, "Please set CDK_TOKEN") + os.Exit(1) + } + baseUrl := os.Getenv("CDK_BASE_URL") + if baseUrl == "" { + fmt.Fprintln(os.Stderr, "Please set CDK_BASE_URL") + os.Exit(2) + } + debug := strings.ToLower(os.Getenv("CDK_DEBUG")) == "true" + key := os.Getenv("CDK_KEY") + cert := os.Getenv("CDK_CERT") + + client, err := Make(token, baseUrl, debug, key, cert) + if err != nil { + fmt.Fprintf(os.Stderr, "Cannot create client: %s", err) + os.Exit(3) + } + insecure := strings.ToLower(os.Getenv("CDK_INSECURE")) == "true" + if insecure { + client.IgnoreUntrustedCertificate() + } + return client +} + +type UpsertResponse struct { + UpsertResult string +} + +func (c *Client) IgnoreUntrustedCertificate() { + c.client.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) +} + +func extractApiError(resp *resty.Response) string { + var apiError ApiError + jsonError := json.Unmarshal(resp.Body(), &apiError) + if jsonError != nil { + return resp.String() + } else { + return apiError.String() + } +} + +func (client *Client) publicV1Url() string { + return client.baseUrl + "/public/v1" +} + +func (client *Client) ActivateDebug() { + client.client.SetDebug(true) +} + +func (client *Client) Apply(resource *resource.Resource, dryMode bool) (string, error) { + url := client.publicV1Url() + "/" + utils.UpperCamelToKebab(resource.Kind) + builder := client.client.R().SetBody(resource.Json) + if dryMode { + builder = builder.SetQueryParam("dryMode", "true") + } + resp, err := builder.Put(url) + if err != nil { + return "", err + } else if resp.IsError() { + return "", fmt.Errorf(extractApiError(resp)) + } + bodyBytes := resp.Body() + var upsertResponse UpsertResponse + err = json.Unmarshal(bodyBytes, &upsertResponse) + //in case backend format change (not json string anymore). Let not fail the client for that + if err != nil { + return resp.String(), nil + } + return upsertResponse.UpsertResult, nil +} + +func printResponseAsYaml(bytes []byte) error { + var data interface{} + err := json.Unmarshal(bytes, &data) + if err != nil { + return err + } + return printutils.PrintResourceLikeYamlFile(os.Stdout, data) +} + +func (client *Client) Get(kind string) error { + url := client.publicV1Url() + "/" + utils.UpperCamelToKebab(kind) + resp, err := client.client.R().Get(url) + if err != nil { + return err + } else if resp.IsError() { + return fmt.Errorf(extractApiError(resp)) + } + return printResponseAsYaml(resp.Body()) +} + +func (client *Client) Describe(kind, name string) error { + url := client.publicV1Url() + "/" + utils.UpperCamelToKebab(kind) + "/" + name + resp, err := client.client.R().Get(url) + if err != nil { + return err + } else if resp.IsError() { + return fmt.Errorf("error describing resources %s/%s, got status code: %d:\n %s", kind, name, resp.StatusCode(), string(resp.Body())) + } + return printResponseAsYaml(resp.Body()) +} + +func (client *Client) Delete(kind, name string) error { + url := client.publicV1Url() + "/" + utils.UpperCamelToKebab(kind) + "/" + name + resp, err := client.client.R().Delete(url) + if err != nil { + return err + } else if resp.IsError() { + return fmt.Errorf(extractApiError(resp)) + } else { + fmt.Printf("%s/%s deleted\n", kind, name) + } + + return err +} + +func (client *Client) GetOpenApi() ([]byte, error) { + url := client.baseUrl + "/public/docs/docs.yaml" + resp, err := client.client.R().Get(url) + if err != nil { + return nil, err + } else if resp.IsError() { + return nil, fmt.Errorf(resp.String()) + } + return resp.Body(), nil +} diff --git a/client/client_test.go b/client/client_test.go new file mode 100644 index 0000000..c36a986 --- /dev/null +++ b/client/client_test.go @@ -0,0 +1,362 @@ +package client + +import ( + "testing" + + "github.com/conduktor/ctl/resource" + "github.com/jarcoal/httpmock" +) + +func TestApplyShouldWork(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder := httpmock.NewStringResponder(200, `{"upsertResult": "NotChanged"}`) + + topic := resource.Resource{ + Json: []byte(`{"yolo": "data"}`), + Kind: "Topic", + Name: "toto", + Version: "v1", + } + + httpmock.RegisterMatcherResponderWithQuery( + "PUT", + "http://baseUrl/public/v1/topic", + nil, + httpmock.HeaderIs("Authorization", "Bearer "+token). + And(httpmock.BodyContainsBytes(topic.Json)), + responder, + ) + + body, err := client.Apply(&topic, false) + if err != nil { + t.Error(err) + } + if body != "NotChanged" { + t.Errorf("Bad result expected NotChanged got: %s", body) + } +} + +func TestApplyWithDryModeShouldWork(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder := httpmock.NewStringResponder(200, `{"upsertResult": "NotChanged"}`) + + topic := resource.Resource{ + Json: []byte(`{"yolo": "data"}`), + Kind: "Topic", + Name: "toto", + Version: "v1", + } + + httpmock.RegisterMatcherResponderWithQuery( + "PUT", + "http://baseUrl/public/v1/topic", + "dryMode=true", + httpmock.HeaderIs("Authorization", "Bearer "+token). + And(httpmock.BodyContainsBytes(topic.Json)), + responder, + ) + + body, err := client.Apply(&topic, true) + if err != nil { + t.Error(err) + } + if body != "NotChanged" { + t.Errorf("Bad result expected NotChanged got: %s", body) + } +} + +func TestApplyShouldFailIfNo2xx(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder, err := httpmock.NewJsonResponder(400, "") + if err != nil { + panic(err) + } + + topic := resource.Resource{ + Json: []byte(`{"yolo": "data"}`), + Kind: "Topic", + Name: "toto", + Version: "v1", + } + + httpmock.RegisterMatcherResponderWithQuery( + "PUT", + "http://baseUrl/public/v1/topic", + nil, + httpmock.HeaderIs("Authorization", "Bearer "+token). + And(httpmock.BodyContainsBytes(topic.Json)), + responder, + ) + + _, err = client.Apply(&topic, false) + if err == nil { + t.Failed() + } +} + +func TestGetShouldWork(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder, err := httpmock.NewJsonResponder(200, "[]") + if err != nil { + panic(err) + } + + httpmock.RegisterMatcherResponderWithQuery( + "GET", + "http://baseUrl/public/v1/application", + nil, + httpmock.HeaderIs("Authorization", "Bearer "+token), + responder, + ) + + err = client.Get("Application") + if err != nil { + t.Error(err) + } +} + +func TestGetShouldApplyCaseTransformation(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder, err := httpmock.NewJsonResponder(200, "[]") + if err != nil { + panic(err) + } + + httpmock.RegisterMatcherResponderWithQuery( + "GET", + "http://baseUrl/public/v1/application-instance", + nil, + httpmock.HeaderIs("Authorization", "Bearer "+token), + responder, + ) + + err = client.Get("ApplicationInstance") + if err != nil { + t.Error(err) + } +} + +func TestGetShouldKeepCase(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder, err := httpmock.NewJsonResponder(200, "[]") + if err != nil { + panic(err) + } + + httpmock.RegisterMatcherResponderWithQuery( + "GET", + "http://baseUrl/public/v1/application-instance", + nil, + httpmock.HeaderIs("Authorization", "Bearer "+token), + responder, + ) + + err = client.Get("application-instance") + if err != nil { + t.Error(err) + } +} + +func TestGetShouldFailIfN2xx(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder, err := httpmock.NewJsonResponder(404, "") + if err != nil { + panic(err) + } + + httpmock.RegisterMatcherResponderWithQuery( + "GET", + "http://baseUrl/public/v1/application", + nil, + httpmock.HeaderIs("Authorization", "Bearer "+token), + responder, + ) + + err = client.Get("Application") + if err == nil { + t.Failed() + } +} + +func TestDescribeShouldWork(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder, err := httpmock.NewJsonResponder(200, "[]") + if err != nil { + panic(err) + } + + httpmock.RegisterMatcherResponderWithQuery( + "GET", + "http://baseUrl/public/v1/application/yo", + nil, + httpmock.HeaderIs("Authorization", "Bearer "+token), + responder, + ) + + err = client.Describe("Application", "yo") + if err != nil { + t.Error(err) + } +} + +func TestDescribeShouldFailIfNo2xx(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl/api" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder, err := httpmock.NewJsonResponder(500, "[]") + if err != nil { + panic(err) + } + + httpmock.RegisterMatcherResponderWithQuery( + "GET", + "http://baseUrl/public/v1/application/yo", + nil, + httpmock.HeaderIs("Authorization", "Bearer "+token), + responder, + ) + + err = client.Describe("Application", "yo") + if err == nil { + t.Failed() + } +} + +func TestDeleteShouldWork(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder, err := httpmock.NewJsonResponder(200, "[]") + if err != nil { + panic(err) + } + + httpmock.RegisterMatcherResponderWithQuery( + "DELETE", + "http://baseUrl/public/v1/application/yo", + nil, + httpmock.HeaderIs("Authorization", "Bearer "+token), + responder, + ) + + err = client.Delete("Application", "yo") + if err != nil { + t.Error(err) + } +} +func TestDeleteShouldFailOnNot2XX(t *testing.T) { + defer httpmock.Reset() + baseUrl := "http://baseUrl" + token := "aToken" + client, err := Make(token, baseUrl, false, "", "") + if err != nil { + panic(err) + } + httpmock.ActivateNonDefault( + client.client.GetClient(), + ) + responder, err := httpmock.NewJsonResponder(404, "[]") + if err != nil { + panic(err) + } + + httpmock.RegisterMatcherResponderWithQuery( + "DELETE", + "http://baseUrl/public/v1/api/application/yo", + nil, + httpmock.HeaderIs("Authorization", "Bearer "+token), + responder, + ) + + err = client.Delete("Application", "yo") + if err == nil { + t.Fail() + } +} diff --git a/cmd/apply.go b/cmd/apply.go new file mode 100644 index 0000000..50f729a --- /dev/null +++ b/cmd/apply.go @@ -0,0 +1,73 @@ +package cmd + +import ( + "fmt" + "github.com/conduktor/ctl/resource" + "github.com/spf13/cobra" + "os" +) + +var filePath *[]string +var dryRun *bool + +// applyCmd represents the apply command +var applyCmd = &cobra.Command{ + Use: "apply", + Short: "upsert a resource on Conduktor", + Long: ``, + Run: func(cmd *cobra.Command, args []string) { + var resources = make([]resource.Resource, 0) + for _, path := range *filePath { + r, err := resourceForPath(path) + if err != nil { + fmt.Fprintf(os.Stderr, "%s\n", err) + os.Exit(1) + } + resources = append(resources, r...) + } + for _, resource := range resources { + upsertResult, err := apiClient.Apply(&resource, *dryRun) + if err != nil { + fmt.Fprintf(os.Stderr, "Could not apply resource %s/%s: %s\n", resource.Kind, resource.Name, err) + os.Exit(1) + } else { + fmt.Printf("%s/%s: %s\n", resource.Kind, resource.Name, upsertResult) + } + } + }, +} + +func resourceForPath(path string) ([]resource.Resource, error) { + directory, err := isDirectory(path) + if err != nil { + fmt.Fprintf(os.Stderr, "%s\n", err) + os.Exit(1) + } + if directory { + return resource.FromFolder(path) + } else { + return resource.FromFile(path) + } +} + +func initApply() { + rootCmd.AddCommand(applyCmd) + + // Here you will define your flags and configuration settings. + filePath = applyCmd. + PersistentFlags().StringArrayP("file", "f", make([]string, 0, 0), "Specify the files to apply") + + dryRun = applyCmd. + PersistentFlags().Bool("dry-run", false, "Don't really apply change but check on backend the effect if applied") + + applyCmd.MarkPersistentFlagRequired("file") +} + +func isDirectory(path string) (bool, error) { + fileInfo, err := os.Stat(path) + if err != nil { + return false, err + } + + return fileInfo.IsDir(), err +} diff --git a/cmd/delete.go b/cmd/delete.go new file mode 100644 index 0000000..6eaacdb --- /dev/null +++ b/cmd/delete.go @@ -0,0 +1,26 @@ +package cmd + +import ( + "fmt" + "github.com/spf13/cobra" + "os" +) + +// applyCmd represents the apply command +var deleteCmd = &cobra.Command{ + Use: "delete", + Short: "delete resource of a given kind and name", + Long: ``, + Args: cobra.ExactArgs(2), + Run: func(cmd *cobra.Command, args []string) { + err := apiClient.Delete(args[0], args[1]) + if err != nil { + fmt.Fprintf(os.Stderr, "%s\n", err) + os.Exit(1) + } + }, +} + +func initDelete() { + rootCmd.AddCommand(deleteCmd) +} diff --git a/cmd/get.go b/cmd/get.go new file mode 100644 index 0000000..065024e --- /dev/null +++ b/cmd/get.go @@ -0,0 +1,77 @@ +package cmd + +import ( + "fmt" + "github.com/spf13/cobra" + "os" +) + +var getCmd = &cobra.Command{ + Use: "get", + Short: "get resource of a given kind", + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, args []string) { + // Root command does nothing + cmd.Help() + os.Exit(1) + }, +} + +var getCmdWhenNoSchema = &cobra.Command{ + Use: "get kind [name]", + Short: "get resource of a given kind", + Long: `If name not provided it will list all resource. For example: +conduktor get application +will list all applications. Whereas: +conduktor get application myapp +will describe the application myapp`, + Args: cobra.MatchAll(cobra.MinimumNArgs(1), cobra.MaximumNArgs(2)), + Run: func(cmd *cobra.Command, args []string) { + var err error + if len(args) == 1 { + err = apiClient.Get(args[0]) + } else if len(args) == 2 { + err = apiClient.Describe(args[0], args[1]) + } + if err != nil { + fmt.Fprintf(os.Stderr, "%s\n", err) + os.Exit(1) + } + }, +} + +func initGet() { + if schemaClient == nil { + rootCmd.AddCommand(getCmdWhenNoSchema) + return + } + tags, err := schemaClient.GetKind() + if err != nil { + fmt.Fprintf(os.Stderr, "Could not load kind from openapi: %s\n", err) + rootCmd.AddCommand(getCmdWhenNoSchema) + return + } + rootCmd.AddCommand(getCmd) + + for _, tag := range tags { + tagCmd := &cobra.Command{ + Use: fmt.Sprintf("%s [name]", tag), + Short: "get resource of kind " + tag, + Args: cobra.MatchAll(cobra.MaximumNArgs(1)), + Long: `If name not provided it will list all resource`, + Run: func(cmd *cobra.Command, args []string) { + var err error + if len(args) == 0 { + err = apiClient.Get(tag) + } else if len(args) == 1 { + err = apiClient.Describe(tag, args[0]) + } + if err != nil { + fmt.Fprintf(os.Stderr, "%s\n", err) + os.Exit(1) + } + }, + } + getCmd.AddCommand(tagCmd) + } +} diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 0000000..1025e7a --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,62 @@ +/* +Copyright © 2024 NAME HERE +*/ +package cmd + +import ( + "fmt" + "github.com/conduktor/ctl/client" + "github.com/conduktor/ctl/schema" + "github.com/spf13/cobra" + "os" +) + +var debug *bool +var key *string +var cert *string +var apiClient *client.Client +var schemaClient *schema.Schema = nil + +// rootCmd represents the base command when called without any subcommands +var rootCmd = &cobra.Command{ + Use: "conduktor", + Short: "command line tools for conduktor", + Long: `You need to define the CDK_TOKEN and CDK_BASE_URL environment variables to use this tool. +You can also use the CDK_KEY,CDK_CERT instead of --key and --cert flags to use a certificate for tls authentication. +If you have an untrusted certificate you can use the CDK_INSECURE=true variable to disable tls verification`, + PersistentPreRun: func(cmd *cobra.Command, args []string) { + if *debug { + apiClient.ActivateDebug() + } + }, + Run: func(cmd *cobra.Command, args []string) { + cmd.Help() + os.Exit(1) + }, +} + +// Execute adds all child commands to the root command and sets flags appropriately. +// This is called by main.main(). It only needs to happen once to the rootCmd. +func Execute() { + err := rootCmd.Execute() + if err != nil { + os.Exit(1) + } +} + +func init() { + apiClient = client.MakeFromEnv() + openApi, err := apiClient.GetOpenApi() + if err == nil { + schemaClient, err = schema.New(openApi) + } + if err != nil { + fmt.Fprintf(os.Stderr, "Could not load server openapi: %s\n", err) + } + debug = rootCmd.PersistentFlags().BoolP("verbose", "v", false, "Show more information for debugging") + key = rootCmd.PersistentFlags().String("key", "", "Set pem key for certificate authentication (useful for teleport)") + cert = rootCmd.PersistentFlags().String("cert", "", "Set pem cert for certificate authentication (useful for teleport)") + initGet() + initDelete() + initApply() +} diff --git a/cmd/version.go b/cmd/version.go new file mode 100644 index 0000000..6bfb98d --- /dev/null +++ b/cmd/version.go @@ -0,0 +1,23 @@ +package cmd + +import ( + "fmt" + "github.com/spf13/cobra" +) + +var version = "unknown" +var hash = "unknown" + +// versionCmd represents the apply command +var versionCmd = &cobra.Command{ + Use: "version", + Short: "display the version of conduktor", + Long: ``, + Run: func(cmd *cobra.Command, args []string) { + fmt.Printf("Version: %s\nHash: %s\n", version, hash) + }, +} + +func init() { + rootCmd.AddCommand(versionCmd) +} diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..d4b1899 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,13 @@ +FROM golang:1.22 +ARG version=unknown +ARG hash=unknown +WORKDIR /app +COPY go.mod go.sum ./ +RUN go mod download +COPY . ./ +RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-X 'github.com/conduktor/ctl/cmd.version=$version' -X 'github.com/conduktor/ctl/cmd.hash=$hash'" -o /conduktor . && rm -rf /app +CMD ["/bin/conduktor"] + +FROM scratch +COPY --from=0 /conduktor /bin/conduktor +ENTRYPOINT ["/bin/conduktor"] diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 0000000..e91f66b --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,17 @@ +version: '3' +services: + conduktor: + build: + dockerfile: docker/Dockerfile + context: .. + environment: + CDK_TOKEN: yo + CDK_BASE_URL: http://mock:1080 + volumes: + - ./test_resource.yml:/test_resource.yml + mock: + image: mockserver/mockserver:latest + volumes: + - ./initializer.json:/config/initializer.json + environment: + MOCKSERVER_INITIALIZATION_JSON_PATH: /config/initializer.json diff --git a/docker/initializer.json b/docker/initializer.json new file mode 100644 index 0000000..29ef260 --- /dev/null +++ b/docker/initializer.json @@ -0,0 +1,66 @@ +[ + { + "httpRequest": { + "method": "Put", + "path": "/public/v1/Topic", + "headers": { + "Authorization": "Bearer yo" + } + }, + "httpResponse": { + "statusCode": 200, + "body": "\"Created\"", + "headers": { + "Content-Type": ["application/json"] + } + } + }, + { + "httpRequest": { + "method": "Get", + "path": "/public/v1/Topic", + "headers": { + "Authorization": "Bearer yo" + } + }, + "httpResponse": { + "statusCode": 200, + "body": "[{}]", + "headers": { + "Content-Type": ["application/json"] + } + } + }, + { + "httpRequest": { + "method": "Get", + "path": "/public/v1/Topic/yolo", + "headers": { + "Authorization": "Bearer yo" + } + }, + "httpResponse": { + "statusCode": 200, + "body": "{}", + "headers": { + "Content-Type": ["application/json"] + } + } + }, + { + "httpRequest": { + "method": "Delete", + "path": "/public/v1/Topic/yolo", + "headers": { + "Authorization": "Bearer yo" + } + }, + "httpResponse": { + "statusCode": 200, + "body": "{}", + "headers": { + "Content-Type": ["application/json"] + } + } + } +] diff --git a/docker/test_resource.yml b/docker/test_resource.yml new file mode 100644 index 0000000..56d5811 --- /dev/null +++ b/docker/test_resource.yml @@ -0,0 +1,25 @@ +# topics.yml +--- +apiVersion: v1 +kind: Topic +metadata: + name: abcd.topic +spec: + replicationFactor: 1 + partitions: 3 + configs: + min.insync.replicas: 1 + cleanup.policy: delete + retention.ms: 604800000 +--- +apiVersion: v1 +kind: Topic +metadata: + name: abcd.myTopicWrong +spec: + replicationFactor: 1 + partitions: 3 + configs: + min.insync.replicas: 1 + cleanup.policy: delete + retention.ms: 604800000 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..cc9fe67 --- /dev/null +++ b/go.mod @@ -0,0 +1,27 @@ +module github.com/conduktor/ctl + +go 1.22.0 + +require ( + github.com/ghodss/yaml v1.0.0 + github.com/go-resty/resty/v2 v2.11.0 + github.com/jarcoal/httpmock v1.3.1 + github.com/pb33f/libopenapi v0.15.14 + github.com/spf13/cobra v1.8.0 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/bahlo/generic-list-go v0.2.0 // indirect + github.com/buger/jsonparser v1.1.1 // indirect + github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect + github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect + golang.org/x/exp v0.0.0-20240213143201-ec583247a57a // indirect + golang.org/x/net v0.17.0 // indirect + golang.org/x/sync v0.6.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..10630e4 --- /dev/null +++ b/go.sum @@ -0,0 +1,187 @@ +github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= +github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= +github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs= +github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58= +github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 h1:PRxIJD8XjimM5aTknUK9w6DHLDox2r2M3DI4i2pnd3w= +github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936/go.mod h1:ttYvX5qlB+mlV1okblJqcSMtR4c52UKxDiX9GRBS8+Q= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-resty/resty/v2 v2.11.0 h1:i7jMfNOJYMp69lq7qozJP+bjgzfAzeOhuGlyDrqxT/8= +github.com/go-resty/resty/v2 v2.11.0/go.mod h1:iiP/OpA0CkcL3IGt1O0+/SIItFUbkkyw5BGXiVdTu+A= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/jarcoal/httpmock v1.3.1 h1:iUx3whfZWVf3jT01hQTO/Eo5sAYtB2/rqaUuOtpInww= +github.com/jarcoal/httpmock v1.3.1/go.mod h1:3yb8rc4BI7TCBhFY8ng0gjuLKJNquuDNiPaZjnENuYg= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/maxatome/go-testdeep v1.12.0 h1:Ql7Go8Tg0C1D/uMMX59LAoYK7LffeJQ6X2T04nTH68g= +github.com/maxatome/go-testdeep v1.12.0/go.mod h1:lPZc/HAcJMP92l7yI6TRz1aZN5URwUBUAfUNvrclaNM= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= +github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= +github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw= +github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= +github.com/pb33f/libopenapi v0.15.14 h1:A0fn45jbthDyFGXfu5bYIZVsWyPI6hJYm3wG143MT8o= +github.com/pb33f/libopenapi v0.15.14/go.mod h1:PEXNwvtT4KNdjrwudp5OYnD1ryqK6uJ68aMNyWvoMuc= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= +github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= +github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk= +github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN1BWz5V+51Ewf8k+rQ= +github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc= +github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/exp v0.0.0-20240213143201-ec583247a57a h1:HinSgX1tJRX3KsL//Gxynpw5CTOAIPhgL4W8PNiIpVE= +golang.org/x/exp v0.0.0-20240213143201-ec583247a57a/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= +golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20191026110619-0b21df46bc1d/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go new file mode 100644 index 0000000..a18ab9b --- /dev/null +++ b/main.go @@ -0,0 +1,7 @@ +package main + +import "github.com/conduktor/ctl/cmd" + +func main() { + cmd.Execute() +} diff --git a/printutils/printYaml.go b/printutils/printYaml.go new file mode 100644 index 0000000..37ad2d5 --- /dev/null +++ b/printutils/printYaml.go @@ -0,0 +1,67 @@ +package printutils + +import ( + "fmt" + "io" + "slices" + + yaml "gopkg.in/yaml.v3" +) + +func printKeyYaml(w io.Writer, key string, data interface{}) error { + if data != nil { + yamlBytes, err := yaml.Marshal(map[string]interface{}{ + key: data, + }) + if err != nil { + return err + } + fmt.Fprint(w, string(yamlBytes)) + } + return nil +} + +// this print a interface that is expected to a be a resource +// with the following field "version", "kind", "spec", "metadata" +// wit the field in a defined order. +// But in case the given interface is not a map or is a map with more or less field +// than expected we still properly write it +func printResource(w io.Writer, data interface{}) error { + yamlBytes, err := yaml.Marshal(data) + if err != nil { + return err + } + asMap, ok := data.(map[string]interface{}) + if !ok { + fmt.Fprint(w, string(yamlBytes)) + } else { + wantedKeys := []string{"version", "kind", "metadata", "spec"} + for _, wantedKey := range wantedKeys { + printKeyYaml(w, wantedKey, asMap[wantedKey]) + } + for otherKey, data := range asMap { + if !slices.Contains(wantedKeys, otherKey) { + printKeyYaml(w, otherKey, data) + } + } + } + return err +} + +// take a interface that can be a resource or multiple resource +// and print it as the content of a file we could use for an apply +func PrintResourceLikeYamlFile(w io.Writer, data interface{}) error { + switch dataType := data.(type) { + case []interface{}: + for _, d := range dataType { + fmt.Fprintln(w, "---") + err := printResource(w, d) + if err != nil { + return err + } + } + default: + return printResource(w, data) + } + return nil +} diff --git a/printutils/printYaml_test.go b/printutils/printYaml_test.go new file mode 100644 index 0000000..5418425 --- /dev/null +++ b/printutils/printYaml_test.go @@ -0,0 +1,96 @@ +package printutils + +import ( + "bytes" + "encoding/json" + "strings" + "testing" +) + +func TestPrintResourceLikeYamlOnSingleResource(t *testing.T) { + resourceFromBe := `{"spec": "someSpec", "version": "v4", "kind": "Gelato", "metadata": "arancia"}` + var data interface{} + err := json.Unmarshal([]byte(resourceFromBe), &data) + if err != nil { + t.Fatal(err) + } + var output bytes.Buffer + PrintResourceLikeYamlFile(&output, data) + expected := strings.TrimSpace(` +version: v4 +kind: Gelato +metadata: arancia +spec: someSpec`) + got := strings.TrimSpace(output.String()) + if got != expected { + t.Errorf("got:\n%s \nexpected:\n%s", got, expected) + } +} + +func TestPrintResourceLikeYamlInCaseOfScalarValue(t *testing.T) { + resourceFromBe := `[[1], 3, true, "cat"]` + var data interface{} + err := json.Unmarshal([]byte(resourceFromBe), &data) + if err != nil { + t.Fatal(err) + } + var output bytes.Buffer + PrintResourceLikeYamlFile(&output, data) + expected := strings.TrimSpace(` +--- +- 1 +--- +3 +--- +true +--- +cat`) + got := strings.TrimSpace(output.String()) + if got != expected { + t.Errorf("got:\n%s \nexpected:\n%s", got, expected) + } +} + +func TestPrintResourceLikeYamlOnMultileResources(t *testing.T) { + resourceFromBe := `{"spec": "someSpec", "version": "v4", "newKind": "Gelato", "metadata": "arancia"}` + var data interface{} + err := json.Unmarshal([]byte(resourceFromBe), &data) + if err != nil { + t.Fatal(err) + } + var output bytes.Buffer + PrintResourceLikeYamlFile(&output, data) + expected := strings.TrimSpace(` +version: v4 +metadata: arancia +spec: someSpec +newKind: Gelato +`) + got := strings.TrimSpace(output.String()) + if got != expected { + t.Errorf("got:\n%s \nexpected:\n%s", got, expected) + } +} +func TestPrintResourceWithMissingFieldAndUnexpectedField(t *testing.T) { + resourceFromBe := `[[1], 3, true, "cat"]` + var data interface{} + err := json.Unmarshal([]byte(resourceFromBe), &data) + if err != nil { + t.Fatal(err) + } + var output bytes.Buffer + PrintResourceLikeYamlFile(&output, data) + expected := strings.TrimSpace(` +--- +- 1 +--- +3 +--- +true +--- +cat`) + got := strings.TrimSpace(output.String()) + if got != expected { + t.Errorf("got:\n%s \nexpected:\n%s", got, expected) + } +} diff --git a/resource/resource.go b/resource/resource.go new file mode 100644 index 0000000..28d9dbe --- /dev/null +++ b/resource/resource.go @@ -0,0 +1,103 @@ +package resource + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + yamlJson "github.com/ghodss/yaml" + yaml "gopkg.in/yaml.v3" +) + +type Resource struct { + Json []byte + Kind string + Name string + Version string +} + +func (r Resource) String() string { + return fmt.Sprintf(`version: %s, kind: %s, name: %s, json: '%s'`, r.Version, r.Kind, r.Name, string(r.Json)) +} + +type yamlRoot struct { + Version string + Kind string + Metadata metadata +} + +type metadata struct { + Name string +} + +func FromFile(path string) ([]Resource, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + + return FromByte(data) +} + +func FromFolder(path string) ([]Resource, error) { + dirEntry, err := os.ReadDir(path) + if err != nil { + return nil, err + } + var result = make([]Resource, 0, 0) + for _, entry := range dirEntry { + if !entry.IsDir() && (strings.HasSuffix(entry.Name(), ".yml") || strings.HasSuffix(entry.Name(), ".yaml")) { + resources, err := FromFile(filepath.Join(path, entry.Name())) + result = append(result, resources...) + if err != nil { + return nil, err + } + } + } + + return result, nil +} + +func FromByte(data []byte) ([]Resource, error) { + reader := bytes.NewReader(data) + var yamlData interface{} + results := make([]Resource, 0, 2) + d := yaml.NewDecoder(reader) + for { + err := d.Decode(&yamlData) + if err == io.EOF { + break + } else if err != nil { + return nil, err + } + yamlByte, err := yaml.Marshal(yamlData) + if err != nil { + return nil, err + } + result, err := yamlByteToResource([]byte(yamlByte)) + if err != nil { + return nil, err + } + results = append(results, result) + } + return results, nil +} + +func yamlByteToResource(data []byte) (Resource, error) { + jsonByte, err := yamlJson.YAMLToJSON(data) + if err != nil { + return Resource{}, nil + } + + var yamlRoot yamlRoot + err = json.Unmarshal(jsonByte, &yamlRoot) + if err != nil { + return Resource{}, nil + } + + return Resource{Json: jsonByte, Kind: yamlRoot.Kind, Name: yamlRoot.Metadata.Name, Version: yamlRoot.Version}, nil +} diff --git a/resource/resource_test.go b/resource/resource_test.go new file mode 100644 index 0000000..92332d0 --- /dev/null +++ b/resource/resource_test.go @@ -0,0 +1,101 @@ +package resource + +import ( + "testing" +) + +func checkResource(t *testing.T, result, expected Resource) { + if result.Name != expected.Name { + t.Errorf("Expected name %s got %s", expected.Name, result.Name) + } + + if result.Kind != expected.Kind { + t.Errorf("Expected kind %s got %s", expected.Kind, result.Kind) + } + + if result.Version != expected.Version { + t.Errorf("Expected version %s got %s", expected.Version, result.Version) + } + + if string(result.Json) != string(expected.Json) { + t.Errorf("Expected json:\n%s got\n%s", string(expected.Json), string(result.Json)) + } +} + +func TestFromByteForOneResourceWithValidResource(t *testing.T) { + yamlByte := []byte(` +# comment +--- +version: v1 +kind: Topic +metadata: + name: abc.myTopic +spec: + replicationFactor: 1 +--- +version: v2 +kind: ConsumerGroup +metadata: + name: cg1 +`) + + results, err := FromByte(yamlByte) + if err != nil { + t.Error(err) + } + if len(results) != 2 { + t.Errorf("results expected1 of length 2, got length %d", len(results)) + } + + checkResource(t, results[0], Resource{ + Version: "v1", + Kind: "Topic", + Name: "abc.myTopic", + Json: []byte(`{"kind":"Topic","metadata":{"name":"abc.myTopic"},"spec":{"replicationFactor":1},"version":"v1"}`), + }) + + checkResource(t, results[1], Resource{ + Version: "v2", + Kind: "ConsumerGroup", + Name: "cg1", + Json: []byte(`{"kind":"ConsumerGroup","metadata":{"name":"cg1"},"version":"v2"}`), + }) +} + +func TestFromFolder(t *testing.T) { + resources, err := FromFolder("yamls") + if err != nil { + t.Fatal(err) + } + if len(resources) != 4 { + t.Fatalf("Expected to read 4 resources, readed %d", len(resources)) + } + + checkResource(t, resources[0], Resource{ + Version: "v1", + Kind: "a", + Name: "a", + Json: []byte(`{"kind":"a","metadata":{"name":"a"},"spec":{"data":"data"},"version":"v1"}`), + }) + + checkResource(t, resources[1], Resource{ + Version: "v1", + Kind: "a", + Name: "b", + Json: []byte(`{"kind":"a","metadata":{"name":"b"},"spec":{"data":"data2"},"version":"v1"}`), + }) + + checkResource(t, resources[2], Resource{ + Version: "v1", + Kind: "b", + Name: "a", + Json: []byte(`{"kind":"b","metadata":{"name":"a"},"spec":{"data":"yo"},"version":"v1"}`), + }) + + checkResource(t, resources[3], Resource{ + Version: "v1", + Kind: "b", + Name: "b", + Json: []byte(`{"kind":"b","metadata":{"name":"b"},"spec":{"data":"lo"},"version":"v1"}`), + }) +} diff --git a/resource/yamls/a.yml b/resource/yamls/a.yml new file mode 100644 index 0000000..9cf0209 --- /dev/null +++ b/resource/yamls/a.yml @@ -0,0 +1,14 @@ +--- +version: v1 +kind: a +metadata: + name: a +spec: + data: data +--- +version: v1 +kind: a +metadata: + name: b +spec: + data: data2 diff --git a/resource/yamls/b.yaml b/resource/yamls/b.yaml new file mode 100644 index 0000000..c638556 --- /dev/null +++ b/resource/yamls/b.yaml @@ -0,0 +1,14 @@ +--- +version: v1 +kind: b +metadata: + name: a +spec: + data: yo +--- +version: v1 +kind: b +metadata: + name: b +spec: + data: lo diff --git a/resource/yamls/other.txt b/resource/yamls/other.txt new file mode 100644 index 0000000..b9190b8 --- /dev/null +++ b/resource/yamls/other.txt @@ -0,0 +1,6 @@ +version: v1 +kind: other +metadata: + name: other +spec: + data: other diff --git a/schema/schema.go b/schema/schema.go new file mode 100644 index 0000000..abab414 --- /dev/null +++ b/schema/schema.go @@ -0,0 +1,45 @@ +package schema + +import ( + "github.com/conduktor/ctl/utils" + "github.com/pb33f/libopenapi" + v3high "github.com/pb33f/libopenapi/datamodel/high/v3" + "golang.org/x/exp/slices" + "strings" +) + +type Schema struct { + doc *libopenapi.DocumentModel[v3high.Document] +} + +func New(schema []byte) (*Schema, error) { + doc, err := libopenapi.NewDocument(schema) + if err != nil { + return nil, err + } + v3Model, errors := doc.BuildV3Model() + if len(errors) > 0 { + return nil, errors[0] + } + + return &Schema{ + doc: v3Model, + }, nil +} + +func (s *Schema) GetKind() ([]string, error) { + result := make([]string, 0) + for path := s.doc.Model.Paths.PathItems.First(); path != nil; path = path.Next() { + if path.Value().Get != nil { + for _, tag := range path.Value().Get.Tags { + if strings.HasPrefix(tag, "self-serve-") { + newTag := utils.KebabToUpperCamel(strings.TrimPrefix(tag, "self-serve-")) + if !slices.Contains(result, newTag) { + result = append(result, newTag) + } + } + } + } + } + return result, nil +} diff --git a/test_final_exec.sh b/test_final_exec.sh new file mode 100755 index 0000000..f4c312c --- /dev/null +++ b/test_final_exec.sh @@ -0,0 +1,23 @@ +#!/bin/bash -eu + +echoerr() { echo "$@" 1>&2; } + +SCRIPTDIR=$(dirname "$0") + +function cleanup { + docker compose -f "$SCRIPTDIR/docker/docker-compose.yml" down +} + + +trap cleanup EXIT +main() { + cd "$SCRIPTDIR" + docker compose -f docker/docker-compose.yml build + docker compose -f docker/docker-compose.yml up -d mock + sleep 1 + docker compose -f docker/docker-compose.yml run conduktor apply -f /test_resource.yml + docker compose -f docker/docker-compose.yml run conduktor get Topic yolo + docker compose -f docker/docker-compose.yml run conduktor delete Topic yolo -v +} + +main "$@" diff --git a/utils/utils.go b/utils/utils.go new file mode 100644 index 0000000..4b61b11 --- /dev/null +++ b/utils/utils.go @@ -0,0 +1,40 @@ +package utils + +import "strings" + +func UpperCamelToKebab(input string) string { + // Split the input string into words + words := make([]string, 0) + currentWord := "" + for _, char := range input { + if char >= 'A' && char <= 'Z' { + if currentWord != "" { + words = append(words, currentWord) + } + currentWord = string(char) + } else { + currentWord += string(char) + } + } + if currentWord != "" { + words = append(words, currentWord) + } + + // Join the words with hyphens + kebabCase := strings.ToLower(strings.Join(words, "-")) + + return kebabCase +} + +func KebabToUpperCamel(input string) string { + // Split the input string into words + words := strings.Split(input, "-") + + // Capitalize the first letter of each word + upperCamelCase := "" + for _, word := range words { + upperCamelCase += strings.Title(word) + } + + return upperCamelCase +} diff --git a/utils/utils_test.go b/utils/utils_test.go new file mode 100644 index 0000000..00ca4c7 --- /dev/null +++ b/utils/utils_test.go @@ -0,0 +1,63 @@ +package utils + +import ( + "testing" +) + +func TestUpperCamelToKebab(t *testing.T) { + t.Run("converts upper camel case to kebab case", func(t *testing.T) { + got := UpperCamelToKebab("UpperCamelCase") + want := "upper-camel-case" + + if got != want { + t.Errorf("got %q, want %q", got, want) + } + }) + + t.Run("handles single word", func(t *testing.T) { + got := UpperCamelToKebab("Word") + want := "word" + + if got != want { + t.Errorf("got %q, want %q", got, want) + } + }) + + t.Run("handles empty string", func(t *testing.T) { + got := UpperCamelToKebab("") + want := "" + + if got != want { + t.Errorf("got %q, want %q", got, want) + } + }) +} + +func TestKebabToUpperCamel(t *testing.T) { + t.Run("converts kebab case to upper camel case", func(t *testing.T) { + got := KebabToUpperCamel("kebab-case-to-upper") + want := "KebabCaseToUpper" + + if got != want { + t.Errorf("got %q, want %q", got, want) + } + }) + + t.Run("handles single word", func(t *testing.T) { + got := KebabToUpperCamel("word") + want := "Word" + + if got != want { + t.Errorf("got %q, want %q", got, want) + } + }) + + t.Run("handles empty string", func(t *testing.T) { + got := KebabToUpperCamel("") + want := "" + + if got != want { + t.Errorf("got %q, want %q", got, want) + } + }) +}