"
labels: ["kind/bug"]
body:
- type: markdown
attributes:
value: "## Thank you for contributing to our Kompose!"
- type: textarea
attributes:
label: Expected Behavior
description: |
Briefly describe what is the desired behavior.
validations:
required: true
- type: textarea
attributes:
label: Actual Behavior
description: |
Briefly describe what is the actual behavior.
validations:
required: true
- type: textarea
attributes:
label: Steps To Reproduce
description: Steps to reproduce the behavior.
placeholder: |
1. In this environment...
2. With this config...
3. Run '...'
4. See error or unexpected result...
validations:
required: false
- type: textarea
attributes:
label: Kompose Version
description: |
Paste output of `kompose version`.
render: Text
validations:
required: true
- type: textarea
attributes:
label: Docker-Compose file
description: Paste output of the `docker-compose.yaml` that you are using.
render: YAML
validations:
required: false
- type: textarea
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the issue you are encountering!
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
validations:
required: false
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: Kubernetes Community Slack
url: https://kubernetes.slack.com
about: "Use the #kompose channel"
================================================
FILE: .github/ISSUE_TEMPLATE/enhancement.yml
================================================
name: Enhancement Tracking Issue
description: Provide supporting details for a feature in development
labels: kind/feature
body:
- type: markdown
attributes:
value: "## Thank you for contributing to our Kompose!"
- type: textarea
id: feature
attributes:
label: What would you like to be added?
description: |
Describe what feature/enhancement that you want to be added to Kompose.
validations:
required: true
- type: textarea
id: rationale
attributes:
label: Why is this needed?
validations:
required: true
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
#### What type of PR is this?
#### What this PR does / why we need it:
#### Which issue(s) this PR fixes:
Fixes #
#### Special notes for your reviewer:
================================================
FILE: .github/dependabot.yaml
================================================
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- commit-message:
include: "scope"
prefix: "chore(deps)"
directory: "/"
open-pull-requests-limit: 10
package-ecosystem: "gomod"
schedule:
interval: "daily"
- commit-message:
include: "scope"
prefix: "chore(ci)"
directory: "/"
open-pull-requests-limit: 10
package-ecosystem: "github-actions"
schedule:
interval: "daily"
================================================
FILE: .github/workflows/go.yml
================================================
name: Go
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
env:
# Avoid noisy outputs like "tput: No value for $TERM and no -T specified"
TERM: dumb
jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.x
uses: actions/setup-go@v5
with:
go-version: ^1.21
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v6
- name: Build
run: make bin
- name: Upload a Build Artifact
uses: actions/upload-artifact@v6
with:
name: "kompose"
path: "kompose"
================================================
FILE: .github/workflows/lint.yml
================================================
name: lint
on:
pull_request:
jobs:
lint:
strategy:
matrix:
go: [1.21, 1.22]
name: lint
runs-on: ubuntu-latest
steps:
- name: "Checkout"
uses: actions/checkout@v6
- name: "Install golang"
uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go }}
- name: "Run go vet"
run: "go vet ./pkg/..."
================================================
FILE: .github/workflows/test.yml
================================================
name: Kompose CI
on:
push:
branches:
- main
pull_request:
env:
# Avoid noisy outputs like "tput: No value for $TERM and no -T specified"
TERM: dumb
jobs:
test:
name: Test with ${{ matrix.go }} and CROSS_COMPILE=${{ matrix.cross_compile }}
runs-on: ubuntu-latest
strategy:
matrix:
go: [1.21, 1.22]
cross_compile: [true, false]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v5
with:
go-version: ${{ matrix.go }}
- name: Install dyff
run: go install github.com/homeport/dyff/cmd/dyff@v1.5.8
- name: Run tests
run: make test
- name: Perform cross compile
if: ${{ matrix.cross_compile }}
run: make cross
docs:
name: Build docs and Coveralls integration
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v6
- uses: actions/setup-go@v5
with:
go-version: ^1.21
- name: Install dyff
run: go install github.com/homeport/dyff/cmd/dyff@v1.5.8
- name: Create .coverprofile for each targeted directory by re:running tests
run: make test
- name: Collect all .coverprofile files and save it to one file gover.coverprofile
run: gover
- name: Send coverage
run: goveralls -coverprofile=gover.coverprofile -service=github
env:
# As per https://github.com/mattn/goveralls#github-actions
COVERALLS_TOKEN: ${{ secrets.GITHUB_TOKEN }}
================================================
FILE: .gitignore
================================================
#
# KOMPOSE SPECIFIC
#
# Ignore compiled Kompose files
kompose
bin
/docker-compose.yaml
/docker-compose.yml
/compose.yaml
/compose.yml
changes.txt
# Ignore site documents / when switching branches
docs/_site/
docs/.jekyll-cache/
docs/.git/
docs/.gitignore
_site/
.jekyll-cache/
#
# GO SPECIFIC
#
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Coveralls files
.coverprofile
#
# VIM SPECIFIC
#
# swap
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
# session
Session.vim
# temporary
.netrwhist
*~
# auto-generated tag files
tags
# IntelliJ IDE specific
.idea
.DS_Store
# VSCode specific
.vscode
# Client Test generated files
client/testdata/generated
pkg/mod
================================================
FILE: .gitmodules
================================================
================================================
FILE: .golangci.yml
================================================
# Golang CI pipeline configuration
linters:
disable-all: true
# Run golangci-lint.yml linters to see the list of all linters
# Please keep them sorted alphabetically
enable:
- bodyclose
- deadcode
- depguard
# - dogsled
# - errcheck
# - goconst
- goimports
# - staticcheck
- goprintffuncname
# - gosimple
- govet
# - ineffassign
- misspell
# - nakedret
- nolintlint
- rowserrcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- varcheck
- whitespace
================================================
FILE: .mention-bot
================================================
{
"maxReviewers": 2,
"numFilesToCheck": 5,
"message": "@pullRequester, thank you for the pull request! We'll request some people to review your PR. @reviewers, please review this.",
"fileBlacklist": ["*.md"],
"userBlacklist": ["ngtuna", "janetkuo", "sebgoa", "dustymabe", "gitlawr"],
"actions": ["opened", "labeled"],
"skipAlreadyMentionedPR": true,
"createReviewRequest": true
}
================================================
FILE: .openvex/templates/README.md
================================================
# OpenVEX Templates Directory
This directory contains the OpenVEX data for this repository.
The files stored in this directory are used as templates by
`vexctl generate` when generating VEX data for a release or
a specific artifact.
To add new statements to publish data about a vulnerability,
download [vexctl](https://github.com/openvex/vexctl)
and append new statements using `vexctl add`. For example:
```
vexctl add --in-place main.openvex.json pkg:oci/test CVE-2014-1234567 fixed
```
That will add a new VEX statement expressing that the impact of
CVE-2014-1234567 is under investigation in the test image. When
cutting a new release, for `pkg:oci/test` the new file will be
incorporated to the relase's VEX data.
## Read more about OpenVEX
To know more about generating, publishing and using VEX data
in your project, please check out the vexctl repository and
documentation: https://github.com/openvex/vexctl
OpenVEX also has an examples repository with samples and docs:
https://github.com/openvex/examples
================================================
FILE: .openvex/templates/main.openvex.json
================================================
{
"@context": "https://openvex.dev/ns/v0.2.0",
"@id": "https://openvex.dev/docs/public/vex-6f9001fd8630edd2996df09f345882066d7b5bf512e54af918343d278640ecd0",
"author": "vexctl (automated template)",
"timestamp": "2023-12-15T19:10:43.910365Z",
"version": 1,
"statements": []
}
================================================
FILE: .pre-commit-config.yaml
================================================
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v5.0.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-added-large-files
- repo: https://github.com/dnephin/pre-commit-golang
rev: v0.5.1
hooks:
- id: go-fmt
- id: go-imports
- id: golangci-lint
- id: go-unit-tests
- repo: https://github.com/alessandrojcm/commitlint-pre-commit-hook
rev: v9.18.0
hooks:
- id: commitlint
stages: [commit-msg]
additional_dependencies: ["@commitlint/config-conventional"]
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing guidelines
## How to become a contributor and submit your own code
### Contributor License Agreements
We'd love to accept your patches! Before we can take them, we have to jump a couple of legal hurdles.
Please fill out either the individual or corporate Contributor License Agreement (CLA).
- If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an individual CLA.
- If you work for a company that wants to allow you to contribute your work, then you'll need to sign a corporate CLA.
Contact one of the [OWNERS](OWNERS) on Slack to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to accept your pull requests.
### Contributing A Patch
1. Submit an issue describing your proposed change to the repo in question.
2. The [repo owners](OWNERS) will respond to your issue promptly.
3. If your proposed change is accepted, and you haven't already done so, sign a Contributor License Agreement (see details above).
4. Fork the desired repo, develop and test your code changes.
5. Submit a pull request.
Note: Code-related PR's require one ACK / LGTM from a maintainer or core contributor. Doc-related PR's require either one or none depending on the content changed (for example, a spec change would require one, but a spelling error would require none).
### Adding dependencies
If your patch depends on new packages, make sure that both `go.mod` and `go.sum` are updated properly. Also we recommend you to execute `go mod tidy` before sending a pull request.
================================================
FILE: Dockerfile
================================================
# Alpine Builder
FROM alpine AS builder
RUN apk add --no-cache curl
COPY ./build/VERSION VERSION
RUN \
version=$(cat VERSION) && \
ARCH=$(uname -m | sed 's/armv7l/arm/g' | sed 's/aarch64/arm64/g' | sed 's/x86_64/amd64/g') && \
curl -L \
"https://github.com/kubernetes/kompose/releases/download/v${version}/kompose-linux-${ARCH}" \
-o kompose && \
chmod +x kompose
# Runtime
FROM alpine
COPY --from=builder /kompose /usr/bin/kompose
================================================
FILE: Jenkinsfile
================================================
@Library('github.com/fabric8io/fabric8-pipeline-library@master')
def dummy
goTemplate{
dockerNode{
goMake{
githubOrganisation = 'kubernetes'
dockerOrganisation = 'fabric8'
project = 'kompose'
makeCommand = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/go/bin:/usr/local/:/go/bin:/home/jenkins/go/bin \
&& bash script/test/cmd/fix_detached_head.sh && make test"
}
}
}
================================================
FILE: LICENSE
================================================
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.
================================================
FILE: Makefile
================================================
# Copyright 2016 The Kubernetes Authors.
#
# 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.
GITCOMMIT := $(shell git rev-parse --short HEAD)
BUILD_FLAGS := -ldflags="-w -s -X github.com/kubernetes/kompose/pkg/version.GITCOMMIT=$(GITCOMMIT)"
TEST_IMAGE := kompose/tests:latest
# go-get-tool will 'go get' any package $2 and install it to $1.
PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST))))
define go-get-tool
@[ -f $(1) ] || { \
set -e ;\
TMP_DIR=$$(mktemp -d) ;\
cd $$TMP_DIR ;\
go mod init tmp ;\
echo "Downloading $(2)" ;\
GOBIN=$(PROJECT_DIR)/bin go get $(2) ;\
rm -rf $$TMP_DIR ;\
}
endef
default: bin
.PHONY: all
all: bin
.PHONY: bin
bin:
CGO_ENABLED=0 GO111MODULE=on go build ${BUILD_FLAGS} -o kompose main.go
.PHONY: install
install:
go install ${BUILD_FLAGS}
# kompile kompose for multiple platforms
.PHONY: cross
cross:
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 GO111MODULE=on go build ${BUILD_FLAGS} -installsuffix cgo -o "bin/kompose-linux-amd64" main.go
GOOS=linux GOARCH=arm CGO_ENABLED=0 GO111MODULE=on go build ${BUILD_FLAGS} -installsuffix cgo -o "bin/kompose-linux-arm" main.go
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 GO111MODULE=on go build ${BUILD_FLAGS} -installsuffix cgo -o "bin/kompose-linux-arm64" main.go
GOOS=windows GOARCH=amd64 CGO_ENABLED=0 GO111MODULE=on go build ${BUILD_FLAGS} -installsuffix cgo -o "bin/kompose-windows-amd64.exe" main.go
GOOS=darwin GOARCH=amd64 CGO_ENABLED=0 GO111MODULE=on go build ${BUILD_FLAGS} -installsuffix cgo -o "bin/kompose-darwin-amd64" main.go
GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 GO111MODULE=on go build ${BUILD_FLAGS} -installsuffix cgo -o "bin/kompose-darwin-arm64" main.go
.PHONY: clean
clean:
rm -f kompose
rm -r -f bundles
.PHONY: test-unit
test-unit:
go test -short $(BUILD_FLAGS) -race -cover -v ./...
# Run unit tests and collect coverage
.PHONY: test-unit-cover
test-unit-cover:
# First install packages that are dependencies of the test.
go test -short -i -race -cover ./...
# go test doesn't support colleting coverage across multiple packages,
# generate go test commands using go list and run go test for every package separately
go list -f '"go test -short -race -cover -v -coverprofile={{.Dir}}/.coverprofile {{.ImportPath}}"' github.com/kubernetes/kompose/... | grep -v "vendor" | xargs -L 1 -P4 sh -c
# run openshift up/down tests
.PHONY: test-openshift
test-openshift:
./script/test_in_openshift/run.sh
# run commandline tests
.PHONY: test-cmd
test-cmd:
./script/test/cmd/tests.sh
# run all validation tests
.PHONY: validate
validate: gofmt vet
.PHONY: vet
vet:
go vet ./pkg/...
.PHONY: gofmt
gofmt:
./script/check-gofmt.sh
# Run all tests
.PHONY: test
test: bin test-dep validate test-unit-cover install test-cmd
# Install all the required test-dependencies before executing tests (only valid when running `make test`)
.PHONY: test-dep
test-dep:
go install github.com/mattn/goveralls@latest
go install github.com/modocache/gover@latest
go install github.com/mitchellh/gox@latest
# build docker image that is used for running all test locally
.PHONY: test-image
test-image:
docker build -t $(TEST_IMAGE) -f script/test_in_container/Dockerfile script/test_in_container/
# run all test locally in docker image (image can be build by by build-test-image target)
.PHONY: test-container
test-container:
docker run -v `pwd`:/opt/tmp/kompose:ro -it $(TEST_IMAGE)
.PHONY: test-k8s
test-k8s:
./script/test_k8s/test.sh
GOLANGCI_LINT = $(shell pwd)/bin/golangci-lint
.PHONY: install-golangci-lint
install-golangci-lint:
# golangci-lint version must consistent with github CI
# ref: ./.github/workflows/golangci-lint.yml
$(call go-get-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint@v1.32.2)
.PHONY: golangci-lint
golangci-lint: install-golangci-lint
$(GOLANGCI_LINT) run -c .golangci.yml --timeout 5m
.PHONY: test-client
test-client:
go test ./client/...
================================================
FILE: OWNERS
================================================
# See the OWNERS file documentation:
# https://github.com/kubernetes/community/blob/master/contributors/devel/owners.md
reviewers:
- cdrage
- hangyan
- TessaIO
approvers:
- cdrage
- hangyan
- TessaIO
================================================
FILE: README.md
================================================
# Kompose (Kubernetes + Compose)
[![Build Status Widget]][Build Status] [![Coverage Status Widget]][Coverage Status] [![GoDoc Widget]][GoDoc] [![GoReportCard Widget]][GoReportCardResult]

`kompose` is a tool to help users who are familiar with `docker-compose` move to [Kubernetes](http://kubernetes.io). `kompose` takes a [Compose Specification](https://compose-spec.io/) file and translates it into Kubernetes resources.
`kompose` is a convenience tool to go from local Compose environment to managing your application with Kubernetes. Transformation of the [Compose Specification](https://compose-spec.io/) format to Kubernetes resources manifest may not be exact, but it helps tremendously when first deploying an application on Kubernetes.
## Use Case
Convert [`compose.yaml`](https://raw.githubusercontent.com/kubernetes/kompose/main/examples/compose.yaml) into Kubernetes deployments and services with one simple command:
```sh
$ kompose convert -f compose.yaml
INFO Kubernetes file "frontend-service.yaml" created
INFO Kubernetes file "redis-leader-service.yaml" created
INFO Kubernetes file "redis-replica-service.yaml" created
INFO Kubernetes file "frontend-deployment.yaml" created
INFO Kubernetes file "redis-leader-deployment.yaml" created
INFO Kubernetes file "redis-replica-deployment.yaml" created
```
Other examples are provided in the _examples_ [directory](./examples).
## Installation
We have multiple ways to install Kompose. Our preferred method is downloading the binary from the latest GitHub release.
Our entire list of installation methods are located in our [installation.md](/docs/installation.md) document.
Installation methods:
- [Binary (Preferred method)](/docs/installation.md#github-release)
- [Go](/docs/installation.md#go)
- [CentOS](/docs/installation.md#centos)
- [openSUSE/SLE](/docs/installation.md#opensusesle)
- [NixOS](/docs/installation.md#nixos)
- [macOS (Homebrew and MacPorts)](/docs/installation.md#macos)
- [Windows](/docs/installation.md#windows)
- [Docker](/docs/installation.md#docker)
#### Binary installation
Kompose is released via GitHub on a three-week cycle, you can see all current releases on the [GitHub release page](https://github.com/kubernetes/kompose/releases).
**Linux and macOS:**
```sh
# Linux
curl -L https://github.com/kubernetes/kompose/releases/download/v1.38.0/kompose-linux-amd64 -o kompose
# macOS
curl -L https://github.com/kubernetes/kompose/releases/download/v1.38.0/kompose-darwin-amd64 -o kompose
chmod +x kompose
sudo mv ./kompose /usr/local/bin/kompose
```
**Windows:**
Download from [GitHub](https://github.com/kubernetes/kompose/releases/download/v1.38.0/kompose-windows-amd64.exe) and add the binary to your PATH.
## Shell autocompletion
We support Bash, Zsh and Fish autocompletion.
```sh
# Bash (add to .bashrc for persistence)
source <(kompose completion bash)
# Zsh (add to .zshrc for persistence)
source <(kompose completion zsh)
# Fish autocompletion
kompose completion fish | source
```
## Development and building of Kompose
### Building with `go`
**Requisites:**
1. [make](https://www.gnu.org/software/make/)
2. [Golang](https://golang.org/) v1.6 or later
3. Set `GOPATH` correctly or click [SettingGOPATH](https://github.com/golang/go/wiki/SettingGOPATH) for details
**Steps:**
1. Clone repository
```console
$ git clone https://github.com/kubernetes/kompose.git $GOPATH/src/github.com/kubernetes/kompose
```
2. Change directory to the cloned repo.
```console
cd $GOPATH/src/github.com/kubernetes/kompose
```
3. Build with `make`
```console
$ make bin
```
4. Or build with `go`
```console
$ go build -o kompose main.go
```
5. Test your changes
```console
$ make test
```
## Documentation
Documentation can be found at our [kompose.io](http://kompose.io) website or our [docs](https://github.com/kubernetes/kompose/tree/main/docs) folder.
Here is a list of all available docs:
- [Quick start](docs/getting-started.md)
- [Installation](docs/installation.md)
- [User guide](docs/user-guide.md)
- [Conversion](docs/conversion.md)
- [Architecture](docs/architecture.md)
- [Development](docs/development.md)
## Community, Discussion, Contribution, and Support
**Issues:** If you find any issues, please [file it](https://github.com/kubernetes/kompose/issues).
**Kubernetes Community:** As part of the Kubernetes ecosystem, we follow the Kubernetes community principles. More information can be found on the [community page](http://kubernetes.io/community/).
**Chat (Slack):** We're fairly active on [Slack](http://slack.kubernetes.io#kompose) and you can find us in the #kompose channel.
### Code of Conduct
Participation in the Kubernetes community is governed by the [Kubernetes Code of Conduct](code-of-conduct.md).
[Build Status]: https://github.com/kubernetes/kompose/actions?query=workflow%3A%22Kompose+CI%22
[Build Status Widget]: https://github.com/kubernetes/kompose/workflows/Kompose%20CI/badge.svg
[GoDoc]: https://godoc.org/github.com/kubernetes/kompose
[GoDoc Widget]: https://godoc.org/github.com/kubernetes/kompose?status.svg
[Coverage Status Widget]: https://coveralls.io/repos/github/kubernetes/kompose/badge.svg?branch=main
[Coverage Status]: https://coveralls.io/github/kubernetes/kompose?branch=main
[GoReportCard Widget]: https://goreportcard.com/badge/github.com/kubernetes/kompose
[GoReportCardResult]: https://goreportcard.com/report/github.com/kubernetes/kompose
================================================
FILE: RELEASE.md
================================================
# Release Process
The process is as follows:
1. A PR proposing a new release with a changelog since the last release
1. At least 2 or more [OWNERS](OWNERS) must LGTM this release
1. The release PR is closed
1. An OWNER runs `git tag -s $VERSION` and inserts the changelog and pushes the tag with `git push $VERSION`
================================================
FILE: SECURITY.md
================================================
# Security Policy
## Security Announcements
Join the [kubernetes-security-announce] group for security and vulnerability announcements.
You can also subscribe to an RSS feed of the above using [this link][kubernetes-security-announce-rss].
## Reporting a Vulnerability
Instructions for reporting a vulnerability can be found on the
[Kubernetes Security and Disclosure Information] page.
## Supported Versions
Information about supported Kubernetes versions can be found on the
[Kubernetes version and version skew support policy] page on the Kubernetes website.
[kubernetes-security-announce]: https://groups.google.com/forum/#!forum/kubernetes-security-announce
[kubernetes-security-announce-rss]: https://groups.google.com/forum/feed/kubernetes-security-announce/msgs/rss_v2_0.xml?num=50
[Kubernetes version and version skew support policy]: https://kubernetes.io/docs/setup/release/version-skew-policy/#supported-versions
[Kubernetes Security and Disclosure Information]: https://kubernetes.io/docs/reference/issues-security/security/#report-a-vulnerability
================================================
FILE: SECURITY_CONTACTS
================================================
# Defined below are the security contacts for this repo.
#
# They are the contact point for the Product Security Committee to reach out
# to for triaging and handling of incoming issues.
#
# The below names agree to abide by the
# [Embargo Policy](https://git.k8s.io/security/private-distributors-list.md#embargo-policy)
# and will be removed and replaced if they violate that agreement.
#
# DO NOT REPORT SECURITY VULNERABILITIES DIRECTLY TO THESE NAMES, FOLLOW THE
# INSTRUCTIONS AT https://kubernetes.io/security/
cdrage
kadel
hangyan
janetkuo
ngtuna
sebgoa
AhmedGrati
================================================
FILE: build/README.md
================================================
# Fedora RPM packaging
There are instructions on how to build the RPM.
# 1. Gofed
Grab gofed from https://github.com/gofed/gofed
Choose which version of the repo you want to build. For kompose it was 0.3.0 and the commit was 135165b39c55d29a5426479ded81eddd56bfbaf4
Run the following to generate spec file:
```sh
gofed repo2spec --detect github.com/kubernetes/kompose --commit 135165b39c55d29a5426479ded81eddd56bfbaf4 --with-extra --with-build -f
```
The spec file is now located at:
```sh
$HOME/gofed/golang-github-kubernetes-incubator-kompose/golang-github-kubernetes-incubator-kompose.spec
```
# 2. Dependencies
Now we need to go through and fix some things.
Generate bundled dependencies by using parsedeps.go
Go to the kompose source folder and then run:
```sh
go run parsedeps.go
```
In the future this will possibly done by `gofed`, see: https://github.com/gofed/gofed/issues/42
# 3. Building a source RPM locally on CentOS
First, follow instructions to do local setup https://wiki.centos.org/HowTos/SetupRpmBuildEnvironment
Source: https://wiki.centos.org/HowTos/RebuildSRPM
Second, checkout the source to the release commit
Copy the kompose code directory with name `kompose-135165b39c55d29a5426479ded81eddd56bfbaf4`
Tar the `kompose-135165b39c55d29a5426479ded81eddd56bfbaf4` code directory as `kompose-135165b.tar.gz` and copy it to `$HOME/rpmbuild/SOURCES/`
Run following command:
```sh
rpmbuild -ba kompose.spec
```
Find the srpm in `$HOME/rpmbuild/SRPMS`
Find the RPM in `$HOME/rpmbuild/RPM/arch/`
Check that the dependencies are proper:
```sh
rpm -qpR RPMS/x86_64/kompose-0.3.0-0.1.git135165b.el7.centos.x86_64.rpm
```
# 4. Running in on Koji (build system)
First, setup your environment in order to run Koji: https://fedoraproject.org/wiki/Using_the_Koji_build_system
Example setup:
```sh
fedora-packager-setup
kinit @FEDORAPROJECT.ORG
```
To build it on koji run:
```
koji build --scratch rawhide kompose-0.3.0-0.1.git135165b.el7.centos.src.rpm
```
================================================
FILE: build/VERSION
================================================
1.38.0
================================================
FILE: client/client.go
================================================
package client
type Kompose struct {
suppressWarnings bool
verbose bool
errorOnWarning bool
}
func NewClient(opts ...Opt) (*Kompose, error) {
k := &Kompose{
suppressWarnings: false,
verbose: false,
errorOnWarning: false,
}
for _, op := range opts {
if err := op(k); err != nil {
return nil, err
}
}
return k, nil
}
================================================
FILE: client/convert.go
================================================
package client
import (
"fmt"
"github.com/kubernetes/kompose/pkg/app"
"github.com/kubernetes/kompose/pkg/kobject"
"k8s.io/apimachinery/pkg/runtime"
)
func (k *Kompose) Convert(options ConvertOptions) ([]runtime.Object, error) {
options = k.setDefaultValues(options)
err := k.validateOptions(options)
if err != nil {
return nil, err
}
kobjectConvertOptions := kobject.ConvertOptions{
ToStdout: options.ToStdout,
CreateChart: k.createChart(options),
GenerateYaml: true,
GenerateJSON: options.GenerateJson,
Replicas: *options.Replicas,
InputFiles: options.InputFiles,
OutFile: options.OutFile,
Provider: k.getProvider(options),
CreateD: k.createDeployment(options),
CreateDS: k.createDaemonSet(options),
CreateRC: k.createReplicationController(options),
Build: *options.Build,
BuildRepo: k.buildRepo(options),
BuildBranch: k.buildBranch(options),
PushImage: options.PushImage,
PushImageRegistry: options.PushImageRegistry,
CreateDeploymentConfig: k.createDeploymentConfig(options),
EmptyVols: false,
Profiles: options.Profiles,
Volumes: *options.VolumeType,
PVCRequestSize: options.PvcRequestSize,
InsecureRepository: k.insecureRepository(options),
IsDeploymentFlag: k.createDeployment(options),
IsDaemonSetFlag: k.createDaemonSet(options),
IsReplicationControllerFlag: k.createReplicationController(options),
Controller: k.getController(options),
IsReplicaSetFlag: *options.Replicas != 0,
IsDeploymentConfigFlag: k.createDeploymentConfig(options),
YAMLIndent: 2,
WithKomposeAnnotation: *options.WithKomposeAnnotations,
MultipleContainerMode: k.multiContainerMode(options),
ServiceGroupMode: k.serviceGroupMode(options),
ServiceGroupName: k.serviceGroupName(options),
SecretsAsFiles: k.secretsAsFiles(options),
GenerateNetworkPolicies: options.GenerateNetworkPolicies,
}
err = app.ValidateComposeFile(&kobjectConvertOptions)
if err != nil {
return nil, err
}
objects, err := app.Convert(kobjectConvertOptions)
return objects, err
}
func (k *Kompose) setDefaultValues(options ConvertOptions) ConvertOptions {
replicasDefaultValue := 1
buildDefaultValue := "none"
volumeTypeDefaultValue := "persistentVolumeClaim"
withKomposeAnnotationsDefaultValue := true
kubernetesControllerDefaultValue := ""
kubernetesServiceGroupModeDefaultValue := ""
if options.Replicas == nil {
options.Replicas = &replicasDefaultValue
}
if options.Build == nil {
options.Build = &buildDefaultValue
}
if options.VolumeType == nil {
options.VolumeType = &volumeTypeDefaultValue
}
if options.WithKomposeAnnotations == nil {
options.WithKomposeAnnotations = &withKomposeAnnotationsDefaultValue
}
if options.Provider == nil {
options.Provider = Kubernetes{
Controller: &kubernetesControllerDefaultValue,
}
}
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
if kubernetesProvider.Controller == nil {
options.Provider = Kubernetes{
Controller: &kubernetesControllerDefaultValue,
Chart: options.Provider.(Kubernetes).Chart,
MultiContainerMode: options.Provider.(Kubernetes).MultiContainerMode,
ServiceGroupMode: options.Provider.(Kubernetes).ServiceGroupMode,
ServiceGroupName: options.Provider.(Kubernetes).ServiceGroupName,
SecretsAsFiles: options.Provider.(Kubernetes).SecretsAsFiles,
}
}
if kubernetesProvider.ServiceGroupMode == nil {
options.Provider = Kubernetes{
Controller: options.Provider.(Kubernetes).Controller,
Chart: options.Provider.(Kubernetes).Chart,
MultiContainerMode: options.Provider.(Kubernetes).MultiContainerMode,
ServiceGroupMode: &kubernetesServiceGroupModeDefaultValue,
ServiceGroupName: options.Provider.(Kubernetes).ServiceGroupName,
SecretsAsFiles: options.Provider.(Kubernetes).SecretsAsFiles,
}
}
}
return options
}
func (k *Kompose) validateOptions(options ConvertOptions) error {
build := options.Build
if *build != string(LOCAL) && *build != string(BUILD_CONFIG) && *build != string(NONE) {
return fmt.Errorf(
"unexpected Value for Build field. Possible values are: %v, %v, and %v", string(LOCAL), string(BUILD_CONFIG), string(NONE),
)
}
volumeType := options.VolumeType
if *volumeType != string(PVC) && *volumeType != string(EMPTYDIR) && *volumeType != string(HOSTPATH) && *volumeType != string(CONFIGMAP) {
return fmt.Errorf(
"unexpected Value for VolumeType field. Possible values are: %v, %v, %v, %v", string(PVC), string(EMPTYDIR), string(HOSTPATH), string(CONFIGMAP),
)
}
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
kubernetesController := kubernetesProvider.Controller
if *kubernetesController != "" && *kubernetesController != string(DEPLOYMENT) && *kubernetesController != string(DAEMONSET) && *kubernetesController != string(REPLICATION_CONTROLLER) {
return fmt.Errorf(
"unexpected Value for Kubernetes Controller field. Possible values are: %v, %v, and %v", string(DEPLOYMENT), string(DAEMONSET), string(REPLICATION_CONTROLLER),
)
}
kubernetesServiceGroupMode := kubernetesProvider.ServiceGroupMode
if *kubernetesServiceGroupMode != string(LABEL) && *kubernetesServiceGroupMode != string(VOLUME) && *kubernetesServiceGroupMode != "" {
return fmt.Errorf(
"unexpected Value for Kubernetes Service Groupe Mode field. Possible values are: %v, %v, ''", string(LABEL), string(VOLUME),
)
}
if *build == string(BUILD_CONFIG) {
return fmt.Errorf("the build value %v is only supported for Openshift provider", string(BUILD_CONFIG))
}
}
return nil
}
func (k *Kompose) createDeployment(options ConvertOptions) bool {
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
return *kubernetesProvider.Controller == string(DEPLOYMENT)
}
return false
}
func (k *Kompose) createDaemonSet(options ConvertOptions) bool {
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
return *kubernetesProvider.Controller == string(DAEMONSET)
}
return false
}
func (k *Kompose) createReplicationController(options ConvertOptions) bool {
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
return *kubernetesProvider.Controller == string(REPLICATION_CONTROLLER)
}
return false
}
func (k *Kompose) createChart(options ConvertOptions) bool {
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
return kubernetesProvider.Chart
}
return false
}
func (k *Kompose) multiContainerMode(options ConvertOptions) bool {
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
return kubernetesProvider.MultiContainerMode
}
return false
}
func (k *Kompose) serviceGroupMode(options ConvertOptions) string {
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
return *kubernetesProvider.ServiceGroupMode
}
return ""
}
func (k *Kompose) serviceGroupName(options ConvertOptions) string {
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
return kubernetesProvider.ServiceGroupName
}
return ""
}
func (k *Kompose) secretsAsFiles(options ConvertOptions) bool {
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
return kubernetesProvider.SecretsAsFiles
}
return false
}
func (k *Kompose) createDeploymentConfig(options ConvertOptions) bool {
if _, ok := options.Provider.(Openshift); ok {
return true
}
return false
}
func (k *Kompose) insecureRepository(options ConvertOptions) bool {
if openshiftProvider, ok := options.Provider.(Openshift); ok {
return openshiftProvider.InsecureRepository
}
return false
}
func (k *Kompose) buildRepo(options ConvertOptions) string {
if openshiftProvider, ok := options.Provider.(Openshift); ok {
return openshiftProvider.BuildRepo
}
return ""
}
func (k *Kompose) buildBranch(options ConvertOptions) string {
if openshiftProvider, ok := options.Provider.(Openshift); ok {
return openshiftProvider.BuildRepo
}
return ""
}
func (k *Kompose) getProvider(options ConvertOptions) string {
if _, ok := options.Provider.(Openshift); ok {
return "openshift"
}
if _, ok := options.Provider.(Kubernetes); ok {
return "kubernetes"
}
return "kubernetes"
}
func (k *Kompose) getController(options ConvertOptions) string {
if kubernetesProvider, ok := options.Provider.(Kubernetes); ok {
return *kubernetesProvider.Controller
}
return ""
}
================================================
FILE: client/convert_test.go
================================================
package client
import (
"fmt"
v1 "k8s.io/api/core/v1"
"sort"
"testing"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
appsv1 "k8s.io/api/apps/v1"
)
func TestConvertError(t *testing.T) {
randomBuildValue := "random-build"
randomVolumeTypeValue := "random-volume-type"
randomKubernetesControllerValue := "random-controller"
randomKubernetesServiceGroupModeValue := "random-group-mode"
buildConfigValue := string(BUILD_CONFIG)
testCases := []struct {
options ConvertOptions
errorMessage string
}{
{
options: ConvertOptions{
Build: &randomBuildValue,
},
errorMessage: fmt.Sprintf("unexpected Value for Build field. Possible values are: %v, %v, and %v", string(LOCAL), string(BUILD_CONFIG), string(NONE)),
},
{
options: ConvertOptions{
VolumeType: &randomVolumeTypeValue,
},
errorMessage: fmt.Sprintf("unexpected Value for VolumeType field. Possible values are: %v, %v, %v, %v", string(PVC), string(EMPTYDIR), string(HOSTPATH), string(CONFIGMAP)),
},
{
options: ConvertOptions{
Provider: Kubernetes{
Controller: &randomKubernetesControllerValue,
},
},
errorMessage: fmt.Sprintf("unexpected Value for Kubernetes Controller field. Possible values are: %v, %v, and %v", string(DEPLOYMENT), string(DAEMONSET), string(REPLICATION_CONTROLLER)),
},
{
options: ConvertOptions{
Provider: Kubernetes{
ServiceGroupMode: &randomKubernetesServiceGroupModeValue,
},
},
errorMessage: fmt.Sprintf("unexpected Value for Kubernetes Service Groupe Mode field. Possible values are: %v, %v, ''", string(LABEL), string(VOLUME)),
},
{
options: ConvertOptions{
Provider: Kubernetes{},
Build: &buildConfigValue,
},
errorMessage: fmt.Sprintf("the build value %v is only supported for Openshift provider", string(BUILD_CONFIG)),
},
}
client, err := NewClient()
assert.Check(t, is.Equal(err, nil))
for _, tc := range testCases {
_, err := client.Convert(tc.options)
assert.Check(t, is.Equal(err.Error(), tc.errorMessage))
}
}
func TestConvertWithDefaultOptions(t *testing.T) {
client, err := NewClient(WithErrorOnWarning())
assert.Check(t, is.Equal(err, nil))
objects, err := client.Convert(ConvertOptions{
ToStdout: true,
InputFiles: []string{
"./testdata/docker-compose.yaml",
},
})
assert.Check(t, is.Equal(err, nil))
for _, object := range objects {
if deployment, ok := object.(*appsv1.Deployment); ok {
assert.Check(t, is.Equal(int(*deployment.Spec.Replicas), 1))
}
}
}
func TestConvertWithProfiles(t *testing.T) {
client, err := NewClient(WithErrorOnWarning())
assert.Check(t, is.Equal(err, nil))
type Want struct {
deploymentsNames []string
servicesNames []string
}
tests := []struct {
name string
options ConvertOptions
want Want
}{
{
name: "No profiles provided",
options: ConvertOptions{
ToStdout: true,
InputFiles: []string{
"./testdata/docker-compose-profiles.yaml",
},
},
want: Want{
deploymentsNames: nil,
servicesNames: nil,
},
},
{
name: "All profiles provided",
options: ConvertOptions{
ToStdout: true,
InputFiles: []string{
"./testdata/docker-compose-profiles.yaml",
},
Profiles: []string{"hello", "world"},
},
want: Want{
deploymentsNames: []string{"backend", "frontend", "database"},
servicesNames: []string{"backend", "frontend", "database"},
},
},
{
name: "One profile only",
options: ConvertOptions{
ToStdout: true,
InputFiles: []string{
"./testdata/docker-compose-profiles.yaml",
},
Profiles: []string{"hello"},
},
want: Want{
deploymentsNames: []string{"backend", "frontend"},
servicesNames: []string{"backend", "frontend"},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
objects, err := client.Convert(tt.options)
assert.Check(t, is.Equal(err, nil))
sort.Strings(tt.want.deploymentsNames)
sort.Strings(tt.want.servicesNames)
var deploymentsNames []string
var servicesNames []string
for _, object := range objects {
if deployment, ok := object.(*appsv1.Deployment); ok {
deploymentsNames = append(deploymentsNames, deployment.Name)
}
if service, ok := object.(*v1.Service); ok {
servicesNames = append(servicesNames, service.Name)
}
}
sort.Strings(deploymentsNames)
sort.Strings(servicesNames)
assert.Check(t, is.DeepEqual(deploymentsNames, tt.want.deploymentsNames))
assert.Check(t, is.DeepEqual(servicesNames, tt.want.servicesNames))
})
}
}
================================================
FILE: client/options.go
================================================
package client
// Opt is a configuration option to initialize a client
type Opt func(*Kompose) error
func WithSuppressWarnings() Opt {
return func(k *Kompose) error {
k.suppressWarnings = true
return nil
}
}
func WithVerboseOutput() Opt {
return func(k *Kompose) error {
k.verbose = true
return nil
}
}
func WithErrorOnWarning() Opt {
return func(k *Kompose) error {
k.errorOnWarning = true
return nil
}
}
================================================
FILE: client/options_test.go
================================================
package client
import (
"testing"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
func TestNewClientWithOpts(t *testing.T) {
testCases := []struct {
expectedError error
expectedSuppressWarnings bool
expectedVerbose bool
expectedErrorOnWarnings bool
opts []Opt
}{
{
expectedError: nil,
expectedSuppressWarnings: false,
expectedVerbose: false,
expectedErrorOnWarnings: false,
opts: []Opt{},
},
{
expectedError: nil,
expectedSuppressWarnings: true,
expectedVerbose: false,
expectedErrorOnWarnings: false,
opts: []Opt{WithSuppressWarnings()},
},
{
expectedError: nil,
expectedSuppressWarnings: false,
expectedVerbose: true,
expectedErrorOnWarnings: false,
opts: []Opt{WithVerboseOutput()},
},
{
expectedError: nil,
expectedSuppressWarnings: false,
expectedVerbose: false,
expectedErrorOnWarnings: true,
opts: []Opt{WithErrorOnWarning()},
},
{
expectedError: nil,
expectedSuppressWarnings: true,
expectedVerbose: false,
expectedErrorOnWarnings: true,
opts: []Opt{WithErrorOnWarning(), WithSuppressWarnings()},
},
}
for _, tc := range testCases {
client, err := NewClient(tc.opts...)
assert.Check(t, is.Equal(err, tc.expectedError))
assert.Check(t, is.Equal(client.errorOnWarning, tc.expectedErrorOnWarnings))
assert.Check(t, is.Equal(client.verbose, tc.expectedVerbose))
assert.Check(t, is.Equal(client.suppressWarnings, tc.expectedSuppressWarnings))
}
}
================================================
FILE: client/testdata/docker-compose-profiles.yaml
================================================
version: '3'
services:
backend:
image: dummy:tag
profiles: ['hello', 'world']
ports:
- "80:80"
frontend:
image: dummy:tag
profiles: [ 'hello' ]
ports:
- "80:80"
database:
image: dummy:tag
profiles: [ 'world' ]
ports:
- "80:80"
================================================
FILE: client/testdata/docker-compose.yaml
================================================
version: '3'
services:
web:
image: nginx:latest
ports:
- "80:80"
================================================
FILE: client/types.go
================================================
package client
type ConvertBuild string
const (
LOCAL ConvertBuild = "local"
BUILD_CONFIG ConvertBuild = "build-config"
NONE ConvertBuild = "none"
)
type KubernetesController string
const (
DEPLOYMENT KubernetesController = "deployment"
DAEMONSET KubernetesController = "daemonSet"
REPLICATION_CONTROLLER KubernetesController = "replicationController"
)
type ServiceGroupMode string
const (
LABEL ServiceGroupMode = "label"
VOLUME ServiceGroupMode = "volume"
)
type VolumeType string
const (
PVC = "persistentVolumeClaim"
EMPTYDIR = "emptyDir"
HOSTPATH = "hostPath"
CONFIGMAP = "configMap"
)
type ConvertOptions struct {
Build *string
PushImage bool
PushImageRegistry string
GenerateJson bool
ToStdout bool
OutFile string
Replicas *int
VolumeType *string
PvcRequestSize string
WithKomposeAnnotations *bool
InputFiles []string
Profiles []string
Provider
GenerateNetworkPolicies bool
}
type Provider interface{}
type Kubernetes struct {
Provider
Chart bool
Controller *string
MultiContainerMode bool
ServiceGroupMode *string
ServiceGroupName string
SecretsAsFiles bool
}
type Openshift struct {
Provider
DeploymentConfig bool
InsecureRepository bool
BuildRepo string
BuildBranch string
}
================================================
FILE: cmd/completion.go
================================================
package cmd
import (
"bytes"
"fmt"
"io"
"os"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var completion = &cobra.Command{
Use: "completion SHELL",
Short: "Output shell completion code",
Long: `Generates shell completion code.
Auto completion supports bash, zsh and fish. Output is to STDOUT.
source <(kompose completion bash)
source <(kompose completion zsh)
kompose completion fish | source
Will load the shell completion code.
`,
RunE: func(cmd *cobra.Command, args []string) error {
err := Generate(cmd, args)
if err != nil {
log.Fatalf("Error: %s", err)
}
return nil
},
}
// Generate the appropriate autocompletion file
func Generate(cmd *cobra.Command, args []string) error {
// Check the passed in arguments
if len(args) == 0 {
return fmt.Errorf("shell not specified. ex. kompose completion [bash|zsh|fish]")
}
if len(args) > 1 {
return fmt.Errorf("too many arguments. Expected only the shell type. ex. kompose completion [bash|zsh|fish]")
}
// Generate bash through cobra if selected
switch args[0] {
case "bash":
return cmd.Root().GenBashCompletion(os.Stdout)
case "zsh":
return runCompletionZsh(os.Stdout, cmd.Root())
case "fish":
return runCompletionFish(os.Stdout, cmd.Root())
default:
return fmt.Errorf("not a compatible shell, bash, zsh and fish are only supported")
}
}
func init() {
RootCmd.AddCommand(completion)
}
/*
Fish shell auto-completion support
*/
func runCompletionFish(out io.Writer, kompose *cobra.Command) error {
kompose.GenFishCompletion(out, true)
fishInitialization := `
set -l commands "completion convert help version"
complete -c kompose -f
complete -c kompose -n "not __fish_seen_subcommand_from $commands" -a $commands
complete -c kompose -n "__fish_seen_subcommand_from completion" -a "bash zsh fish"
`
out.Write([]byte(fishInitialization))
return nil
}
/*
This is copied from
https://github.com/kubernetes/kubernetes/blob/ea18d5c32ee7c320fe96dda6b0c757476908e696/pkg/kubectl/cmd/completion.go
in order to generate ZSH completion support.
*/
func runCompletionZsh(out io.Writer, kompose *cobra.Command) error {
zshInitialization := `
#compdef kompose
__kompose_bash_source() {
alias shopt=':'
alias _expand=_bash_expand
alias _complete=_bash_comp
emulate -L sh
setopt kshglob noshglob braceexpand
source "$@"
}
__kompose_type() {
# -t is not supported by zsh
if [ "$1" == "-t" ]; then
shift
# fake Bash 4 to disable "complete -o nospace". Instead
# "compopt +-o nospace" is used in the code to toggle trailing
# spaces. We don't support that, but leave trailing spaces on
# all the time
if [ "$1" = "__kompose_compopt" ]; then
echo builtin
return 0
fi
fi
type "$@"
}
__kompose_compgen() {
local completions w
completions=( $(compgen "$@") ) || return $?
# filter by given word as prefix
while [[ "$1" = -* && "$1" != -- ]]; do
shift
shift
done
if [[ "$1" == -- ]]; then
shift
fi
for w in "${completions[@]}"; do
if [[ "${w}" = "$1"* ]]; then
echo "${w}"
fi
done
}
__kompose_compopt() {
true # don't do anything. Not supported by bashcompinit in zsh
}
__kompose_declare() {
if [ "$1" == "-F" ]; then
whence -w "$@"
else
builtin declare "$@"
fi
}
__kompose_ltrim_colon_completions()
{
if [[ "$1" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then
# Remove colon-word prefix from COMPREPLY items
local colon_word=${1%${1##*:}}
local i=${#COMPREPLY[*]}
while [[ $((--i)) -ge 0 ]]; do
COMPREPLY[$i]=${COMPREPLY[$i]#"$colon_word"}
done
fi
}
__kompose_get_comp_words_by_ref() {
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[${COMP_CWORD}-1]}"
words=("${COMP_WORDS[@]}")
cword=("${COMP_CWORD[@]}")
}
__kompose_filedir() {
local RET OLD_IFS w qw
__debug "_filedir $@ cur=$cur"
if [[ "$1" = \~* ]]; then
# somehow does not work. Maybe, zsh does not call this at all
eval echo "$1"
return 0
fi
OLD_IFS="$IFS"
IFS=$'\n'
if [ "$1" = "-d" ]; then
shift
RET=( $(compgen -d) )
else
RET=( $(compgen -f) )
fi
IFS="$OLD_IFS"
IFS="," __debug "RET=${RET[@]} len=${#RET[@]}"
for w in ${RET[@]}; do
if [[ ! "${w}" = "${cur}"* ]]; then
continue
fi
if eval "[[ \"\${w}\" = *.$1 || -d \"\${w}\" ]]"; then
qw="$(__kompose_quote "${w}")"
if [ -d "${w}" ]; then
COMPREPLY+=("${qw}/")
else
COMPREPLY+=("${qw}")
fi
fi
done
}
__kompose_quote() {
if [[ $1 == \'* || $1 == \"* ]]; then
# Leave out first character
printf %q "${1:1}"
else
printf %q "$1"
fi
}
autoload -U +X bashcompinit && bashcompinit
# use word boundary patterns for BSD or GNU sed
LWORD='[[:<:]]'
RWORD='[[:>:]]'
if sed --help 2>&1 | grep -q GNU; then
LWORD='\<'
RWORD='\>'
fi
__kompose_convert_bash_to_zsh() {
sed \
-e 's/declare -F/whence -w/' \
-e 's/local \([a-zA-Z0-9_]*\)=/local \1; \1=/' \
-e 's/flags+=("\(--.*\)=")/flags+=("\1"); two_word_flags+=("\1")/' \
-e 's/must_have_one_flag+=("\(--.*\)=")/must_have_one_flag+=("\1")/' \
-e "s/${LWORD}_filedir${RWORD}/__kompose_filedir/g" \
-e "s/${LWORD}_get_comp_words_by_ref${RWORD}/__kompose_get_comp_words_by_ref/g" \
-e "s/${LWORD}__ltrim_colon_completions${RWORD}/__kompose_ltrim_colon_completions/g" \
-e "s/${LWORD}compgen${RWORD}/__kompose_compgen/g" \
-e "s/${LWORD}compopt${RWORD}/__kompose_compopt/g" \
-e "s/${LWORD}declare${RWORD}/__kompose_declare/g" \
-e "s/\\\$(type${RWORD}/\$(__kompose_type/g" \
<<'BASH_COMPLETION_EOF'
`
out.Write([]byte(zshInitialization))
buf := new(bytes.Buffer)
kompose.GenBashCompletion(buf)
out.Write(buf.Bytes())
zshTail := `
BASH_COMPLETION_EOF
}
__kompose_bash_source <(__kompose_convert_bash_to_zsh)
`
out.Write([]byte(zshTail))
return nil
}
================================================
FILE: cmd/convert.go
================================================
/*
Copyright 2017 The Kubernetes Authors All rights reserved.
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.
*/
package cmd
import (
"strings"
"github.com/kubernetes/kompose/pkg/app"
"github.com/kubernetes/kompose/pkg/kobject"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// TODO: comment
var (
ConvertOut string
ConvertBuildRepo string
ConvertBuildBranch string
ConvertBuild string
ConvertVolumes string
ConvertPVCRequestSize string
ConvertChart bool
ConvertDeployment bool
ConvertDaemonSet bool
ConvertReplicationController bool
ConvertYaml bool
ConvertJSON bool
ConvertStdout bool
ConvertEmptyVols bool
ConvertInsecureRepo bool
ConvertDeploymentConfig bool
ConvertReplicas int
ConvertController string
ConvertProfiles []string
ConvertPushImage bool
ConvertNamespace string
ConvertPushImageRegistry string
ConvertOpt kobject.ConvertOptions
ConvertYAMLIndent int
GenerateNetworkPolicies bool
UpBuild string
BuildCommand string
PushCommand string
// WithKomposeAnnotation decides if we will add metadata about this convert to resource's annotation.
// default is true.
WithKomposeAnnotation bool
// NoInterpolation decides if we will interpolate environment variables in the compose file.
NoInterpolate bool
// MultipleContainerMode which enables creating multi containers in a single pod is a developing function.
// default is false
MultipleContainerMode bool
ServiceGroupMode string
ServiceGroupName string
// SecretsAsFiles forces secrets to result in files inside a container instead of symlinked directories containing
// files of the same name. This reproduces the behavior of file-based secrets in docker-compose and should probably
// be the default for kompose, but we must keep compatibility with the previous behavior.
// See https://github.com/kubernetes/kompose/issues/1280 for more details.
SecretsAsFiles bool
)
var convertCmd = &cobra.Command{
Use: "convert",
Short: "Convert a Compose file",
Example: ` kompose --file compose.yaml convert
kompose -f first.yaml -f second.yaml convert
kompose --provider openshift --file compose.yaml convert`,
PreRun: func(cmd *cobra.Command, args []string) {
// Check that build-config wasn't passed in with --provider=kubernetes
if GlobalProvider == "kubernetes" && UpBuild == "build-config" {
log.Fatalf("build-config is not a valid --build parameter with provider Kubernetes")
}
// Create the Convert Options.
ConvertOpt = kobject.ConvertOptions{
ToStdout: ConvertStdout,
CreateChart: ConvertChart,
GenerateYaml: ConvertYaml,
GenerateJSON: ConvertJSON,
Replicas: ConvertReplicas,
InputFiles: GlobalFiles,
OutFile: ConvertOut,
Provider: GlobalProvider,
CreateD: ConvertDeployment,
CreateDS: ConvertDaemonSet,
CreateRC: ConvertReplicationController,
Build: ConvertBuild,
BuildRepo: ConvertBuildRepo,
BuildBranch: ConvertBuildBranch,
PushImage: ConvertPushImage,
PushImageRegistry: ConvertPushImageRegistry,
CreateDeploymentConfig: ConvertDeploymentConfig,
EmptyVols: ConvertEmptyVols,
Volumes: ConvertVolumes,
PVCRequestSize: ConvertPVCRequestSize,
InsecureRepository: ConvertInsecureRepo,
IsDeploymentFlag: cmd.Flags().Lookup("deployment").Changed,
IsDaemonSetFlag: cmd.Flags().Lookup("daemon-set").Changed,
IsReplicationControllerFlag: cmd.Flags().Lookup("replication-controller").Changed,
Controller: strings.ToLower(ConvertController),
IsReplicaSetFlag: cmd.Flags().Lookup("replicas").Changed,
IsDeploymentConfigFlag: cmd.Flags().Lookup("deployment-config").Changed,
YAMLIndent: ConvertYAMLIndent,
Profiles: ConvertProfiles,
WithKomposeAnnotation: WithKomposeAnnotation,
NoInterpolate: NoInterpolate,
MultipleContainerMode: MultipleContainerMode,
ServiceGroupMode: ServiceGroupMode,
ServiceGroupName: ServiceGroupName,
SecretsAsFiles: SecretsAsFiles,
GenerateNetworkPolicies: GenerateNetworkPolicies,
BuildCommand: BuildCommand,
PushCommand: PushCommand,
Namespace: ConvertNamespace,
}
if ServiceGroupMode == "" && MultipleContainerMode {
ConvertOpt.ServiceGroupMode = "label"
}
app.ValidateFlags(args, cmd, &ConvertOpt)
// Since ValidateComposeFiles returns an error, let's validate it and output the error appropriately if the validation fails
err := app.ValidateComposeFile(&ConvertOpt)
if err != nil {
log.Fatalf("Error validating compose file: %v", err)
}
},
Run: func(cmd *cobra.Command, args []string) {
app.Convert(ConvertOpt)
},
}
func init() {
// Automatically grab environment variables
viper.AutomaticEnv()
// Kubernetes only
convertCmd.Flags().BoolVarP(&ConvertChart, "chart", "c", false, "Create a Helm chart for converted objects")
convertCmd.Flags().BoolVar(&ConvertDaemonSet, "daemon-set", false, "Generate a Kubernetes daemonset object (deprecated, use --controller instead)")
convertCmd.Flags().BoolVarP(&ConvertDeployment, "deployment", "d", false, "Generate a Kubernetes deployment object (deprecated, use --controller instead)")
convertCmd.Flags().BoolVar(&ConvertReplicationController, "replication-controller", false, "Generate a Kubernetes replication controller object (deprecated, use --controller instead)")
convertCmd.Flags().StringVar(&ConvertController, "controller", "", `Set the output controller ("deployment"|"daemonSet"|"replicationController")`)
convertCmd.Flags().MarkDeprecated("daemon-set", "use --controller")
convertCmd.Flags().MarkDeprecated("deployment", "use --controller")
convertCmd.Flags().MarkDeprecated("replication-controller", "use --controller")
convertCmd.Flags().MarkHidden("chart")
convertCmd.Flags().MarkHidden("daemon-set")
convertCmd.Flags().MarkHidden("replication-controller")
convertCmd.Flags().MarkHidden("deployment")
convertCmd.Flags().BoolVar(&MultipleContainerMode, "multiple-container-mode", false, "Create multiple containers grouped by 'kompose.service.group' label")
convertCmd.Flags().StringVar(&ServiceGroupMode, "service-group-mode", "", "Group multiple service to create single workload by `label`(`kompose.service.group`) or `volume`(shared volumes)")
convertCmd.Flags().StringVar(&ServiceGroupName, "service-group-name", "", "Using with --service-group-mode=volume to specific a final service name for the group")
convertCmd.Flags().MarkDeprecated("multiple-container-mode", "use --service-group-mode=label")
convertCmd.Flags().BoolVar(&SecretsAsFiles, "secrets-as-files", false, "Always convert docker-compose secrets into files instead of symlinked directories")
// OpenShift only
convertCmd.Flags().BoolVar(&ConvertDeploymentConfig, "deployment-config", true, "Generate an OpenShift deploymentconfig object")
convertCmd.Flags().BoolVar(&ConvertInsecureRepo, "insecure-repository", false, "Use an insecure Docker repository for OpenShift ImageStream")
convertCmd.Flags().StringVar(&ConvertBuildRepo, "build-repo", "", "Specify source repository for buildconfig (default remote origin)")
convertCmd.Flags().StringVar(&ConvertBuildBranch, "build-branch", "", "Specify repository branch to use for buildconfig (default master)")
convertCmd.Flags().MarkDeprecated("deployment-config", "use --controller")
convertCmd.Flags().MarkHidden("deployment-config")
convertCmd.Flags().MarkHidden("insecure-repository")
convertCmd.Flags().MarkHidden("build-repo")
convertCmd.Flags().MarkHidden("build-branch")
// Standard between the two
convertCmd.Flags().StringVar(&ConvertBuild, "build", "none", `Set the type of build ("local"|"build-config"(OpenShift only)|"none")`)
convertCmd.Flags().BoolVar(&ConvertPushImage, "push-image", false, "If we should push the docker image we built")
convertCmd.Flags().StringVar(&BuildCommand, "build-command", "", `Set the command used to build the container image, which will override the docker build command. Should be used in conjuction with --push-command flag.`)
convertCmd.Flags().StringVar(&PushCommand, "push-command", "", `Set the command used to push the container image. override the docker push command. Should be used in conjuction with --build-command flag.`)
convertCmd.Flags().StringVar(&ConvertPushImageRegistry, "push-image-registry", "", "Specify registry for pushing image, which will override registry from image name")
convertCmd.Flags().BoolVarP(&ConvertYaml, "yaml", "y", false, "Generate resource files into YAML format")
convertCmd.Flags().MarkDeprecated("yaml", "YAML is the default format now")
convertCmd.Flags().MarkShorthandDeprecated("y", "YAML is the default format now")
convertCmd.Flags().BoolVarP(&ConvertJSON, "json", "j", false, "Generate resource files into JSON format")
convertCmd.Flags().BoolVar(&ConvertStdout, "stdout", false, "Print converted objects to stdout")
convertCmd.Flags().StringVarP(&ConvertOut, "out", "o", "", "Specify a file name or directory to save objects to (if path does not exist, a file will be created)")
convertCmd.Flags().IntVar(&ConvertReplicas, "replicas", 1, "Specify the number of replicas in the generated resource spec")
convertCmd.Flags().StringVar(&ConvertVolumes, "volumes", "persistentVolumeClaim", `Volumes to be generated ("persistentVolumeClaim"|"emptyDir"|"hostPath" | "configMap")`)
convertCmd.Flags().StringVar(&ConvertPVCRequestSize, "pvc-request-size", "", `Specify the size of pvc storage requests in the generated resource spec`)
convertCmd.Flags().StringVarP(&ConvertNamespace, "namespace", "n", "", `Specify the namespace of the generated resources`)
convertCmd.Flags().BoolVar(&GenerateNetworkPolicies, "generate-network-policies", false, "Specify whether to generate network policies or not")
convertCmd.Flags().BoolVar(&WithKomposeAnnotation, "with-kompose-annotation", true, "Add kompose annotations to generated resource")
convertCmd.Flags().BoolVar(&NoInterpolate, "no-interpolate", false, "Keep environment variable names in the Compose file")
// Deprecated commands
convertCmd.Flags().BoolVar(&ConvertEmptyVols, "emptyvols", false, "Use Empty Volumes. Do not generate PVCs")
convertCmd.Flags().MarkDeprecated("emptyvols", "emptyvols has been marked as deprecated. Use --volumes emptyDir")
convertCmd.Flags().IntVar(&ConvertYAMLIndent, "indent", 2, "Spaces length to indent generated yaml files")
convertCmd.Flags().StringArrayVar(&ConvertProfiles, "profile", []string{}, `Specify the profile to use, can use multiple profiles`)
// In order to 'separate' both OpenShift and Kubernetes only flags. A custom help page is created
customHelp := `Usage:{{if .Runnable}}
{{if .HasAvailableFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
{{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
Aliases:
{{.NameAndAliases}}
{{end}}{{if .HasExample}}
Examples:
{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableLocalFlags}}
Kubernetes Flags:
-c, --chart Create a Helm chart for converted objects
--controller Set the output controller ("deployment"|"daemonSet"|"replicationController")
--service-group-mode Group multiple service to create single workload by "label"("kompose.service.group") or "volume"(shared volumes)
--service-group-name Using with --service-group-mode=volume to specific a final service name for the group
OpenShift Flags:
--build-branch Specify repository branch to use for buildconfig (default is current branch name)
--build-repo Specify source repository for buildconfig (default is current branch's remote url)
--insecure-repository Specify to use insecure docker repository while generating Openshift image stream object
Flags:
{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
// Set the help template + add the command to root
convertCmd.SetUsageTemplate(customHelp)
RootCmd.AddCommand(convertCmd)
}
================================================
FILE: cmd/root.go
================================================
/*
Copyright 2017 The Kubernetes Authors All rights reserved.
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.
*/
package cmd
import (
"strings"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
// Logrus hooks
// Hook for error and exit out on warning
type errorOnWarningHook struct{}
func (errorOnWarningHook) Levels() []log.Level {
return []log.Level{log.WarnLevel}
}
func (errorOnWarningHook) Fire(entry *log.Entry) error {
log.Fatalln(entry.Message)
return nil
}
// TODO: comment
var (
GlobalProvider string
GlobalVerbose bool
GlobalSuppressWarnings bool
GlobalErrorOnWarning bool
GlobalFiles []string
)
// RootCmd root level flags and commands
var RootCmd = &cobra.Command{
Use: "kompose",
Short: "A tool helping Compose users move to Kubernetes",
Long: `Kompose is a tool to help users who are familiar with docker-compose move to Kubernetes.`,
Example: ` kompose --file compose.yaml convert
kompose -f first.yaml -f second.yaml convert
kompose --provider openshift --file compose.yaml convert
kompose completion bash`,
SilenceErrors: true,
// PersistentPreRun will be "inherited" by all children and ran before *every* command unless
// the child has overridden the functionality. This functionality was implemented to check / modify
// all global flag calls regardless of app call.
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// Add extra logging when verbosity is passed
if GlobalVerbose {
log.SetLevel(log.DebugLevel)
}
// Disable the timestamp (Kompose is too fast!)
formatter := new(log.TextFormatter)
formatter.DisableTimestamp = true
formatter.ForceColors = true
log.SetFormatter(formatter)
// Set the appropriate suppress warnings and error on warning flags
if GlobalSuppressWarnings {
log.SetLevel(log.ErrorLevel)
} else if GlobalErrorOnWarning {
hook := errorOnWarningHook{}
log.AddHook(hook)
}
// Error out of the user has not chosen Kubernetes or OpenShift
provider := strings.ToLower(GlobalProvider)
if provider != "kubernetes" && provider != "openshift" {
log.Fatalf("%s is an unsupported provider. Supported providers are: 'kubernetes', 'openshift'.", GlobalProvider)
}
v := viper.New()
v.BindEnv("file", "COMPOSE_FILE")
cmd.Flags().VisitAll(func(f *pflag.Flag) {
configName := f.Name
if configName == "file" && !f.Changed && v.IsSet(configName) {
GlobalFiles = v.GetStringSlice(configName)
}
})
},
}
// Execute executes the root level command.
// It returns an error if any.
func Execute() error {
return RootCmd.Execute()
}
func init() {
RootCmd.PersistentFlags().BoolVarP(&GlobalVerbose, "verbose", "v", false, "verbose output")
RootCmd.PersistentFlags().BoolVar(&GlobalSuppressWarnings, "suppress-warnings", false, "Suppress all warnings")
RootCmd.PersistentFlags().BoolVar(&GlobalErrorOnWarning, "error-on-warning", false, "Treat any warning as an error")
RootCmd.PersistentFlags().StringSliceVarP(&GlobalFiles, "file", "f", []string{}, "Specify an alternative compose file")
RootCmd.PersistentFlags().StringVar(&GlobalProvider, "provider", "kubernetes", "Specify a provider. Kubernetes or OpenShift.")
}
================================================
FILE: cmd/version.go
================================================
/*
Copyright 2017 The Kubernetes Authors All rights reserved.
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.
*/
package cmd
import (
"fmt"
"github.com/kubernetes/kompose/pkg/version"
"github.com/spf13/cobra"
)
// versionCmd represents the version command
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version of Kompose",
Run: func(cmd *cobra.Command, args []string) {
// See pkg/version/version.go for more information as to why we use the git commit / hash value
fmt.Println(version.VERSION + " (" + version.GITCOMMIT + ")")
},
}
func init() {
RootCmd.AddCommand(versionCmd)
}
================================================
FILE: code-of-conduct.md
================================================
# Kubernetes Community Code of Conduct
Please refer to our [Kubernetes Community Code of Conduct](https://git.k8s.io/community/code-of-conduct.md)
================================================
FILE: docs/404.html
================================================
---
permalink: /404.html
layout: default
---
404
Page not found :(
The requested page could not be found.
================================================
FILE: docs/CNAME
================================================
kompose.io
================================================
FILE: docs/Gemfile
================================================
source "https://rubygems.org"
# Hello! This is where you manage which Jekyll version is used to run.
# When you want to use a different version, change it below, save the
# file and run `bundle install`. Run Jekyll with `bundle exec`, like so:
#
# bundle exec jekyll serve
#
# This will help ensure the proper Jekyll version is running.
# Happy Jekylling!
gem "jekyll", "~> 4.0.0"
# This is the default theme for new Jekyll sites. You may change this to anything you like.
gem "minima", "~> 2.5"
# If you want to use GitHub Pages, remove the "gem "jekyll"" above and
# uncomment the line below. To upgrade, run `bundle update github-pages`.
# gem "github-pages", group: :jekyll_plugins
# If you have any plugins, put them here!
group :jekyll_plugins do
gem "jekyll-feed", "~> 0.12"
end
# Windows and JRuby does not include zoneinfo files, so bundle the tzinfo-data gem
# and associated library.
install_if -> { RUBY_PLATFORM =~ %r!mingw|mswin|java! } do
gem "tzinfo", "~> 1.2"
gem "tzinfo-data"
end
# Performance-booster for watching directories on Windows
gem "wdm", "~> 0.1.1", :install_if => Gem.win_platform?
gem "jekyll-redirect-from"
================================================
FILE: docs/LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2014-2016 GochoMugo
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to
whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall
be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: docs/README.md
================================================
View the site via:
```sh
bundle exec jekyll serve .
```
And visiting `localhost:4000` on your browser.
================================================
FILE: docs/_config.yml
================================================
title: Kompose
name: Kompose
email: foo@gmail.com
github_page: https://github.com/kubernetes/kompose
slack_page: https://slack.k8s.io
description: >- # this means to ignore newlines until "baseurl:"
Convert your Docker Compose file to Kubernetes or OpenShift
baseurl: "" # the subpath of your site, e.g. /blog
url: "" # the base hostname & protocol for your site, e.g. http://example.com
year: 2024
# Google Analytics number (starts with UA?)
analytics: 12345
instagram: https://www.instagram.com
facebook: https://www.facebook.com
# Build settings
theme: minima
plugins:
- jekyll-feed
================================================
FILE: docs/_data/dates.yml
================================================
- date: "Saturday May 8"
green: 20
yellow: 20
red: 20
- date: "Monday May 17"
green: 20
yellow: 20
red: 20
- date: "Monday May 31"
green: 20
yellow: 20
red: 20
- date: "Monday June 7"
green: 20
yellow: 20
red: 20
- date: "Monday June 14"
green: 20
yellow: 20
red: 20
- date: "Monday June 21"
green: 20
yellow: 20
red: 20
- date: "Monday July 5"
green: 20
yellow: 20
red: 20
- date: "Monday July 19"
green: 20
yellow: 20
red: 20
- date: "Monday July 26"
green: 20
yellow: 20
red: 20
- date: "Monday August 9"
green: 20
yellow: 20
red: 20
- date: "Monday August 16"
green: 20
yellow: 20
red: 20
- date: "Monday August 23"
green: 20
yellow: 20
red: 20
- date: "Monday August 30"
green: 20
yellow: 20
red: 20
- date: "Monday September 13"
green: 20
yellow: 20
red: 20
- date: "Friday September 24"
green: 20
yellow: 20
red: 20
- date: "Monday September 27"
green: 20
yellow: 20
red: 20
- date: "Monday October 4"
green: 20
yellow: 20
red: 20
- date: "Sunday October 10"
green: 20
yellow: 20
red: 20
================================================
FILE: docs/_data/menu.yml
================================================
other_links:
"Installation": "/installation/"
"Getting Started": "/getting-started/"
"User Guide": "/user-guide/"
"Conversion Matrix": "/conversion/"
"Architecture": "/architecture/"
================================================
FILE: docs/_foobar.yml
================================================
dates:
"May 8th 2021"
================================================
FILE: docs/_includes/footer.html
================================================
================================================
FILE: docs/_includes/meta.html
================================================
================================================
FILE: docs/_includes/navbar.html
================================================
================================================
FILE: docs/_layouts/default.html
================================================
{{ site.title }} - {{ page.title }}
{% include meta.html %}