Skip to content

Commit

Permalink
Add support for creating helm packages without needing the helm binary (
Browse files Browse the repository at this point in the history
#72)

Signed-off-by: Paul Czarkowski <username.taken@gmail.com>
Co-authored-by: David J. M. Karlsen <david@davidkarlsen.com>
Co-authored-by: Reinhard Nägele <unguiculus@gmail.com>
  • Loading branch information
3 people authored Aug 27, 2020
1 parent a680ed0 commit be24fd2
Show file tree
Hide file tree
Showing 17 changed files with 640 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ Available Commands:
help Help about any command
index Update Helm repo index.yaml for the given GitHub repo
upload Upload Helm chart packages to GitHub Releases
package Package Helm charts
version Print version information

Flags:
Expand Down
57 changes: 57 additions & 0 deletions cr/cmd/package.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright The Helm 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.

package cmd

import (
"github.com/helm/chart-releaser/pkg/config"
"github.com/helm/chart-releaser/pkg/packager"
"github.com/spf13/cobra"
)

// packageCmd represents the package command
var packageCmd = &cobra.Command{
Use: "package [CHART_PATH] [...]",
Short: "Package Helm charts",
Long: `This command packages a chart into a versioned chart archive file. If a path
is given, this will look at that path for a chart (which must contain a
Chart.yaml file) and then package that directory.
If you wish to use advanced packaging options such as creating signed
packages or updating chart dependencies please use "helm package" instead.`,
RunE: func(cmd *cobra.Command, args []string) error {
var err error
if len(args) == 0 {
args = append(args, ".")
}
config, err := config.LoadConfiguration(cfgFile, cmd, getRequiredPackageArgs())
if err != nil {
return err
}

p := packager.NewPackager(config, args)
return p.CreatePackages()

},
}

func getRequiredPackageArgs() []string {
return []string{"package-path"}
}

func init() {
rootCmd.AddCommand(packageCmd)
packageCmd.Flags().StringP("package-path", "p", ".cr-release-packages", "Path to directory with chart packages")
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ require (
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.6.2
github.com/stretchr/testify v1.5.1
github.com/ulule/deepcopier v0.0.0-20200430083143-45decc6639b6
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
golang.org/x/tools v0.0.0-20200204192400-7124308813f3
helm.sh/helm/v3 v3.1.2
rsc.io/letsencrypt v0.0.3 // indirect
)

exclude (
Expand Down
54 changes: 54 additions & 0 deletions go.sum

Large diffs are not rendered by default.

68 changes: 68 additions & 0 deletions pkg/packager/packager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright The Helm 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.

package packager

import (
"fmt"
"os"
"path/filepath"

"github.com/helm/chart-releaser/pkg/config"
"github.com/ulule/deepcopier"
"helm.sh/helm/v3/pkg/action"
)

// Packager exposes the packager object
type Packager struct {
config *config.Options
paths []string
}

// NewPackager returns a configured Packager
func NewPackager(config *config.Options, paths []string) *Packager {
return &Packager{
config: config,
paths: paths,
}
}

// CreatePackages creates Helm chart packages
func (p *Packager) CreatePackages() error {
var settings map[string]interface{}

helmClient := action.NewPackage()

helmClient.Destination = p.config.PackagePath

for i := 0; i < len(p.paths); i++ {
path, err := filepath.Abs(p.paths[i])
if err != nil {
return err
}
if _, err := os.Stat(p.paths[i]); err != nil {
return err
}
deepcopier.Copy(p.config).To(settings)
packageRun, err := helmClient.Run(path, settings)

if err != nil {
fmt.Printf("Failed to package chart in %s (%s)\n", path, err.Error())
return err
}

fmt.Printf("Successfully packaged chart in %s and saved it to: %s\n", path, packageRun)
}
return nil
}
77 changes: 77 additions & 0 deletions pkg/packager/packager_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright The Helm 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.

package packager

import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"

"github.com/helm/chart-releaser/pkg/config"
)

func TestPackager_CreatePackages(t *testing.T) {
packagePath, _ := ioutil.TempDir(".", "packages")
invalidPackagePath := filepath.Join(packagePath, "bad")
file, _ := os.Create(invalidPackagePath)
defer file.Close()
defer os.RemoveAll(packagePath)
tests := []struct {
name string
chartPath string
packagePath string
error bool
}{
{
"valid-chart-path",
"testdata/test-chart",
packagePath,
false,
},
{
"invalid-package-path",
"testdata/test-chart",
invalidPackagePath,
true,
},
{
"invalid-chart-path",
"testdata/invalid-chart",
packagePath,
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p := &Packager{
paths: strings.Split(tt.chartPath, ","),
config: &config.Options{PackagePath: tt.packagePath},
}
err := p.CreatePackages()

if tt.error {
if err == nil {
t.Error()
}
} else {
if err != nil {
t.Error()
}
}
})
}
}
23 changes: 23 additions & 0 deletions pkg/packager/testdata/test-chart/.helmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Patterns to ignore when building packages.
# This supports shell glob matching, relative path matching, and
# negation (prefixed with !). Only one pattern per line.
.DS_Store
# Common VCS dirs
.git/
.gitignore
.bzr/
.bzrignore
.hg/
.hgignore
.svn/
# Common backup files
*.swp
*.bak
*.tmp
*.orig
*~
# Various IDEs
.project
.idea/
*.tmproj
.vscode/
23 changes: 23 additions & 0 deletions pkg/packager/testdata/test-chart/Chart.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
apiVersion: v2
name: test-chart
description: A Helm chart for Kubernetes

# A chart can be either an 'application' or a 'library' chart.
#
# Application charts are a collection of templates that can be packaged into versioned archives
# to be deployed.
#
# Library charts provide useful utilities or functions for the chart developer. They're included as
# a dependency of application charts to inject those utilities and functions into the rendering
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
type: application

# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
version: 0.1.0

# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.
appVersion: 1.16.0
21 changes: 21 additions & 0 deletions pkg/packager/testdata/test-chart/templates/NOTES.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
1. Get the application URL by running these commands:
{{- if .Values.ingress.enabled }}
{{- range $host := .Values.ingress.hosts }}
{{- range .paths }}
http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ . }}
{{- end }}
{{- end }}
{{- else if contains "NodePort" .Values.service.type }}
export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "test-chart.fullname" . }})
export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
echo http://$NODE_IP:$NODE_PORT
{{- else if contains "LoadBalancer" .Values.service.type }}
NOTE: It may take a few minutes for the LoadBalancer IP to be available.
You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "test-chart.fullname" . }}'
export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "test-chart.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}")
echo http://$SERVICE_IP:{{ .Values.service.port }}
{{- else if contains "ClusterIP" .Values.service.type }}
export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "test-chart.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
echo "Visit http://127.0.0.1:8080 to use your application"
kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:80
{{- end }}
63 changes: 63 additions & 0 deletions pkg/packager/testdata/test-chart/templates/_helpers.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "test-chart.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "test-chart.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "test-chart.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Common labels
*/}}
{{- define "test-chart.labels" -}}
helm.sh/chart: {{ include "test-chart.chart" . }}
{{ include "test-chart.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}

{{/*
Selector labels
*/}}
{{- define "test-chart.selectorLabels" -}}
app.kubernetes.io/name: {{ include "test-chart.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}

{{/*
Create the name of the service account to use
*/}}
{{- define "test-chart.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "test-chart.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
Loading

0 comments on commit be24fd2

Please sign in to comment.