repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/stat_unix.go | internal/fs/stat_unix.go | //go:build !windows && !darwin && !freebsd && !netbsd
package fs
import (
"os"
"syscall"
"time"
)
// extendedStat extracts info into an ExtendedFileInfo for unix based operating systems.
func extendedStat(fi os.FileInfo) *ExtendedFileInfo {
s := fi.Sys().(*syscall.Stat_t)
return &ExtendedFileInfo{
Name: fi.Name(),
Mode: fi.Mode(),
DeviceID: uint64(s.Dev),
Inode: s.Ino,
Links: uint64(s.Nlink),
UID: s.Uid,
GID: s.Gid,
Device: uint64(s.Rdev),
BlockSize: int64(s.Blksize),
Blocks: s.Blocks,
Size: s.Size,
AccessTime: time.Unix(s.Atim.Unix()),
ModTime: time.Unix(s.Mtim.Unix()),
ChangeTime: time.Unix(s.Ctim.Unix()),
}
}
// RecallOnDataAccess checks windows-specific attributes to determine if a file is a cloud-only placeholder.
func (*ExtendedFileInfo) RecallOnDataAccess() (bool, error) {
return false, nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/node_test.go | internal/fs/node_test.go | package fs
import (
"fmt"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/restic"
rtest "github.com/restic/restic/internal/test"
)
func BenchmarkNodeFromFileInfo(t *testing.B) {
tempfile, err := os.CreateTemp(t.TempDir(), "restic-test-temp-")
rtest.OK(t, err)
path := tempfile.Name()
rtest.OK(t, tempfile.Close())
fs := Local{}
f, err := fs.OpenFile(path, O_NOFOLLOW, true)
rtest.OK(t, err)
_, err = f.Stat()
rtest.OK(t, err)
t.ResetTimer()
for i := 0; i < t.N; i++ {
_, err := f.ToNode(false, t.Logf)
rtest.OK(t, err)
}
rtest.OK(t, f.Close())
}
func parseTime(s string) time.Time {
t, err := time.Parse("2006-01-02 15:04:05.999", s)
if err != nil {
panic(err)
}
return t.Local()
}
var nodeTests = []data.Node{
{
Name: "testFile",
Type: data.NodeTypeFile,
Content: restic.IDs{},
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0604,
ModTime: parseTime("2015-05-14 21:07:23.111"),
AccessTime: parseTime("2015-05-14 21:07:24.222"),
ChangeTime: parseTime("2015-05-14 21:07:25.333"),
},
{
Name: "testSuidFile",
Type: data.NodeTypeFile,
Content: restic.IDs{},
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0755 | os.ModeSetuid,
ModTime: parseTime("2015-05-14 21:07:23.111"),
AccessTime: parseTime("2015-05-14 21:07:24.222"),
ChangeTime: parseTime("2015-05-14 21:07:25.333"),
},
{
Name: "testSuidFile2",
Type: data.NodeTypeFile,
Content: restic.IDs{},
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0755 | os.ModeSetgid,
ModTime: parseTime("2015-05-14 21:07:23.111"),
AccessTime: parseTime("2015-05-14 21:07:24.222"),
ChangeTime: parseTime("2015-05-14 21:07:25.333"),
},
{
Name: "testSticky",
Type: data.NodeTypeFile,
Content: restic.IDs{},
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0755 | os.ModeSticky,
ModTime: parseTime("2015-05-14 21:07:23.111"),
AccessTime: parseTime("2015-05-14 21:07:24.222"),
ChangeTime: parseTime("2015-05-14 21:07:25.333"),
},
{
Name: "testDir",
Type: data.NodeTypeDir,
Subtree: nil,
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0750 | os.ModeDir,
ModTime: parseTime("2015-05-14 21:07:23.111"),
AccessTime: parseTime("2015-05-14 21:07:24.222"),
ChangeTime: parseTime("2015-05-14 21:07:25.333"),
},
{
Name: "testSymlink",
Type: data.NodeTypeSymlink,
LinkTarget: "invalid",
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0777 | os.ModeSymlink,
ModTime: parseTime("2015-05-14 21:07:23.111"),
AccessTime: parseTime("2015-05-14 21:07:24.222"),
ChangeTime: parseTime("2015-05-14 21:07:25.333"),
},
// include "testFile" and "testDir" again with slightly different
// metadata, so we can test if CreateAt works with pre-existing files.
{
Name: "testFile",
Type: data.NodeTypeFile,
Content: restic.IDs{},
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0604,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
},
{
Name: "testDir",
Type: data.NodeTypeDir,
Subtree: nil,
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0750 | os.ModeDir,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
},
{
Name: "testXattrFile",
Type: data.NodeTypeFile,
Content: restic.IDs{},
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0604,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
ExtendedAttributes: []data.ExtendedAttribute{
{Name: "user.foo", Value: []byte("bar")},
},
},
{
Name: "testXattrDir",
Type: data.NodeTypeDir,
Subtree: nil,
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0750 | os.ModeDir,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
ExtendedAttributes: []data.ExtendedAttribute{
{Name: "user.foo", Value: []byte("bar")},
},
},
{
Name: "testXattrFileMacOSResourceFork",
Type: data.NodeTypeFile,
Content: restic.IDs{},
UID: uint32(os.Getuid()),
GID: uint32(os.Getgid()),
Mode: 0604,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
ExtendedAttributes: []data.ExtendedAttribute{
{Name: "com.apple.ResourceFork", Value: []byte("bar")},
},
},
}
func TestNodeRestoreAt(t *testing.T) {
for _, ownershipByName := range []bool{false, true} {
tempdir := t.TempDir()
for _, test := range nodeTests {
t.Run("", func(t *testing.T) {
var nodePath string
if test.ExtendedAttributes != nil {
if runtime.GOOS == "windows" {
// In windows extended attributes are case insensitive and windows returns
// the extended attributes in UPPER case.
// Update the tests to use UPPER case xattr names for windows.
extAttrArr := test.ExtendedAttributes
// Iterate through the array using pointers
for i := 0; i < len(extAttrArr); i++ {
extAttrArr[i].Name = strings.ToUpper(extAttrArr[i].Name)
}
}
for _, attr := range test.ExtendedAttributes {
if strings.HasPrefix(attr.Name, "com.apple.") && runtime.GOOS != "darwin" {
t.Skipf("attr %v only relevant on macOS", attr.Name)
}
}
// tempdir might be backed by a filesystem that does not support
// extended attributes
nodePath = test.Name
defer func() {
_ = os.Remove(nodePath)
}()
} else {
nodePath = filepath.Join(tempdir, test.Name)
}
rtest.OK(t, NodeCreateAt(&test, nodePath))
// Restore metadata, restoring all xattrs
rtest.OK(t, NodeRestoreMetadata(&test, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", nodePath, msg)) },
func(_ string) bool { return true }, ownershipByName))
fs := &Local{}
meta, err := fs.OpenFile(nodePath, O_NOFOLLOW, true)
rtest.OK(t, err)
n2, err := meta.ToNode(false, t.Logf)
rtest.OK(t, err)
n3, err := meta.ToNode(true, t.Logf)
rtest.OK(t, err)
rtest.OK(t, meta.Close())
rtest.Assert(t, n2.Equals(*n3), "unexpected node info mismatch %v", cmp.Diff(n2, n3))
rtest.Assert(t, test.Name == n2.Name,
"%v: name doesn't match (%v != %v)", test.Type, test.Name, n2.Name)
rtest.Assert(t, test.Type == n2.Type,
"%v: type doesn't match (%v != %v)", test.Type, test.Type, n2.Type)
rtest.Assert(t, test.Size == n2.Size,
"%v: size doesn't match (%v != %v)", test.Size, test.Size, n2.Size)
if runtime.GOOS != "windows" {
rtest.Assert(t, test.UID == n2.UID,
"%v: UID doesn't match (%v != %v)", test.Type, test.UID, n2.UID)
rtest.Assert(t, test.GID == n2.GID,
"%v: GID doesn't match (%v != %v)", test.Type, test.GID, n2.GID)
if test.Type != data.NodeTypeSymlink {
// On OpenBSD only root can set sticky bit (see sticky(8)).
if runtime.GOOS != "openbsd" && runtime.GOOS != "netbsd" && runtime.GOOS != "solaris" && test.Name == "testSticky" {
rtest.Assert(t, test.Mode == n2.Mode,
"%v: mode doesn't match (0%o != 0%o)", test.Type, test.Mode, n2.Mode)
}
}
}
AssertFsTimeEqual(t, "AccessTime", test.Type, test.AccessTime, n2.AccessTime)
AssertFsTimeEqual(t, "ModTime", test.Type, test.ModTime, n2.ModTime)
if len(n2.ExtendedAttributes) == 0 {
n2.ExtendedAttributes = nil
}
rtest.Assert(t, reflect.DeepEqual(test.ExtendedAttributes, n2.ExtendedAttributes),
"%v: xattrs don't match (%v != %v)", test.Name, test.ExtendedAttributes, n2.ExtendedAttributes)
})
}
}
}
func AssertFsTimeEqual(t *testing.T, label string, nodeType data.NodeType, t1 time.Time, t2 time.Time) {
var equal bool
// Go currently doesn't support setting timestamps of symbolic links on darwin and bsd
if nodeType == data.NodeTypeSymlink {
switch runtime.GOOS {
case "darwin", "freebsd", "openbsd", "netbsd", "solaris":
return
}
}
switch runtime.GOOS {
case "darwin":
// HFS+ timestamps don't support sub-second precision,
// see https://en.wikipedia.org/wiki/Comparison_of_file_systems
diff := int(t1.Sub(t2).Seconds())
equal = diff == 0
default:
equal = t1.Equal(t2)
}
rtest.Assert(t, equal, "%s: %s doesn't match (%v != %v)", label, nodeType, t1, t2)
}
func TestNodeRestoreMetadataError(t *testing.T) {
tempdir := t.TempDir()
node := &nodeTests[0]
nodePath := filepath.Join(tempdir, node.Name)
// This will fail because the target file does not exist
err := NodeRestoreMetadata(node, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", nodePath, msg)) },
func(_ string) bool { return true }, false)
rtest.Assert(t, errors.Is(err, os.ErrNotExist), "failed for an unexpected reason")
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/node_xattr_all_test.go | internal/fs/node_xattr_all_test.go | //go:build darwin || freebsd || netbsd || linux || solaris || windows
package fs
import (
"bytes"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/filter"
rtest "github.com/restic/restic/internal/test"
)
func setAndVerifyXattr(t *testing.T, file string, attrs []data.ExtendedAttribute) {
if runtime.GOOS == "windows" {
// windows seems to convert the xattr name to upper case
for i := range attrs {
attrs[i].Name = strings.ToUpper(attrs[i].Name)
}
}
node := &data.Node{
Type: data.NodeTypeFile,
ExtendedAttributes: attrs,
}
/* restore all xattrs */
rtest.OK(t, nodeRestoreExtendedAttributes(node, file, func(_ string) bool { return true }))
nodeActual := &data.Node{
Type: data.NodeTypeFile,
}
rtest.OK(t, nodeFillExtendedAttributes(nodeActual, file, false, t.Logf))
rtest.Assert(t, nodeActual.Equals(*node), "xattr mismatch got %v expected %v", nodeActual.ExtendedAttributes, node.ExtendedAttributes)
}
func setAndVerifyXattrWithSelectFilter(t *testing.T, file string, testAttr []testXattrToRestore, xattrSelectFilter func(_ string) bool) {
attrs := make([]data.ExtendedAttribute, len(testAttr))
for i := range testAttr {
// windows seems to convert the xattr name to upper case
if runtime.GOOS == "windows" {
testAttr[i].xattr.Name = strings.ToUpper(testAttr[i].xattr.Name)
}
attrs[i] = testAttr[i].xattr
}
node := &data.Node{
Type: data.NodeTypeFile,
ExtendedAttributes: attrs,
}
rtest.OK(t, nodeRestoreExtendedAttributes(node, file, xattrSelectFilter))
nodeActual := &data.Node{
Type: data.NodeTypeFile,
}
rtest.OK(t, nodeFillExtendedAttributes(nodeActual, file, false, t.Logf))
// Check nodeActual to make sure only xattrs we expect are there
for _, testAttr := range testAttr {
xattrFound := false
xattrRestored := false
for _, restoredAttr := range nodeActual.ExtendedAttributes {
if restoredAttr.Name == testAttr.xattr.Name {
xattrFound = true
xattrRestored = bytes.Equal(restoredAttr.Value, testAttr.xattr.Value)
break
}
}
if testAttr.shouldRestore {
rtest.Assert(t, xattrFound, "xattr %s not restored", testAttr.xattr.Name)
rtest.Assert(t, xattrRestored, "xattr %v value not restored", testAttr.xattr)
} else {
rtest.Assert(t, !xattrFound, "xattr %v should not have been restored", testAttr.xattr)
}
}
}
type testXattrToRestore struct {
xattr data.ExtendedAttribute
shouldRestore bool
}
func TestOverwriteXattr(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "file")
rtest.OK(t, os.WriteFile(file, []byte("hello world"), 0o600))
setAndVerifyXattr(t, file, []data.ExtendedAttribute{
{
Name: "user.foo",
Value: []byte("bar"),
},
})
setAndVerifyXattr(t, file, []data.ExtendedAttribute{
{
Name: "user.other",
Value: []byte("some"),
},
})
}
func uppercaseOnWindows(patterns []string) []string {
// windows seems to convert the xattr name to upper case
if runtime.GOOS == "windows" {
out := []string{}
for _, pattern := range patterns {
out = append(out, strings.ToUpper(pattern))
}
return out
}
return patterns
}
func TestOverwriteXattrWithSelectFilter(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "file2")
rtest.OK(t, os.WriteFile(file, []byte("hello world"), 0o600))
noopWarnf := func(_ string, _ ...interface{}) {}
// Set a filter as if the user passed in --include-xattr user.*
xattrSelectFilter1 := func(xattrName string) bool {
shouldInclude, _ := filter.IncludeByPattern(uppercaseOnWindows([]string{"user.*"}), noopWarnf)(xattrName)
return shouldInclude
}
setAndVerifyXattrWithSelectFilter(t, file, []testXattrToRestore{
{
xattr: data.ExtendedAttribute{
Name: "user.foo",
Value: []byte("bar"),
},
shouldRestore: true,
},
{
xattr: data.ExtendedAttribute{
Name: "user.test",
Value: []byte("testxattr"),
},
shouldRestore: true,
},
{
xattr: data.ExtendedAttribute{
Name: "security.other",
Value: []byte("testing"),
},
shouldRestore: false,
},
}, xattrSelectFilter1)
// Set a filter as if the user passed in --include-xattr user.*
xattrSelectFilter2 := func(xattrName string) bool {
shouldInclude, _ := filter.IncludeByPattern(uppercaseOnWindows([]string{"user.o*", "user.comm*"}), noopWarnf)(xattrName)
return shouldInclude
}
setAndVerifyXattrWithSelectFilter(t, file, []testXattrToRestore{
{
xattr: data.ExtendedAttribute{
Name: "user.other",
Value: []byte("some"),
},
shouldRestore: true,
},
{
xattr: data.ExtendedAttribute{
Name: "security.other",
Value: []byte("testing"),
},
shouldRestore: false,
},
{
xattr: data.ExtendedAttribute{
Name: "user.open",
Value: []byte("door"),
},
shouldRestore: true,
},
{
xattr: data.ExtendedAttribute{
Name: "user.common",
Value: []byte("testing"),
},
shouldRestore: true,
},
{
xattr: data.ExtendedAttribute{
Name: "user.bad",
Value: []byte("dontincludeme"),
},
shouldRestore: false,
},
}, xattrSelectFilter2)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/preallocate_other.go | internal/fs/preallocate_other.go | //go:build !linux && !darwin
package fs
import "os"
func PreallocateFile(wr *os.File, size int64) error {
// Maybe truncate can help?
// Windows: This calls SetEndOfFile which preallocates space on disk
return wr.Truncate(size)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/file_windows.go | internal/fs/file_windows.go | package fs
import (
"math/rand"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/restic/restic/internal/data"
"golang.org/x/sys/windows"
)
// fixpath returns an absolute path on windows, so restic can open long file
// names.
func fixpath(name string) string {
abspath, err := filepath.Abs(name)
if err == nil {
// Check if \\?\UNC\ already exist
if strings.HasPrefix(abspath, uncPathPrefix) {
return abspath
}
// Check if \\?\GLOBALROOT exists which marks volume shadow copy snapshots
if strings.HasPrefix(abspath, globalRootPrefix) {
if strings.Count(abspath, `\`) == 5 {
// Append slash if this just a volume name, e.g. `\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopyXX`
// Without the trailing slash any access to the volume itself will fail.
return abspath + string(filepath.Separator)
}
return abspath
}
// Check if \\?\ already exist
if strings.HasPrefix(abspath, extendedPathPrefix) {
return abspath
}
// Check if path starts with \\
if strings.HasPrefix(abspath, `\\`) {
return strings.Replace(abspath, `\\`, uncPathPrefix, 1)
}
// Normal path
return extendedPathPrefix + abspath
}
return name
}
// TempFile creates a temporary file which is marked as delete-on-close
func TempFile(dir, prefix string) (f *os.File, err error) {
// slightly modified implementation of os.CreateTemp(dir, prefix) to allow us to add
// the FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE flags.
// These provide two large benefits:
// FILE_ATTRIBUTE_TEMPORARY tells Windows to keep the file in memory only if possible
// which reduces the amount of unnecessary disk writes.
// FILE_FLAG_DELETE_ON_CLOSE instructs Windows to automatically delete the file once
// all file descriptors are closed.
if dir == "" {
dir = os.TempDir()
}
access := uint32(windows.GENERIC_READ | windows.GENERIC_WRITE)
creation := uint32(windows.CREATE_NEW)
share := uint32(0) // prevent other processes from accessing the file
flags := uint32(windows.FILE_ATTRIBUTE_TEMPORARY | windows.FILE_FLAG_DELETE_ON_CLOSE)
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < 10000; i++ {
randSuffix := strconv.Itoa(int(1e9 + rnd.Intn(1e9)%1e9))[1:]
path := filepath.Join(dir, prefix+randSuffix)
ptr, err := windows.UTF16PtrFromString(path)
if err != nil {
return nil, err
}
h, err := windows.CreateFile(ptr, access, share, nil, creation, flags, 0)
if os.IsExist(err) {
continue
}
return os.NewFile(uintptr(h), path), err
}
// Proper error handling is still to do
return nil, os.ErrExist
}
// Chmod changes the mode of the named file to mode.
func chmod(name string, mode os.FileMode) error {
return os.Chmod(fixpath(name), mode)
}
// clearSystem removes the system attribute from the file.
func clearSystem(path string) error {
return clearAttribute(path, windows.FILE_ATTRIBUTE_SYSTEM)
}
// clearAttribute removes the specified attribute from the file.
func clearAttribute(path string, attribute uint32) error {
ptr, err := windows.UTF16PtrFromString(fixpath(path))
if err != nil {
return err
}
fileAttributes, err := windows.GetFileAttributes(ptr)
if err != nil {
return err
}
if fileAttributes&attribute != 0 {
// Clear the attribute
fileAttributes &= ^attribute
err = windows.SetFileAttributes(ptr, fileAttributes)
if err != nil {
return err
}
}
return nil
}
// openHandleForEA return a file handle for file or dir for setting/getting EAs
func openHandleForEA(nodeType data.NodeType, path string, writeAccess bool) (handle windows.Handle, err error) {
path = fixpath(path)
fileAccess := windows.FILE_READ_EA
if writeAccess {
fileAccess = fileAccess | windows.FILE_WRITE_EA
}
switch nodeType {
case data.NodeTypeFile, data.NodeTypeDir:
utf16Path := windows.StringToUTF16Ptr(path)
handle, err = windows.CreateFile(utf16Path, uint32(fileAccess), 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
default:
return 0, nil
}
return handle, err
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/fs_local_test.go | internal/fs/fs_local_test.go | package fs
import (
"io"
"os"
"path/filepath"
"slices"
"testing"
"github.com/restic/restic/internal/data"
rtest "github.com/restic/restic/internal/test"
)
type fsLocalMetadataTestcase struct {
name string
follow bool
setup func(t *testing.T, path string)
nodeType data.NodeType
}
func TestFSLocalMetadata(t *testing.T) {
for _, test := range []fsLocalMetadataTestcase{
{
name: "file",
setup: func(t *testing.T, path string) {
rtest.OK(t, os.WriteFile(path, []byte("example"), 0o600))
},
nodeType: data.NodeTypeFile,
},
{
name: "directory",
setup: func(t *testing.T, path string) {
rtest.OK(t, os.Mkdir(path, 0o600))
},
nodeType: data.NodeTypeDir,
},
{
name: "symlink",
setup: func(t *testing.T, path string) {
rtest.OK(t, os.Symlink(path+"old", path))
},
nodeType: data.NodeTypeSymlink,
},
{
name: "symlink file",
follow: true,
setup: func(t *testing.T, path string) {
rtest.OK(t, os.WriteFile(path+"file", []byte("example"), 0o600))
rtest.OK(t, os.Symlink(path+"file", path))
},
nodeType: data.NodeTypeFile,
},
} {
runFSLocalTestcase(t, test)
}
}
func runFSLocalTestcase(t *testing.T, test fsLocalMetadataTestcase) {
t.Run(test.name, func(t *testing.T) {
tmp := t.TempDir()
path := filepath.Join(tmp, "item")
test.setup(t, path)
testFs := &Local{}
flags := 0
if !test.follow {
flags |= O_NOFOLLOW
}
f, err := testFs.OpenFile(path, flags, true)
rtest.OK(t, err)
checkMetadata(t, f, path, test.follow, test.nodeType)
rtest.OK(t, f.Close())
})
}
func checkMetadata(t *testing.T, f File, path string, follow bool, nodeType data.NodeType) {
fi, err := f.Stat()
rtest.OK(t, err)
var fi2 os.FileInfo
if follow {
fi2, err = os.Stat(path)
} else {
fi2, err = os.Lstat(path)
}
rtest.OK(t, err)
assertFIEqual(t, fi2, fi)
node, err := f.ToNode(false, t.Logf)
rtest.OK(t, err)
// ModTime is likely unique per file, thus it provides a good indication that it is from the correct file
rtest.Equals(t, fi.ModTime, node.ModTime, "node ModTime")
rtest.Equals(t, nodeType, node.Type, "node Type")
}
func assertFIEqual(t *testing.T, want os.FileInfo, got *ExtendedFileInfo) {
t.Helper()
rtest.Equals(t, want.Name(), got.Name, "Name")
rtest.Equals(t, want.ModTime(), got.ModTime, "ModTime")
rtest.Equals(t, want.Mode(), got.Mode, "Mode")
rtest.Equals(t, want.Size(), got.Size, "Size")
}
func TestFSLocalRead(t *testing.T) {
testFSLocalRead(t, false)
testFSLocalRead(t, true)
}
func testFSLocalRead(t *testing.T, makeReadable bool) {
tmp := t.TempDir()
path := filepath.Join(tmp, "item")
testdata := "example"
rtest.OK(t, os.WriteFile(path, []byte(testdata), 0o600))
f := openReadable(t, path, makeReadable)
checkMetadata(t, f, path, false, data.NodeTypeFile)
data, err := io.ReadAll(f)
rtest.OK(t, err)
rtest.Equals(t, testdata, string(data), "file content mismatch")
rtest.OK(t, f.Close())
}
func openReadable(t *testing.T, path string, useMakeReadable bool) File {
testFs := &Local{}
f, err := testFs.OpenFile(path, O_NOFOLLOW, useMakeReadable)
rtest.OK(t, err)
if useMakeReadable {
// file was opened as metadataOnly. open for reading
rtest.OK(t, f.MakeReadable())
}
return f
}
func TestFSLocalReaddir(t *testing.T) {
testFSLocalReaddir(t, false)
testFSLocalReaddir(t, true)
}
func testFSLocalReaddir(t *testing.T, makeReadable bool) {
tmp := t.TempDir()
path := filepath.Join(tmp, "item")
rtest.OK(t, os.Mkdir(path, 0o700))
entries := []string{"testfile"}
rtest.OK(t, os.WriteFile(filepath.Join(path, entries[0]), []byte("example"), 0o600))
f := openReadable(t, path, makeReadable)
checkMetadata(t, f, path, false, data.NodeTypeDir)
names, err := f.Readdirnames(-1)
rtest.OK(t, err)
slices.Sort(names)
rtest.Equals(t, entries, names, "directory content mismatch")
rtest.OK(t, f.Close())
}
func TestFSLocalReadableRace(t *testing.T) {
tmp := t.TempDir()
path := filepath.Join(tmp, "item")
testdata := "example"
rtest.OK(t, os.WriteFile(path, []byte(testdata), 0o600))
testFs := &Local{}
f, err := testFs.OpenFile(path, O_NOFOLLOW, true)
rtest.OK(t, err)
pathNew := path + "new"
rtest.OK(t, os.Rename(path, pathNew))
err = f.MakeReadable()
if err == nil {
// a file handle based implementation should still work
checkMetadata(t, f, pathNew, false, data.NodeTypeFile)
data, err := io.ReadAll(f)
rtest.OK(t, err)
rtest.Equals(t, testdata, string(data), "file content mismatch")
}
rtest.OK(t, f.Close())
}
func TestFSLocalTypeChange(t *testing.T) {
tmp := t.TempDir()
path := filepath.Join(tmp, "item")
testdata := "example"
rtest.OK(t, os.WriteFile(path, []byte(testdata), 0o600))
testFs := &Local{}
f, err := testFs.OpenFile(path, O_NOFOLLOW, true)
rtest.OK(t, err)
// cache metadata
_, err = f.Stat()
rtest.OK(t, err)
pathNew := path + "new"
// rename instead of unlink to let the test also work on windows
rtest.OK(t, os.Rename(path, pathNew))
rtest.OK(t, os.Mkdir(path, 0o700))
rtest.OK(t, f.MakeReadable())
fi, err := f.Stat()
rtest.OK(t, err)
if !fi.Mode.IsDir() {
// a file handle based implementation should still reference the file
checkMetadata(t, f, pathNew, false, data.NodeTypeFile)
data, err := io.ReadAll(f)
rtest.OK(t, err)
rtest.Equals(t, testdata, string(data), "file content mismatch")
}
// else:
// path-based implementation
// nothing to test here. stat returned the new file type
rtest.OK(t, f.Close())
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/fs_reader_command.go | internal/fs/fs_reader_command.go | package fs
import (
"bufio"
"context"
"fmt"
"io"
"os/exec"
"github.com/restic/restic/internal/errors"
)
// CommandReader wraps a command such that its standard output can be read using
// a io.ReadCloser. Close() waits for the command to terminate, reporting
// any error back to the caller.
type CommandReader struct {
cmd *exec.Cmd
stdout io.ReadCloser
// cmd.Wait() must only be called once. Prevent duplicate executions in
// Read() and Close().
waitHandled bool
// alreadyClosedReadErr is the error that we should return if we try to
// read the pipe again after closing. This works around a Read() call that
// is issued after a previous Read() with `io.EOF` (but some bytes were
// read in the past).
alreadyClosedReadErr error
}
func NewCommandReader(ctx context.Context, args []string, errorOutput func(msg string, args ...interface{})) (*CommandReader, error) {
if len(args) == 0 {
return nil, fmt.Errorf("no command was specified as argument")
}
// Prepare command and stdout
command := exec.CommandContext(ctx, args[0], args[1:]...)
stdout, err := command.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("failed to setup stdout pipe: %w", err)
}
// Use a Go routine to handle the stderr to avoid deadlocks
stderr, err := command.StderrPipe()
if err != nil {
return nil, fmt.Errorf("failed to setup stderr pipe: %w", err)
}
go func() {
sc := bufio.NewScanner(stderr)
for sc.Scan() {
errorOutput("subprocess %v: %v", command.Args[0], sc.Text())
}
}()
if err := command.Start(); err != nil {
return nil, fmt.Errorf("failed to start command: %w", err)
}
return &CommandReader{
cmd: command,
stdout: stdout,
}, nil
}
// Read populate the array with data from the process stdout.
func (fp *CommandReader) Read(p []byte) (int, error) {
if fp.alreadyClosedReadErr != nil {
return 0, fp.alreadyClosedReadErr
}
b, err := fp.stdout.Read(p)
// If the error is io.EOF, the program terminated. We need to check the
// exit code here because, if the program terminated with no output, the
// error in `Close()` is ignored.
if errors.Is(err, io.EOF) {
fp.waitHandled = true
// check if the command terminated successfully, If not return the error.
if errw := fp.wait(); errw != nil {
err = errw
}
}
fp.alreadyClosedReadErr = err
return b, err
}
func (fp *CommandReader) wait() error {
err := fp.cmd.Wait()
if err != nil {
// Use a fatal error to abort the snapshot.
return errors.Fatalf("command failed: %v", err)
}
return nil
}
func (fp *CommandReader) Close() error {
if fp.waitHandled {
return nil
}
return fp.wait()
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/fs_local_unix_test.go | internal/fs/fs_local_unix_test.go | //go:build unix
package fs
import (
"syscall"
"testing"
"github.com/restic/restic/internal/data"
rtest "github.com/restic/restic/internal/test"
)
func TestFSLocalMetadataUnix(t *testing.T) {
for _, test := range []fsLocalMetadataTestcase{
{
name: "socket",
setup: func(t *testing.T, path string) {
fd, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM, 0)
rtest.OK(t, err)
defer func() {
_ = syscall.Close(fd)
}()
addr := &syscall.SockaddrUnix{Name: path}
rtest.OK(t, syscall.Bind(fd, addr))
},
nodeType: data.NodeTypeSocket,
},
{
name: "fifo",
setup: func(t *testing.T, path string) {
rtest.OK(t, mkfifo(path, 0o600))
},
nodeType: data.NodeTypeFifo,
},
// device files can only be created as root
} {
runFSLocalTestcase(t, test)
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/mknod_unix.go | internal/fs/mknod_unix.go | //go:build !freebsd && !windows
package fs
import (
"os"
"golang.org/x/sys/unix"
)
func mknod(path string, mode uint32, dev uint64) error {
err := unix.Mknod(path, mode, int(dev))
if err != nil {
err = &os.PathError{Op: "mknod", Path: path, Err: err}
}
return err
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/ea_windows_test.go | internal/fs/ea_windows_test.go | //go:build windows
package fs
import (
"crypto/rand"
"fmt"
"math/big"
"os"
"path/filepath"
"reflect"
"syscall"
"testing"
"unsafe"
"golang.org/x/sys/windows"
)
// The code below was adapted from github.com/Microsoft/go-winio under MIT license.
// The MIT License (MIT)
// Copyright (c) 2015 Microsoft
// 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.
// The code below was adapted from https://github.com/ambarve/go-winio/blob/a7564fd482feb903f9562a135f1317fd3b480739/ea_test.go
// under MIT license.
var (
testEas = []extendedAttribute{
{Name: "foo", Value: []byte("bar")},
{Name: "fizz", Value: []byte("buzz")},
}
testEasEncoded = []byte{16, 0, 0, 0, 0, 3, 3, 0, 102, 111, 111, 0, 98, 97, 114, 0, 0,
0, 0, 0, 0, 4, 4, 0, 102, 105, 122, 122, 0, 98, 117, 122, 122, 0, 0, 0}
testEasNotPadded = testEasEncoded[0 : len(testEasEncoded)-3]
testEasTruncated = testEasEncoded[0:20]
)
func TestRoundTripEas(t *testing.T) {
b, err := encodeExtendedAttributes(testEas)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(testEasEncoded, b) {
t.Fatalf("Encoded mismatch %v %v", testEasEncoded, b)
}
eas, err := decodeExtendedAttributes(b)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(testEas, eas) {
t.Fatalf("mismatch %+v %+v", testEas, eas)
}
}
func TestEasDontNeedPaddingAtEnd(t *testing.T) {
eas, err := decodeExtendedAttributes(testEasNotPadded)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(testEas, eas) {
t.Fatalf("mismatch %+v %+v", testEas, eas)
}
}
func TestTruncatedEasFailCorrectly(t *testing.T) {
_, err := decodeExtendedAttributes(testEasTruncated)
if err == nil {
t.Fatal("expected error")
}
}
func TestNilEasEncodeAndDecodeAsNil(t *testing.T) {
b, err := encodeExtendedAttributes(nil)
if err != nil {
t.Fatal(err)
}
if len(b) != 0 {
t.Fatal("expected empty")
}
eas, err := decodeExtendedAttributes(nil)
if err != nil {
t.Fatal(err)
}
if len(eas) != 0 {
t.Fatal("expected empty")
}
}
// TestSetFileEa makes sure that the test buffer is actually parsable by NtSetEaFile.
func TestSetFileEa(t *testing.T) {
f, err := os.CreateTemp("", "testea")
if err != nil {
t.Fatal(err)
}
defer func() {
err := os.Remove(f.Name())
if err != nil {
t.Logf("Error removing file %s: %v\n", f.Name(), err)
}
err = f.Close()
if err != nil {
t.Logf("Error closing file %s: %v\n", f.Name(), err)
}
}()
ntdll := syscall.MustLoadDLL("ntdll.dll")
ntSetEaFile := ntdll.MustFindProc("NtSetEaFile")
var iosb [2]uintptr
r, _, _ := ntSetEaFile.Call(f.Fd(),
uintptr(unsafe.Pointer(&iosb[0])),
uintptr(unsafe.Pointer(&testEasEncoded[0])),
uintptr(len(testEasEncoded)))
if r != 0 {
t.Fatalf("NtSetEaFile failed with %08x", r)
}
}
// The code below was refactored from github.com/Microsoft/go-winio/blob/a7564fd482feb903f9562a135f1317fd3b480739/ea_test.go
// under MIT license.
func TestSetGetFileEA(t *testing.T) {
testFilePath, testFile := setupTestFile(t)
testEAs := generateTestEAs(t, 3, testFilePath)
fileHandle := openFile(t, testFilePath, windows.FILE_ATTRIBUTE_NORMAL)
defer testCloseFileHandle(t, testFilePath, testFile, fileHandle)
testSetGetEA(t, testFilePath, fileHandle, testEAs)
}
// The code is new code and reuses code refactored from github.com/Microsoft/go-winio/blob/a7564fd482feb903f9562a135f1317fd3b480739/ea_test.go
// under MIT license.
func TestSetGetFolderEA(t *testing.T) {
testFolderPath := setupTestFolder(t)
testEAs := generateTestEAs(t, 3, testFolderPath)
fileHandle := openFile(t, testFolderPath, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_BACKUP_SEMANTICS)
defer testCloseFileHandle(t, testFolderPath, nil, fileHandle)
testSetGetEA(t, testFolderPath, fileHandle, testEAs)
}
func setupTestFile(t *testing.T) (testFilePath string, testFile *os.File) {
tempDir := t.TempDir()
testFilePath = filepath.Join(tempDir, "testfile.txt")
var err error
if testFile, err = os.Create(testFilePath); err != nil {
t.Fatalf("failed to create temporary file: %s", err)
}
return testFilePath, testFile
}
func setupTestFolder(t *testing.T) string {
tempDir := t.TempDir()
testfolderPath := filepath.Join(tempDir, "testfolder")
if err := os.Mkdir(testfolderPath, os.ModeDir); err != nil {
t.Fatalf("failed to create temporary folder: %s", err)
}
return testfolderPath
}
func generateTestEAs(t *testing.T, nAttrs int, path string) []extendedAttribute {
testEAs := make([]extendedAttribute, nAttrs)
for i := 0; i < nAttrs; i++ {
testEAs[i].Name = fmt.Sprintf("TESTEA%d", i+1)
testEAs[i].Value = make([]byte, getRandomInt())
if _, err := rand.Read(testEAs[i].Value); err != nil {
t.Logf("Error reading rand for path %s: %v\n", path, err)
}
}
return testEAs
}
func getRandomInt() int64 {
nBig, err := rand.Int(rand.Reader, big.NewInt(27))
if err != nil {
panic(err)
}
n := nBig.Int64()
if n == 0 {
n = getRandomInt()
}
return n
}
func openFile(t *testing.T, path string, attributes uint32) windows.Handle {
utf16Path := windows.StringToUTF16Ptr(path)
fileAccessRightReadWriteEA := uint32(0x8 | 0x10)
fileHandle, err := windows.CreateFile(utf16Path, fileAccessRightReadWriteEA, 0, nil, windows.OPEN_EXISTING, attributes, 0)
if err != nil {
t.Fatalf("open file failed with: %s", err)
}
return fileHandle
}
func testCloseFileHandle(t *testing.T, testfilePath string, testFile *os.File, handle windows.Handle) {
if testFile != nil {
err := testFile.Close()
if err != nil {
t.Logf("Error closing file %s: %v\n", testFile.Name(), err)
}
}
if err := windows.Close(handle); err != nil {
t.Logf("Error closing file handle %s: %v\n", testfilePath, err)
}
cleanupTestFile(t, testfilePath)
}
func cleanupTestFile(t *testing.T, path string) {
if err := os.Remove(path); err != nil {
t.Logf("Error removing file/folder %s: %v\n", path, err)
}
}
func testSetGetEA(t *testing.T, path string, handle windows.Handle, testEAs []extendedAttribute) {
if err := fsetEA(handle, testEAs); err != nil {
t.Fatalf("set EA for path %s failed: %s", path, err)
}
readEAs, err := fgetEA(handle)
if err != nil {
t.Fatalf("get EA for path %s failed: %s", path, err)
}
if !reflect.DeepEqual(readEAs, testEAs) {
t.Logf("expected: %+v, found: %+v\n", testEAs, readEAs)
t.Fatalf("EAs read from path %s don't match", path)
}
}
func TestPathSupportsExtendedAttributes(t *testing.T) {
testCases := []struct {
name string
path string
expected bool
}{
{
name: "System drive",
path: os.Getenv("SystemDrive") + `\`,
expected: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
supported, err := pathSupportsExtendedAttributes(tc.path)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if supported != tc.expected {
t.Errorf("Expected %v, got %v for path %s", tc.expected, supported, tc.path)
}
})
}
// Test with an invalid path
_, err := pathSupportsExtendedAttributes("Z:\\NonExistentPath-UAS664da5s4dyu56das45f5as")
if err == nil {
t.Error("Expected an error for non-existent path, but got nil")
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/node_unix_notlinux.go | internal/fs/node_unix_notlinux.go | //go:build !linux && unix
package fs
import (
"syscall"
"github.com/restic/restic/internal/data"
)
// utimesNano is like syscall.UtimesNano, except that it skips symlinks.
func utimesNano(path string, atime, mtime int64, typ data.NodeType) error {
if typ == data.NodeTypeSymlink {
return nil
}
return syscall.UtimesNano(path, []syscall.Timespec{
syscall.NsecToTimespec(atime),
syscall.NsecToTimespec(mtime),
})
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/const.go | internal/fs/const.go | package fs
import "syscall"
// Flags to OpenFile wrapping those of the underlying system. Not all flags may
// be implemented on a given system.
const (
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened.
O_NONBLOCK int = syscall.O_NONBLOCK // don't block open on fifos etc.
)
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/node_windows.go | internal/fs/node_windows.go | package fs
import (
"encoding/json"
"fmt"
"path/filepath"
"reflect"
"strings"
"sync"
"syscall"
"unsafe"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/errors"
"golang.org/x/sys/windows"
)
var (
modAdvapi32 = syscall.NewLazyDLL("advapi32.dll")
procEncryptFile = modAdvapi32.NewProc("EncryptFileW")
procDecryptFile = modAdvapi32.NewProc("DecryptFileW")
// eaSupportedVolumesMap is a map of volumes to boolean values indicating if they support extended attributes.
eaSupportedVolumesMap = sync.Map{}
)
const (
extendedPathPrefix = `\\?\`
uncPathPrefix = `\\?\UNC\`
globalRootPrefix = `\\?\GLOBALROOT\`
volumeGUIDPrefix = `\\?\Volume{`
)
// mknod is not supported on Windows.
func mknod(_ string, _ uint32, _ uint64) (err error) {
return errors.New("device nodes cannot be created on windows")
}
// Windows doesn't need lchown
func lchown(_ string, _ *data.Node, _ bool) (err error) {
return nil
}
// utimesNano is like syscall.UtimesNano, except that it sets FILE_FLAG_OPEN_REPARSE_POINT.
func utimesNano(path string, atime, mtime int64, _ data.NodeType) error {
// tweaked version of UtimesNano from go/src/syscall/syscall_windows.go
pathp, e := syscall.UTF16PtrFromString(fixpath(path))
if e != nil {
return e
}
h, e := syscall.CreateFile(pathp,
syscall.FILE_WRITE_ATTRIBUTES, syscall.FILE_SHARE_WRITE, nil, syscall.OPEN_EXISTING,
syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, 0)
if e != nil {
return e
}
defer func() {
err := syscall.Close(h)
if err != nil {
debug.Log("Error closing file handle for %s: %v\n", path, err)
}
}()
a := syscall.NsecToFiletime(atime)
w := syscall.NsecToFiletime(mtime)
return syscall.SetFileTime(h, nil, &a, &w)
}
// restore extended attributes for windows
func nodeRestoreExtendedAttributes(node *data.Node, path string, xattrSelectFilter func(xattrName string) bool) error {
count := len(node.ExtendedAttributes)
if count > 0 {
eas := []extendedAttribute{}
for _, attr := range node.ExtendedAttributes {
// Filter for xattrs we want to include/exclude
if xattrSelectFilter(attr.Name) {
eas = append(eas, extendedAttribute{Name: attr.Name, Value: attr.Value})
}
}
if len(eas) > 0 {
if errExt := restoreExtendedAttributes(node.Type, path, eas); errExt != nil {
return errExt
}
}
}
return nil
}
// fill extended attributes in the node
// It also checks if the volume supports extended attributes and stores the result in a map
// so that it does not have to be checked again for subsequent calls for paths in the same volume.
func nodeFillExtendedAttributes(node *data.Node, path string, _ bool, _ func(format string, args ...any)) (err error) {
if strings.Contains(filepath.Base(path), ":") {
// Do not process for Alternate Data Streams in Windows
return nil
}
// only capture xattrs for file/dir
if node.Type != data.NodeTypeFile && node.Type != data.NodeTypeDir {
return nil
}
allowExtended, err := checkAndStoreEASupport(path)
if err != nil {
return err
}
if !allowExtended {
return nil
}
var fileHandle windows.Handle
if fileHandle, err = openHandleForEA(node.Type, path, false); fileHandle == 0 {
return nil
}
if err != nil {
return errors.Errorf("get EA failed while opening file handle for path %v, with: %v", path, err)
}
defer closeFileHandle(fileHandle, path) // Replaced inline defer with named function call
//Get the windows Extended Attributes using the file handle
var extAtts []extendedAttribute
extAtts, err = fgetEA(fileHandle)
debug.Log("fillExtendedAttributes(%v) %v", path, extAtts)
if err != nil {
return errors.Errorf("get EA failed for path %v, with: %v", path, err)
}
if len(extAtts) == 0 {
return nil
}
//Fill the ExtendedAttributes in the node using the name/value pairs in the windows EA
for _, attr := range extAtts {
extendedAttr := data.ExtendedAttribute{
Name: attr.Name,
Value: attr.Value,
}
node.ExtendedAttributes = append(node.ExtendedAttributes, extendedAttr)
}
return nil
}
// closeFileHandle safely closes a file handle and logs any errors.
func closeFileHandle(fileHandle windows.Handle, path string) {
err := windows.CloseHandle(fileHandle)
if err != nil {
debug.Log("Error closing file handle for %s: %v\n", path, err)
}
}
// restoreExtendedAttributes handles restore of the Windows Extended Attributes to the specified path.
// The Windows API requires setting of all the Extended Attributes in one call.
func restoreExtendedAttributes(nodeType data.NodeType, path string, eas []extendedAttribute) (err error) {
var fileHandle windows.Handle
if fileHandle, err = openHandleForEA(nodeType, path, true); fileHandle == 0 {
return nil
}
if err != nil {
return errors.Errorf("set EA failed while opening file handle for path %v, with: %v", path, err)
}
defer closeFileHandle(fileHandle, path) // Replaced inline defer with named function call
// clear old unexpected xattrs by setting them to an empty value
oldEAs, err := fgetEA(fileHandle)
if err != nil {
return err
}
for _, oldEA := range oldEAs {
found := false
for _, ea := range eas {
if strings.EqualFold(ea.Name, oldEA.Name) {
found = true
break
}
}
if !found {
eas = append(eas, extendedAttribute{Name: oldEA.Name, Value: nil})
}
}
if err = fsetEA(fileHandle, eas); err != nil {
return errors.Errorf("set EA failed for path %v, with: %v", path, err)
}
return nil
}
// restoreGenericAttributes restores generic attributes for Windows
func nodeRestoreGenericAttributes(node *data.Node, path string, warn func(msg string)) (err error) {
if len(node.GenericAttributes) == 0 {
return nil
}
var errs []error
windowsAttributes, unknownAttribs, err := genericAttributesToWindowsAttrs(node.GenericAttributes)
if err != nil {
return fmt.Errorf("error parsing generic attribute for: %s : %v", path, err)
}
if windowsAttributes.CreationTime != nil {
if err := restoreCreationTime(path, windowsAttributes.CreationTime); err != nil {
errs = append(errs, fmt.Errorf("error restoring creation time for: %s : %v", path, err))
}
}
if windowsAttributes.FileAttributes != nil {
if err := restoreFileAttributes(path, windowsAttributes.FileAttributes); err != nil {
errs = append(errs, fmt.Errorf("error restoring file attributes for: %s : %v", path, err))
}
}
if windowsAttributes.SecurityDescriptor != nil {
if err := setSecurityDescriptor(path, windowsAttributes.SecurityDescriptor); err != nil {
errs = append(errs, fmt.Errorf("error restoring security descriptor for: %s : %v", path, err))
}
}
data.HandleUnknownGenericAttributesFound(unknownAttribs, warn)
return errors.Join(errs...)
}
// genericAttributesToWindowsAttrs converts the generic attributes map to a WindowsAttributes and also returns a string of unknown attributes that it could not convert.
func genericAttributesToWindowsAttrs(attrs map[data.GenericAttributeType]json.RawMessage) (windowsAttributes data.WindowsAttributes, unknownAttribs []data.GenericAttributeType, err error) {
waValue := reflect.ValueOf(&windowsAttributes).Elem()
unknownAttribs, err = data.GenericAttributesToOSAttrs(attrs, reflect.TypeOf(windowsAttributes), &waValue, "windows")
return windowsAttributes, unknownAttribs, err
}
// restoreCreationTime gets the creation time from the data and sets it to the file/folder at
// the specified path.
func restoreCreationTime(path string, creationTime *syscall.Filetime) (err error) {
pathPointer, err := syscall.UTF16PtrFromString(fixpath(path))
if err != nil {
return err
}
handle, err := syscall.CreateFile(pathPointer,
syscall.FILE_WRITE_ATTRIBUTES, syscall.FILE_SHARE_WRITE, nil,
syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0)
if err != nil {
return err
}
defer func() {
if err := syscall.Close(handle); err != nil {
debug.Log("Error closing file handle for %s: %v\n", path, err)
}
}()
return syscall.SetFileTime(handle, creationTime, nil, nil)
}
// restoreFileAttributes gets the File Attributes from the data and sets them to the file/folder
// at the specified path.
func restoreFileAttributes(path string, fileAttributes *uint32) (err error) {
pathPointer, err := syscall.UTF16PtrFromString(fixpath(path))
if err != nil {
return err
}
err = fixEncryptionAttribute(path, fileAttributes, pathPointer)
if err != nil {
debug.Log("Could not change encryption attribute for path: %s: %v", path, err)
}
return syscall.SetFileAttributes(pathPointer, *fileAttributes)
}
// fixEncryptionAttribute checks if a file needs to be marked encrypted and is not already encrypted, it sets
// the FILE_ATTRIBUTE_ENCRYPTED. Conversely, if the file needs to be marked unencrypted and it is already
// marked encrypted, it removes the FILE_ATTRIBUTE_ENCRYPTED.
func fixEncryptionAttribute(path string, attrs *uint32, pathPointer *uint16) (err error) {
if *attrs&windows.FILE_ATTRIBUTE_ENCRYPTED != 0 {
// File should be encrypted.
err = encryptFile(pathPointer)
if err != nil {
if IsAccessDenied(err) || errors.Is(err, windows.ERROR_FILE_READ_ONLY) {
// If existing file already has readonly or system flag, encrypt file call fails.
// The readonly and system flags will be set again at the end of this func if they are needed.
err = ResetPermissions(path)
if err != nil {
return fmt.Errorf("failed to encrypt file: failed to reset permissions: %s : %v", path, err)
}
err = clearSystem(path)
if err != nil {
return fmt.Errorf("failed to encrypt file: failed to clear system flag: %s : %v", path, err)
}
err = encryptFile(pathPointer)
if err != nil {
return fmt.Errorf("failed retry to encrypt file: %s : %v", path, err)
}
} else {
return fmt.Errorf("failed to encrypt file: %s : %v", path, err)
}
}
} else {
existingAttrs, err := windows.GetFileAttributes(pathPointer)
if err != nil {
return fmt.Errorf("failed to get file attributes for existing file: %s : %v", path, err)
}
if existingAttrs&windows.FILE_ATTRIBUTE_ENCRYPTED != 0 {
// File should not be encrypted, but its already encrypted. Decrypt it.
err = decryptFile(pathPointer)
if err != nil {
if IsAccessDenied(err) || errors.Is(err, windows.ERROR_FILE_READ_ONLY) {
// If existing file already has readonly or system flag, decrypt file call fails.
// The readonly and system flags will be set again after this func if they are needed.
err = ResetPermissions(path)
if err != nil {
return fmt.Errorf("failed to encrypt file: failed to reset permissions: %s : %v", path, err)
}
err = clearSystem(path)
if err != nil {
return fmt.Errorf("failed to decrypt file: failed to clear system flag: %s : %v", path, err)
}
err = decryptFile(pathPointer)
if err != nil {
return fmt.Errorf("failed retry to decrypt file: %s : %v", path, err)
}
} else {
return fmt.Errorf("failed to decrypt file: %s : %v", path, err)
}
}
}
}
return err
}
// encryptFile set the encrypted flag on the file.
func encryptFile(pathPointer *uint16) error {
// Call EncryptFile function
ret, _, err := procEncryptFile.Call(uintptr(unsafe.Pointer(pathPointer)))
if ret == 0 {
return err
}
return nil
}
// decryptFile removes the encrypted flag from the file.
func decryptFile(pathPointer *uint16) error {
// Call DecryptFile function
ret, _, err := procDecryptFile.Call(uintptr(unsafe.Pointer(pathPointer)))
if ret == 0 {
return err
}
return nil
}
// nodeFillGenericAttributes fills in the generic attributes for windows like File Attributes,
// Created time and Security Descriptors.
func nodeFillGenericAttributes(node *data.Node, path string, stat *ExtendedFileInfo) error {
if strings.Contains(filepath.Base(path), ":") {
// Do not process for Alternate Data Streams in Windows
return nil
}
isVolume, err := isVolumePath(path)
if err != nil {
return err
}
if isVolume {
// Do not process file attributes, created time and sd for windows root volume paths
// Security descriptors are not supported for root volume paths.
// Though file attributes and created time are supported for root volume paths,
// we ignore them and we do not want to replace them during every restore.
return nil
}
var sd *[]byte
if node.Type == data.NodeTypeFile || node.Type == data.NodeTypeDir {
if sd, err = getSecurityDescriptor(path); err != nil {
return err
}
}
winFI := stat.sys.(*syscall.Win32FileAttributeData)
// Add Windows attributes
node.GenericAttributes, err = data.WindowsAttrsToGenericAttributes(data.WindowsAttributes{
CreationTime: &winFI.CreationTime,
FileAttributes: &winFI.FileAttributes,
SecurityDescriptor: sd,
})
return err
}
// checkAndStoreEASupport checks if the volume of the path supports extended attributes and stores the result in a map
// If the result is already in the map, it returns the result from the map.
func checkAndStoreEASupport(path string) (isEASupportedVolume bool, err error) {
var volumeName string
volumeName, err = prepareVolumeName(path)
if err != nil {
return false, err
}
if volumeName != "" {
// First check if the manually prepared volume name is already in the map
eaSupportedValue, exists := eaSupportedVolumesMap.Load(volumeName)
if exists {
// Cache hit, immediately return the cached value
return eaSupportedValue.(bool), nil
}
// If not found, check if EA is supported with manually prepared volume name
isEASupportedVolume, err = pathSupportsExtendedAttributes(volumeName + `\`)
// If the prepared volume name is not valid, we will fetch the actual volume name next.
if err != nil && !errors.Is(err, windows.DNS_ERROR_INVALID_NAME) {
debug.Log("Error checking if extended attributes are supported for prepared volume name %s: %v", volumeName, err)
// There can be multiple errors like path does not exist, bad network path, etc.
// We just gracefully disallow extended attributes for cases.
return false, nil
}
}
// If an entry is not found, get the actual volume name
volumeNameActual, err := getVolumePathName(path)
if err != nil {
debug.Log("Error getting actual volume name %s for path %s: %v", volumeName, path, err)
// There can be multiple errors like path does not exist, bad network path, etc.
// We just gracefully disallow extended attributes for cases.
return false, nil
}
if volumeNameActual != volumeName {
// If the actual volume name is different, check cache for the actual volume name
eaSupportedValue, exists := eaSupportedVolumesMap.Load(volumeNameActual)
if exists {
// Cache hit, immediately return the cached value
return eaSupportedValue.(bool), nil
}
// If the actual volume name is different and is not in the map, again check if the new volume supports extended attributes with the actual volume name
isEASupportedVolume, err = pathSupportsExtendedAttributes(volumeNameActual + `\`)
// Debug log for cases where the prepared volume name is not valid
if err != nil {
debug.Log("Error checking if extended attributes are supported for actual volume name %s: %v", volumeNameActual, err)
// There can be multiple errors like path does not exist, bad network path, etc.
// We just gracefully disallow extended attributes for cases.
return false, nil
} else {
debug.Log("Checking extended attributes. Prepared volume name: %s, actual volume name: %s, isEASupportedVolume: %v, err: %v", volumeName, volumeNameActual, isEASupportedVolume, err)
}
}
if volumeNameActual != "" {
eaSupportedVolumesMap.Store(volumeNameActual, isEASupportedVolume)
}
return isEASupportedVolume, err
}
// getVolumePathName returns the volume path name for the given path.
func getVolumePathName(path string) (volumeName string, err error) {
utf16Path, err := windows.UTF16PtrFromString(path)
if err != nil {
return "", err
}
// Get the volume path (e.g., "D:")
var volumePath [windows.MAX_PATH + 1]uint16
err = windows.GetVolumePathName(utf16Path, &volumePath[0], windows.MAX_PATH+1)
if err != nil {
return "", err
}
// Trim any trailing backslashes
volumeName = strings.TrimRight(windows.UTF16ToString(volumePath[:]), "\\")
return volumeName, nil
}
// isVolumePath returns whether a path refers to a volume
func isVolumePath(path string) (bool, error) {
volName, err := prepareVolumeName(path)
if err != nil {
return false, err
}
cleanPath := filepath.Clean(path)
cleanVolume := filepath.Clean(volName + `\`)
return cleanPath == cleanVolume, nil
}
// prepareVolumeName prepares the volume name for different cases in Windows
func prepareVolumeName(path string) (volumeName string, err error) {
// Check if it's an extended length path
if strings.HasPrefix(path, globalRootPrefix) {
// Extract the VSS snapshot volume name eg. `\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopyXX`
if parts := strings.SplitN(path, `\`, 7); len(parts) >= 6 {
volumeName = strings.Join(parts[:6], `\`)
} else {
volumeName = filepath.VolumeName(path)
}
} else {
if !strings.HasPrefix(path, volumeGUIDPrefix) { // Handle volume GUID path
if strings.HasPrefix(path, uncPathPrefix) {
// Convert \\?\UNC\ extended path to standard path to get the volume name correctly
path = `\\` + path[len(uncPathPrefix):]
} else if strings.HasPrefix(path, extendedPathPrefix) {
//Extended length path prefix needs to be trimmed to get the volume name correctly
path = path[len(extendedPathPrefix):]
} else {
// Use the absolute path
path, err = filepath.Abs(path)
if err != nil {
return "", fmt.Errorf("failed to get absolute path: %w", err)
}
}
}
volumeName = filepath.VolumeName(path)
}
return volumeName, nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/stat_darwin.go | internal/fs/stat_darwin.go | //go:build darwin
package fs
import (
"fmt"
"os"
"syscall"
"time"
"golang.org/x/sys/unix"
)
// extendedStat extracts info into an ExtendedFileInfo for macOS.
func extendedStat(fi os.FileInfo) *ExtendedFileInfo {
s := fi.Sys().(*syscall.Stat_t)
return &ExtendedFileInfo{
Name: fi.Name(),
Mode: fi.Mode(),
DeviceID: uint64(s.Dev),
Inode: uint64(s.Ino),
Links: uint64(s.Nlink),
UID: s.Uid,
GID: s.Gid,
Device: uint64(s.Rdev),
BlockSize: int64(s.Blksize),
Blocks: s.Blocks,
Size: s.Size,
AccessTime: time.Unix(s.Atimespec.Unix()),
ModTime: time.Unix(s.Mtimespec.Unix()),
ChangeTime: time.Unix(s.Ctimespec.Unix()),
sys: s,
}
}
// RecallOnDataAccess checks if a file is available locally on the disk or if the file is
// just a dataless files which must be downloaded from a remote server. This is typically used
// in cloud syncing services (e.g. iCloud drive) to prevent downloading files from cloud storage
// until they are accessed.
func (fi *ExtendedFileInfo) RecallOnDataAccess() (bool, error) {
extAttribute, ok := fi.sys.(*syscall.Stat_t)
if !ok {
return false, fmt.Errorf("could not determine file attributes: %s", fi.Name)
}
const mask uint32 = unix.SF_DATALESS // 0x40000000
if extAttribute.Flags&mask == mask {
return true, nil
}
return false, nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/sd_windows_test.go | internal/fs/sd_windows_test.go | //go:build windows
package fs
import (
"encoding/base64"
"os"
"path/filepath"
"testing"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/test"
)
func TestSetGetFileSecurityDescriptors(t *testing.T) {
tempDir := t.TempDir()
testfilePath := filepath.Join(tempDir, "testfile.txt")
// create temp file
testfile, err := os.Create(testfilePath)
if err != nil {
t.Fatalf("failed to create temporary file: %s", err)
}
defer func() {
err := testfile.Close()
if err != nil {
t.Logf("Error closing file %s: %v\n", testfilePath, err)
}
}()
testSecurityDescriptors(t, testFileSDs, testfilePath)
}
func TestSetGetFolderSecurityDescriptors(t *testing.T) {
tempDir := t.TempDir()
testfolderPath := filepath.Join(tempDir, "testfolder")
// create temp folder
err := os.Mkdir(testfolderPath, os.ModeDir)
if err != nil {
t.Fatalf("failed to create temporary file: %s", err)
}
testSecurityDescriptors(t, testDirSDs, testfolderPath)
}
func testSecurityDescriptors(t *testing.T, testSDs []string, testPath string) {
for _, testSD := range testSDs {
sdInputBytes, err := base64.StdEncoding.DecodeString(testSD)
test.OK(t, errors.Wrapf(err, "Error decoding SD: %s", testPath))
err = setSecurityDescriptor(testPath, &sdInputBytes)
test.OK(t, errors.Wrapf(err, "Error setting file security descriptor for: %s", testPath))
var sdOutputBytes *[]byte
sdOutputBytes, err = getSecurityDescriptor(testPath)
test.OK(t, errors.Wrapf(err, "Error getting file security descriptor for: %s", testPath))
compareSecurityDescriptors(t, testPath, sdInputBytes, *sdOutputBytes)
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/node_windows_test.go | internal/fs/node_windows_test.go | //go:build windows
package fs
import (
"encoding/base64"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/test"
"golang.org/x/sys/windows"
)
func TestRestoreSecurityDescriptors(t *testing.T) {
t.Parallel()
tempDir := t.TempDir()
for i, sd := range testFileSDs {
testRestoreSecurityDescriptor(t, sd, tempDir, data.NodeTypeFile, fmt.Sprintf("testfile%d", i))
}
for i, sd := range testDirSDs {
testRestoreSecurityDescriptor(t, sd, tempDir, data.NodeTypeDir, fmt.Sprintf("testdir%d", i))
}
}
func testRestoreSecurityDescriptor(t *testing.T, sd string, tempDir string, fileType data.NodeType, fileName string) {
// Decode the encoded string SD to get the security descriptor input in bytes.
sdInputBytes, err := base64.StdEncoding.DecodeString(sd)
test.OK(t, errors.Wrapf(err, "Error decoding SD for: %s", fileName))
// Wrap the security descriptor bytes in windows attributes and convert to generic attributes.
genericAttributes, err := data.WindowsAttrsToGenericAttributes(data.WindowsAttributes{CreationTime: nil, FileAttributes: nil, SecurityDescriptor: &sdInputBytes})
test.OK(t, errors.Wrapf(err, "Error constructing windows attributes for: %s", fileName))
// Construct a Node with the generic attributes.
expectedNode := getNode(fileName, fileType, genericAttributes)
// Restore the file/dir and restore the meta data including the security descriptors.
testPath, node := restoreAndGetNode(t, tempDir, &expectedNode, false)
// Get the security descriptor from the node constructed from the file info of the restored path.
sdByteFromRestoredNode := getWindowsAttr(t, testPath, node).SecurityDescriptor
// Get the security descriptor for the test path after the restore.
sdBytesFromRestoredPath, err := getSecurityDescriptor(testPath)
test.OK(t, errors.Wrapf(err, "Error while getting the security descriptor for: %s", testPath))
// Compare the input SD and the SD got from the restored file.
compareSecurityDescriptors(t, testPath, sdInputBytes, *sdBytesFromRestoredPath)
// Compare the SD got from node constructed from the restored file info and the SD got directly from the restored file.
compareSecurityDescriptors(t, testPath, *sdByteFromRestoredNode, *sdBytesFromRestoredPath)
}
// TestRestoreSecurityDescriptorInheritance checks that the DACL protection (inheritance)
// flags are correctly restored. This is the mechanism that preserves the `IsInherited`
// property on individual ACEs.
func TestRestoreSecurityDescriptorInheritance(t *testing.T) {
// This test requires admin privileges to manipulate ACLs effectively.
isAdmin, err := isAdmin()
test.OK(t, err)
if !isAdmin {
t.Skip("Skipping inheritance test, requires admin privileges")
}
tempDir := t.TempDir()
// 1. Create a parent/child directory structure.
parentDir := filepath.Join(tempDir, "parent")
err = os.Mkdir(parentDir, 0755)
test.OK(t, err)
childDir := filepath.Join(parentDir, "child")
err = os.Mkdir(childDir, 0755)
test.OK(t, err)
// 2. Set inheritable permissions on the parent.
// We will give the "Users" group inheritable read access.
users, err := windows.StringToSid("S-1-5-32-545") // BUILTIN\Users
test.OK(t, err)
// Create an EXPLICIT_ACCESS structure for the new ACE.
explicitAccess := windows.EXPLICIT_ACCESS{
AccessPermissions: windows.GENERIC_READ,
AccessMode: windows.GRANT_ACCESS,
Inheritance: windows.OBJECT_INHERIT_ACE | windows.CONTAINER_INHERIT_ACE,
Trustee: windows.TRUSTEE{
TrusteeForm: windows.TRUSTEE_IS_SID,
TrusteeType: windows.TRUSTEE_IS_GROUP,
TrusteeValue: windows.TrusteeValueFromSID(users),
},
}
// Create a new DACL from the entry.
dacl, err := windows.ACLFromEntries([]windows.EXPLICIT_ACCESS{explicitAccess}, nil)
test.OK(t, err)
// Apply this new DACL to the parent, marking it as unprotected so it can be inherited.
err = windows.SetNamedSecurityInfo(
parentDir,
windows.SE_FILE_OBJECT,
windows.DACL_SECURITY_INFORMATION|windows.UNPROTECTED_DACL_SECURITY_INFORMATION,
nil, nil, dacl, nil,
)
test.OK(t, errors.Wrapf(err, "failed to set inheritable ACL on parent dir"))
// 3. Get the Security Descriptor of the child, which should now have inherited the ACE.
sdBytesOriginal, err := getSecurityDescriptor(childDir)
test.OK(t, err)
// Sanity check: verify the original child SD is NOT protected from inheritance.
sdOriginal, err := securityDescriptorBytesToStruct(*sdBytesOriginal)
test.OK(t, err)
control, _, err := sdOriginal.Control()
test.OK(t, err)
test.Assert(t, control&windows.SE_DACL_PROTECTED == 0, "Pre-condition failed: child directory should have inheritance enabled")
// 4. Create a restic node for the child directory.
genericAttrs, err := data.WindowsAttrsToGenericAttributes(data.WindowsAttributes{SecurityDescriptor: sdBytesOriginal})
test.OK(t, err)
childNode := getNode("child-restored", "dir", genericAttrs)
// 5. Restore the node to a new location.
restoreDir := filepath.Join(tempDir, "restore")
err = os.Mkdir(restoreDir, 0755)
test.OK(t, err)
restoredPath, _ := restoreAndGetNode(t, restoreDir, &childNode, false)
// 6. Get the Security Descriptor of the restored child directory.
sdBytesRestored, err := getSecurityDescriptor(restoredPath)
test.OK(t, err)
// 7. Compare the control flags of the original and restored SDs.
sdRestored, err := securityDescriptorBytesToStruct(*sdBytesRestored)
test.OK(t, err)
controlRestored, _, err := sdRestored.Control()
test.OK(t, err)
// The core of the test: Ensure the restored DACL protection flag matches the original.
originalIsProtected := (control & windows.SE_DACL_PROTECTED) != 0
restoredIsProtected := (controlRestored & windows.SE_DACL_PROTECTED) != 0
test.Equals(t, originalIsProtected, restoredIsProtected, "DACL protection flag was not restored correctly. Inheritance state is wrong.")
}
// TestRestoreSecurityDescriptorInheritanceLowPrivilege tests that the low-privilege restore
// path (setNamedSecurityInfoLow) correctly handles inheritance flags. This test doesn't require
// admin privileges and focuses on DACL restoration only.
func TestRestoreSecurityDescriptorInheritanceLowPrivilege(t *testing.T) {
tempDir := t.TempDir()
// 1. Create a test directory
testDir := filepath.Join(tempDir, "testdir")
err := os.Mkdir(testDir, 0755)
test.OK(t, err)
// 2. Get its security descriptor (which will have some default ACL)
sdBytesOriginal, err := getSecurityDescriptor(testDir)
test.OK(t, err)
// Verify we can get the control flags
sdOriginal, err := securityDescriptorBytesToStruct(*sdBytesOriginal)
test.OK(t, err)
controlOriginal, _, err := sdOriginal.Control()
test.OK(t, err)
// 3. Test both protected and unprotected scenarios by modifying the control flags
testCases := []struct {
name string
shouldBeProtected bool
}{
{"unprotected_inheritance_enabled", false},
{"protected_inheritance_disabled", true},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create a copy of the SD bytes to modify
sdBytesTest := make([]byte, len(*sdBytesOriginal))
copy(sdBytesTest, *sdBytesOriginal)
// Modify the control flags to simulate protected/unprotected DACL
sdTest, err := securityDescriptorBytesToStruct(sdBytesTest)
test.OK(t, err)
// Get the DACL from the test SD
dacl, _, err := sdTest.DACL()
test.OK(t, err)
// Determine which control flag to use based on test case
var controlToUse windows.SECURITY_DESCRIPTOR_CONTROL
if tc.shouldBeProtected {
controlToUse = controlOriginal | windows.SE_DACL_PROTECTED
} else {
controlToUse = controlOriginal &^ windows.SE_DACL_PROTECTED
}
// 4. Call setNamedSecurityInfoLow directly to test the low-privilege path
restoreTarget := filepath.Join(tempDir, "restore_"+tc.name)
err = os.Mkdir(restoreTarget, 0755)
test.OK(t, err)
// This directly tests the low-privilege restore function
err = setNamedSecurityInfoLow(restoreTarget, dacl, controlToUse)
test.OK(t, err)
// 5. Get the security descriptor of the restored directory
sdBytesRestored, err := getSecurityDescriptor(restoreTarget)
test.OK(t, err)
// 6. Verify that the control flags were correctly restored
sdRestored, err := securityDescriptorBytesToStruct(*sdBytesRestored)
test.OK(t, err)
controlRestored, _, err := sdRestored.Control()
test.OK(t, err) // Check if the protection flag matches what we requested
restoredIsProtected := (controlRestored & windows.SE_DACL_PROTECTED) != 0
if tc.shouldBeProtected != restoredIsProtected {
t.Errorf("DACL protection flag was not restored correctly in low-privilege path. Expected protected=%v, got protected=%v",
tc.shouldBeProtected, restoredIsProtected)
}
})
}
}
func getNode(name string, fileType data.NodeType, genericAttributes map[data.GenericAttributeType]json.RawMessage) data.Node {
return data.Node{
Name: name,
Type: fileType,
Mode: 0644,
ModTime: parseTime("2024-02-21 6:30:01.111"),
AccessTime: parseTime("2024-02-22 7:31:02.222"),
ChangeTime: parseTime("2024-02-23 8:32:03.333"),
GenericAttributes: genericAttributes,
}
}
func getWindowsAttr(t *testing.T, testPath string, node *data.Node) data.WindowsAttributes {
windowsAttributes, unknownAttribs, err := genericAttributesToWindowsAttrs(node.GenericAttributes)
test.OK(t, errors.Wrapf(err, "Error getting windows attr from generic attr: %s", testPath))
test.Assert(t, len(unknownAttribs) == 0, "Unknown attribs found: %s for: %s", unknownAttribs, testPath)
return windowsAttributes
}
func TestRestoreCreationTime(t *testing.T) {
t.Parallel()
path := t.TempDir()
fi, err := os.Lstat(path)
test.OK(t, errors.Wrapf(err, "Could not Lstat for path: %s", path))
attr := fi.Sys().(*syscall.Win32FileAttributeData)
creationTimeAttribute := attr.CreationTime
//Using the temp dir creation time as the test creation time for the test file and folder
runGenericAttributesTest(t, path, data.TypeCreationTime, data.WindowsAttributes{CreationTime: &creationTimeAttribute}, false)
}
func TestRestoreFileAttributes(t *testing.T) {
t.Parallel()
genericAttributeName := data.TypeFileAttributes
tempDir := t.TempDir()
normal := uint32(syscall.FILE_ATTRIBUTE_NORMAL)
hidden := uint32(syscall.FILE_ATTRIBUTE_HIDDEN)
system := uint32(syscall.FILE_ATTRIBUTE_SYSTEM)
archive := uint32(syscall.FILE_ATTRIBUTE_ARCHIVE)
encrypted := uint32(windows.FILE_ATTRIBUTE_ENCRYPTED)
fileAttributes := []data.WindowsAttributes{
//normal
{FileAttributes: &normal},
//hidden
{FileAttributes: &hidden},
//system
{FileAttributes: &system},
//archive
{FileAttributes: &archive},
//encrypted
{FileAttributes: &encrypted},
}
for i, fileAttr := range fileAttributes {
genericAttrs, err := data.WindowsAttrsToGenericAttributes(fileAttr)
test.OK(t, err)
expectedNodes := []data.Node{
{
Name: fmt.Sprintf("testfile%d", i),
Type: data.NodeTypeFile,
Mode: 0655,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
GenericAttributes: genericAttrs,
},
}
runGenericAttributesTestForNodes(t, expectedNodes, tempDir, genericAttributeName, fileAttr, false)
}
normal = uint32(syscall.FILE_ATTRIBUTE_DIRECTORY)
hidden = uint32(syscall.FILE_ATTRIBUTE_DIRECTORY | syscall.FILE_ATTRIBUTE_HIDDEN)
system = uint32(syscall.FILE_ATTRIBUTE_DIRECTORY | windows.FILE_ATTRIBUTE_SYSTEM)
archive = uint32(syscall.FILE_ATTRIBUTE_DIRECTORY | windows.FILE_ATTRIBUTE_ARCHIVE)
encrypted = uint32(syscall.FILE_ATTRIBUTE_DIRECTORY | windows.FILE_ATTRIBUTE_ENCRYPTED)
folderAttributes := []data.WindowsAttributes{
//normal
{FileAttributes: &normal},
//hidden
{FileAttributes: &hidden},
//system
{FileAttributes: &system},
//archive
{FileAttributes: &archive},
//encrypted
{FileAttributes: &encrypted},
}
for i, folderAttr := range folderAttributes {
genericAttrs, err := data.WindowsAttrsToGenericAttributes(folderAttr)
test.OK(t, err)
expectedNodes := []data.Node{
{
Name: fmt.Sprintf("testdirectory%d", i),
Type: data.NodeTypeDir,
Mode: 0755,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
GenericAttributes: genericAttrs,
},
}
runGenericAttributesTestForNodes(t, expectedNodes, tempDir, genericAttributeName, folderAttr, false)
}
}
func runGenericAttributesTest(t *testing.T, tempDir string, genericAttributeName data.GenericAttributeType, genericAttributeExpected data.WindowsAttributes, warningExpected bool) {
genericAttributes, err := data.WindowsAttrsToGenericAttributes(genericAttributeExpected)
test.OK(t, err)
expectedNodes := []data.Node{
{
Name: "testfile",
Type: data.NodeTypeFile,
Mode: 0644,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
GenericAttributes: genericAttributes,
},
{
Name: "testdirectory",
Type: data.NodeTypeDir,
Mode: 0755,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
GenericAttributes: genericAttributes,
},
}
runGenericAttributesTestForNodes(t, expectedNodes, tempDir, genericAttributeName, genericAttributeExpected, warningExpected)
}
func runGenericAttributesTestForNodes(t *testing.T, expectedNodes []data.Node, tempDir string, genericAttr data.GenericAttributeType, genericAttributeExpected data.WindowsAttributes, warningExpected bool) {
for _, testNode := range expectedNodes {
testPath, node := restoreAndGetNode(t, tempDir, &testNode, warningExpected)
rawMessage := node.GenericAttributes[genericAttr]
genericAttrsExpected, err := data.WindowsAttrsToGenericAttributes(genericAttributeExpected)
test.OK(t, err)
rawMessageExpected := genericAttrsExpected[genericAttr]
test.Equals(t, rawMessageExpected, rawMessage, "Generic attribute: %s got from NodeFromFileInfo not equal for path: %s", string(genericAttr), testPath)
}
}
func restoreAndGetNode(t *testing.T, tempDir string, testNode *data.Node, warningExpected bool) (string, *data.Node) {
testPath := filepath.Join(tempDir, "001", testNode.Name)
err := os.MkdirAll(filepath.Dir(testPath), testNode.Mode)
test.OK(t, errors.Wrapf(err, "Failed to create parent directories for: %s", testPath))
if testNode.Type == data.NodeTypeFile {
testFile, err := os.Create(testPath)
test.OK(t, errors.Wrapf(err, "Failed to create test file: %s", testPath))
testFile.Close()
} else if testNode.Type == data.NodeTypeDir {
err := os.Mkdir(testPath, testNode.Mode)
test.OK(t, errors.Wrapf(err, "Failed to create test directory: %s", testPath))
}
err = NodeRestoreMetadata(testNode, testPath, func(msg string) {
if warningExpected {
test.Assert(t, warningExpected, "Warning triggered as expected: %s", msg)
} else {
// If warning is not expected, this code should not get triggered.
test.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", testPath, msg))
}
}, func(_ string) bool { return true }, false)
test.OK(t, errors.Wrapf(err, "Failed to restore metadata for: %s", testPath))
fs := &Local{}
meta, err := fs.OpenFile(testPath, O_NOFOLLOW, true)
test.OK(t, err)
nodeFromFileInfo, err := meta.ToNode(false, t.Logf)
test.OK(t, errors.Wrapf(err, "Could not get NodeFromFileInfo for path: %s", testPath))
test.OK(t, meta.Close())
return testPath, nodeFromFileInfo
}
const TypeSomeNewAttribute data.GenericAttributeType = "MockAttributes.SomeNewAttribute"
func TestNewGenericAttributeType(t *testing.T) {
t.Parallel()
newGenericAttribute := map[data.GenericAttributeType]json.RawMessage{}
newGenericAttribute[TypeSomeNewAttribute] = []byte("any value")
tempDir := t.TempDir()
expectedNodes := []data.Node{
{
Name: "testfile",
Type: data.NodeTypeFile,
Mode: 0644,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
GenericAttributes: newGenericAttribute,
},
{
Name: "testdirectory",
Type: data.NodeTypeDir,
Mode: 0755,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
GenericAttributes: newGenericAttribute,
},
}
for _, testNode := range expectedNodes {
testPath, node := restoreAndGetNode(t, tempDir, &testNode, true)
_, ua, err := genericAttributesToWindowsAttrs(node.GenericAttributes)
test.OK(t, err)
// Since this GenericAttribute is unknown to this version of the software, it will not get set on the file.
test.Assert(t, len(ua) == 0, "Unknown attributes: %s found for path: %s", ua, testPath)
}
}
func TestRestoreExtendedAttributes(t *testing.T) {
t.Parallel()
tempDir := t.TempDir()
expectedNodes := []data.Node{
{
Name: "testfile",
Type: data.NodeTypeFile,
Mode: 0644,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
ExtendedAttributes: []data.ExtendedAttribute{
{"user.foo", []byte("bar")},
},
},
{
Name: "testdirectory",
Type: data.NodeTypeDir,
Mode: 0755,
ModTime: parseTime("2005-05-14 21:07:03.111"),
AccessTime: parseTime("2005-05-14 21:07:04.222"),
ChangeTime: parseTime("2005-05-14 21:07:05.333"),
ExtendedAttributes: []data.ExtendedAttribute{
{"user.foo", []byte("bar")},
},
},
}
for _, testNode := range expectedNodes {
testPath, node := restoreAndGetNode(t, tempDir, &testNode, false)
var handle windows.Handle
var err error
utf16Path := windows.StringToUTF16Ptr(testPath)
if node.Type == data.NodeTypeFile || node.Type == data.NodeTypeDir {
handle, err = windows.CreateFile(utf16Path, windows.FILE_READ_EA, 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
}
test.OK(t, errors.Wrapf(err, "Error opening file/directory for: %s", testPath))
defer func() {
err := windows.Close(handle)
test.OK(t, errors.Wrapf(err, "Error closing file for: %s", testPath))
}()
extAttr, err := fgetEA(handle)
test.OK(t, errors.Wrapf(err, "Error getting extended attributes for: %s", testPath))
test.Equals(t, len(node.ExtendedAttributes), len(extAttr))
for _, expectedExtAttr := range node.ExtendedAttributes {
var foundExtAttr *extendedAttribute
for _, ea := range extAttr {
if strings.EqualFold(ea.Name, expectedExtAttr.Name) {
foundExtAttr = &ea
break
}
}
test.Assert(t, foundExtAttr != nil, "Expected extended attribute not found")
test.Equals(t, expectedExtAttr.Value, foundExtAttr.Value)
}
}
}
func TestPrepareVolumeName(t *testing.T) {
currentVolume := filepath.VolumeName(func() string {
// Get the current working directory
pwd, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current working directory: %v", err)
}
return pwd
}())
// Create a temporary directory for the test
tempDir, err := os.MkdirTemp("", "restic_test_"+time.Now().Format("20060102150405"))
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tempDir)
// Create a long file name
longFileName := `\Very\Long\Path\That\Exceeds\260\Characters\` + strings.Repeat(`\VeryLongFolderName`, 20) + `\\LongFile.txt`
longFilePath := filepath.Join(tempDir, longFileName)
tempDirVolume := filepath.VolumeName(tempDir)
// Create the file
content := []byte("This is a test file with a very long name.")
err = os.MkdirAll(filepath.Dir(longFilePath), 0755)
test.OK(t, err)
if err != nil {
t.Fatalf("Failed to create long folder: %v", err)
}
err = os.WriteFile(longFilePath, content, 0644)
test.OK(t, err)
if err != nil {
t.Fatalf("Failed to create long file: %v", err)
}
osVolumeGUIDPath := getOSVolumeGUIDPath(t)
osVolumeGUIDVolume := filepath.VolumeName(osVolumeGUIDPath)
testCases := []struct {
name string
path string
expectedVolume string
expectError bool
expectedEASupported bool
isRealPath bool
}{
{
name: "Network drive path",
path: `Z:\Shared\Documents`,
expectedVolume: `Z:`,
expectError: false,
expectedEASupported: false,
},
{
name: "Subst drive path",
path: `X:\Virtual\Folder`,
expectedVolume: `X:`,
expectError: false,
expectedEASupported: false,
},
{
name: "Windows reserved path",
path: `\\.\` + os.Getenv("SystemDrive") + `\System32\drivers\etc\hosts`,
expectedVolume: `\\.\` + os.Getenv("SystemDrive"),
expectError: false,
expectedEASupported: true,
isRealPath: true,
},
{
name: "Long UNC path",
path: `\\?\UNC\LongServerName\VeryLongShareName\DeepPath\File.txt`,
expectedVolume: `\\LongServerName\VeryLongShareName`,
expectError: false,
expectedEASupported: false,
},
{
name: "Volume GUID path",
path: osVolumeGUIDPath,
expectedVolume: osVolumeGUIDVolume,
expectError: false,
expectedEASupported: true,
isRealPath: true,
},
{
name: "Volume GUID path with subfolder",
path: osVolumeGUIDPath + `\Windows`,
expectedVolume: osVolumeGUIDVolume,
expectError: false,
expectedEASupported: true,
isRealPath: true,
},
{
name: "Standard path",
path: os.Getenv("SystemDrive") + `\Users\`,
expectedVolume: os.Getenv("SystemDrive"),
expectError: false,
expectedEASupported: true,
isRealPath: true,
},
{
name: "Extended length path",
path: longFilePath,
expectedVolume: tempDirVolume,
expectError: false,
expectedEASupported: true,
isRealPath: true,
},
{
name: "UNC path",
path: `\\server\share\folder`,
expectedVolume: `\\server\share`,
expectError: false,
expectedEASupported: false,
},
{
name: "Extended UNC path",
path: `\\?\UNC\server\share\folder`,
expectedVolume: `\\server\share`,
expectError: false,
expectedEASupported: false,
},
{
name: "Volume Shadow Copy root",
path: `\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy5555`,
expectedVolume: `\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy5555`,
expectError: false,
expectedEASupported: false,
},
{
name: "Volume Shadow Copy path",
path: `\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy5555\Users\test`,
expectedVolume: `\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy5555`,
expectError: false,
expectedEASupported: false,
},
{
name: "Relative path",
path: `folder\subfolder`,
expectedVolume: currentVolume, // Get current volume
expectError: false,
expectedEASupported: true,
},
{
name: "Empty path",
path: ``,
expectedVolume: currentVolume,
expectError: false,
expectedEASupported: true,
isRealPath: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
isEASupported, err := checkAndStoreEASupport(tc.path)
test.OK(t, err)
test.Equals(t, tc.expectedEASupported, isEASupported)
volume, err := prepareVolumeName(tc.path)
if tc.expectError {
test.Assert(t, err != nil, "Expected an error, but got none")
} else {
test.OK(t, err)
}
test.Equals(t, tc.expectedVolume, volume)
if tc.isRealPath {
isEASupportedVolume, err := pathSupportsExtendedAttributes(volume + `\`)
// If the prepared volume name is not valid, we will next fetch the actual volume name.
test.OK(t, err)
test.Equals(t, tc.expectedEASupported, isEASupportedVolume)
actualVolume, err := getVolumePathName(tc.path)
test.OK(t, err)
test.Equals(t, tc.expectedVolume, actualVolume)
}
})
}
}
func getOSVolumeGUIDPath(t *testing.T) string {
// Get the path of the OS drive (usually C:\)
osDrive := os.Getenv("SystemDrive") + "\\"
// Convert to a volume GUID path
volumeName, err := windows.UTF16PtrFromString(osDrive)
test.OK(t, err)
if err != nil {
return ""
}
var volumeGUID [windows.MAX_PATH]uint16
err = windows.GetVolumeNameForVolumeMountPoint(volumeName, &volumeGUID[0], windows.MAX_PATH)
test.OK(t, err)
if err != nil {
return ""
}
return windows.UTF16ToString(volumeGUID[:])
}
func TestGetVolumePathName(t *testing.T) {
tempDirVolume := filepath.VolumeName(os.TempDir())
testCases := []struct {
name string
path string
expectedPrefix string
}{
{
name: "Root directory",
path: os.Getenv("SystemDrive") + `\`,
expectedPrefix: os.Getenv("SystemDrive"),
},
{
name: "Nested directory",
path: os.Getenv("SystemDrive") + `\Windows\System32`,
expectedPrefix: os.Getenv("SystemDrive"),
},
{
name: "Temp directory",
path: os.TempDir() + `\`,
expectedPrefix: tempDirVolume,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
volumeName, err := getVolumePathName(tc.path)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if !strings.HasPrefix(volumeName, tc.expectedPrefix) {
t.Errorf("Expected volume name to start with %s, but got %s", tc.expectedPrefix, volumeName)
}
})
}
// Test with an invalid path
_, err := getVolumePathName("Z:\\NonExistentPath")
if err == nil {
t.Error("Expected an error for non-existent path, but got nil")
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/node_xattr_test.go | internal/fs/node_xattr_test.go | //go:build darwin || freebsd || netbsd || linux || solaris
package fs
import (
"os"
"testing"
"github.com/pkg/xattr"
rtest "github.com/restic/restic/internal/test"
)
func TestIsListxattrPermissionError(t *testing.T) {
xerr := &xattr.Error{
Op: "xattr.list",
Name: "test",
Err: os.ErrPermission,
}
err := handleXattrErr(xerr)
rtest.Assert(t, err != nil, "missing error")
rtest.Assert(t, isListxattrPermissionError(err), "expected IsListxattrPermissionError to return true for %v", err)
xerr.Err = os.ErrNotExist
err = handleXattrErr(xerr)
rtest.Assert(t, err != nil, "missing error")
rtest.Assert(t, !isListxattrPermissionError(err), "expected IsListxattrPermissionError to return false for %v", err)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/path_prefix_test.go | internal/fs/path_prefix_test.go | package fs
import (
"path/filepath"
"runtime"
"testing"
)
func fromSlashAbs(p string) string {
if runtime.GOOS == "windows" {
if len(p) > 0 && p[0] == '/' {
p = "c:" + p
}
}
return filepath.FromSlash(p)
}
func TestHasPathPrefix(t *testing.T) {
var tests = []struct {
base, p string
result bool
}{
{"", "", true},
{".", ".", true},
{".", "foo", true},
{"foo", ".", false},
{"/", "", false},
{"/", "x", false},
{"x", "/", false},
{"/", "/x", true},
{"/x", "/y", false},
{"/home/user/foo", "/home", false},
{"/home/user/foo/", "/home", false},
{"/home/user/foo", "/home/", false},
{"/home/user/foo/", "/home/", false},
{"/home/user/foo", "/home/user/foo/bar", true},
{"/home/user/foo", "/home/user/foo/bar/baz/x/y/z", true},
{"/home/user/foo", "/home/user/foobar", false},
{"/home/user/Foo", "/home/user/foo/bar/baz", false},
{"/home/user/foo", "/home/user/Foo/bar/baz", false},
{"user/foo", "user/foo/bar/baz", true},
{"user/foo", "./user/foo", true},
{"user/foo", "./user/foo/", true},
{"/home/user/foo", "./user/foo/", false},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
base := fromSlashAbs(test.base)
p := fromSlashAbs(test.p)
result := HasPathPrefix(base, p)
if result != test.result {
t.Fatalf("wrong result for HasPathPrefix(%q, %q): want %v, got %v",
base, p, test.result, result)
}
})
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/file_unix.go | internal/fs/file_unix.go | //go:build !windows
package fs
import (
"os"
"syscall"
)
// fixpath returns an absolute path on windows, so restic can open long file
// names.
func fixpath(name string) string {
return name
}
// TempFile creates a temporary file which has already been deleted (on
// supported platforms)
func TempFile(dir, prefix string) (f *os.File, err error) {
f, err = os.CreateTemp(dir, prefix)
if err != nil {
return nil, err
}
if err = os.Remove(f.Name()); err != nil {
return nil, err
}
return f, nil
}
// isNotSupported returns true if the error is caused by an unsupported file system feature.
func isNotSupported(err error) bool {
if perr, ok := err.(*os.PathError); ok && perr.Err == syscall.ENOTSUP {
return true
}
return false
}
// chmod changes the mode of the named file to mode.
func chmod(name string, mode os.FileMode) error {
err := os.Chmod(fixpath(name), mode)
// ignore the error if the FS does not support setting this mode (e.g. CIFS with gvfs on Linux)
if err != nil && isNotSupported(err) {
return nil
}
return err
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/node_xattr.go | internal/fs/node_xattr.go | //go:build darwin || freebsd || netbsd || linux || solaris
package fs
import (
"os"
"syscall"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/debug"
"github.com/restic/restic/internal/errors"
"github.com/pkg/xattr"
)
// getxattr retrieves extended attribute data associated with path.
func getxattr(path, name string) ([]byte, error) {
b, err := xattr.LGet(path, name)
return b, handleXattrErr(err)
}
// listxattr retrieves a list of names of extended attributes associated with the
// given path in the file system.
func listxattr(path string) ([]string, error) {
l, err := xattr.LList(path)
return l, handleXattrErr(err)
}
func isListxattrPermissionError(err error) bool {
var xerr *xattr.Error
if errors.As(err, &xerr) {
return xerr.Op == "xattr.list" && errors.Is(xerr.Err, os.ErrPermission)
}
return false
}
// setxattr associates name and data together as an attribute of path.
func setxattr(path, name string, data []byte) error {
return handleXattrErr(xattr.LSet(path, name, data))
}
// removexattr removes the attribute name from path.
func removexattr(path, name string) error {
return handleXattrErr(xattr.LRemove(path, name))
}
func handleXattrErr(err error) error {
switch e := err.(type) {
case nil:
return nil
case *xattr.Error:
// On Linux, xattr calls on files in an SMB/CIFS mount can return
// ENOATTR instead of ENOTSUP. BSD can return EOPNOTSUPP.
if e.Err == syscall.ENOTSUP || e.Err == syscall.EOPNOTSUPP || e.Err == xattr.ENOATTR {
return nil
}
return errors.WithStack(e)
default:
return errors.WithStack(e)
}
}
func nodeRestoreExtendedAttributes(node *data.Node, path string, xattrSelectFilter func(xattrName string) bool) error {
expectedAttrs := map[string]struct{}{}
for _, attr := range node.ExtendedAttributes {
// Only restore xattrs that match the filter
if xattrSelectFilter(attr.Name) {
err := setxattr(path, attr.Name, attr.Value)
if err != nil {
return err
}
expectedAttrs[attr.Name] = struct{}{}
}
}
// remove unexpected xattrs
xattrs, err := listxattr(path)
if err != nil {
return err
}
for _, name := range xattrs {
if _, ok := expectedAttrs[name]; ok {
continue
}
// Only attempt to remove xattrs that match the filter
if xattrSelectFilter(name) {
if err := removexattr(path, name); err != nil {
return err
}
}
}
return nil
}
func nodeFillExtendedAttributes(node *data.Node, path string, ignoreListError bool, warnf func(format string, args ...any)) error {
xattrs, err := listxattr(path)
debug.Log("fillExtendedAttributes(%v) %v %v", path, xattrs, err)
if err != nil {
if ignoreListError && isListxattrPermissionError(err) {
return nil
}
return err
}
node.ExtendedAttributes = make([]data.ExtendedAttribute, 0, len(xattrs))
for _, attr := range xattrs {
attrVal, err := getxattr(path, attr)
if err != nil {
warnf("can not obtain extended attribute %v for %v:\n", attr, path)
continue
}
attr := data.ExtendedAttribute{
Name: attr,
Value: attrVal,
}
node.ExtendedAttributes = append(node.ExtendedAttributes, attr)
}
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/preallocate_darwin.go | internal/fs/preallocate_darwin.go | package fs
import (
"os"
"golang.org/x/sys/unix"
)
func PreallocateFile(wr *os.File, size int64) error {
// try contiguous first
fst := unix.Fstore_t{
Flags: unix.F_ALLOCATECONTIG | unix.F_ALLOCATEALL,
Posmode: unix.F_PEOFPOSMODE,
Offset: 0,
Length: size,
}
err := unix.FcntlFstore(wr.Fd(), unix.F_PREALLOCATE, &fst)
if err == nil {
return nil
}
// just take preallocation in any form, but still ask for everything
fst.Flags = unix.F_ALLOCATEALL
err = unix.FcntlFstore(wr.Fd(), unix.F_PREALLOCATE, &fst)
return err
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/node_noxattr.go | internal/fs/node_noxattr.go | //go:build aix || dragonfly || openbsd
package fs
import "github.com/restic/restic/internal/data"
// nodeRestoreExtendedAttributes is a no-op
func nodeRestoreExtendedAttributes(_ *data.Node, _ string, _ func(xattrName string) bool) error {
return nil
}
// nodeFillExtendedAttributes is a no-op
func nodeFillExtendedAttributes(_ *data.Node, _ string, _ bool, _ func(format string, args ...any)) error {
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/node_unix.go | internal/fs/node_unix.go | //go:build !windows
package fs
import (
"os"
"github.com/restic/restic/internal/data"
)
func lchown(name string, node *data.Node, lookupByName bool) error {
var uid, gid uint32
if lookupByName {
uid = lookupUid(node.User)
gid = lookupGid(node.Group)
} else {
uid = node.UID
gid = node.GID
}
return os.Lchown(name, int(uid), int(gid))
}
// nodeRestoreGenericAttributes is no-op.
func nodeRestoreGenericAttributes(node *data.Node, _ string, warn func(msg string)) error {
return data.HandleAllUnknownGenericAttributesFound(node.GenericAttributes, warn)
}
// nodeFillGenericAttributes is a no-op.
func nodeFillGenericAttributes(_ *data.Node, _ string, _ *ExtendedFileInfo) error {
return nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/fs_local_vss.go | internal/fs/fs_local_vss.go | package fs
import (
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/options"
)
// VSSConfig holds extended options of windows volume shadow copy service.
type VSSConfig struct {
ExcludeAllMountPoints bool `option:"exclude-all-mount-points" help:"exclude mountpoints from snapshotting on all volumes"`
ExcludeVolumes string `option:"exclude-volumes" help:"semicolon separated list of volumes to exclude from snapshotting (ex. 'c:\\;e:\\mnt;\\\\?\\Volume{...}')"`
Timeout time.Duration `option:"timeout" help:"time that the VSS can spend creating snapshot before timing out"`
Provider string `option:"provider" help:"VSS provider identifier which will be used for snapshotting"`
}
func init() {
if runtime.GOOS == "windows" {
options.Register("vss", VSSConfig{})
}
}
// NewVSSConfig returns a new VSSConfig with the default values filled in.
func NewVSSConfig() VSSConfig {
return VSSConfig{
Timeout: time.Second * 120,
}
}
// ParseVSSConfig parses a VSS extended options to VSSConfig struct.
func ParseVSSConfig(o options.Options) (VSSConfig, error) {
cfg := NewVSSConfig()
o = o.Extract("vss")
if err := o.Apply("vss", &cfg); err != nil {
return VSSConfig{}, err
}
return cfg, nil
}
// ErrorHandler is used to report errors via callback.
type ErrorHandler func(item string, err error)
// MessageHandler is used to report errors/messages via callbacks.
type MessageHandler func(msg string, args ...interface{})
// VolumeFilter is used to filter volumes by it's mount point or GUID path.
type VolumeFilter func(volume string) bool
// LocalVss is a wrapper around the local file system which uses windows volume
// shadow copy service (VSS) in a transparent way.
type LocalVss struct {
FS
snapshots map[string]VssSnapshot
failedSnapshots map[string]struct{}
mutex sync.RWMutex
msgError ErrorHandler
msgMessage MessageHandler
excludeAllMountPoints bool
excludeVolumes map[string]struct{}
timeout time.Duration
provider string
}
// statically ensure that LocalVss implements FS.
var _ FS = &LocalVss{}
// parseMountPoints try to convert semicolon separated list of mount points
// to map of lowercased volume GUID paths. Mountpoints already in volume
// GUID path format will be validated and normalized.
func parseMountPoints(list string, msgError ErrorHandler) (volumes map[string]struct{}) {
if list == "" {
return
}
for _, s := range strings.Split(list, ";") {
if v, err := getVolumeNameForVolumeMountPoint(s); err != nil {
msgError(s, errors.Errorf("failed to parse vss.exclude-volumes [%s]: %s", s, err))
} else {
if volumes == nil {
volumes = make(map[string]struct{})
}
volumes[strings.ToLower(v)] = struct{}{}
}
}
return
}
// NewLocalVss creates a new wrapper around the windows filesystem using volume
// shadow copy service to access locked files.
func NewLocalVss(msgError ErrorHandler, msgMessage MessageHandler, cfg VSSConfig) *LocalVss {
return &LocalVss{
FS: Local{},
snapshots: make(map[string]VssSnapshot),
failedSnapshots: make(map[string]struct{}),
msgError: msgError,
msgMessage: msgMessage,
excludeAllMountPoints: cfg.ExcludeAllMountPoints,
excludeVolumes: parseMountPoints(cfg.ExcludeVolumes, msgError),
timeout: cfg.Timeout,
provider: cfg.Provider,
}
}
// DeleteSnapshots deletes all snapshots that were created automatically.
func (fs *LocalVss) DeleteSnapshots() {
fs.mutex.Lock()
defer fs.mutex.Unlock()
activeSnapshots := make(map[string]VssSnapshot)
for volumeName, snapshot := range fs.snapshots {
if err := snapshot.Delete(); err != nil {
fs.msgError(volumeName, errors.Errorf("failed to delete VSS snapshot: %s", err))
activeSnapshots[volumeName] = snapshot
}
}
fs.snapshots = activeSnapshots
}
// OpenFile wraps the OpenFile method of the underlying file system.
func (fs *LocalVss) OpenFile(name string, flag int, metadataOnly bool) (File, error) {
return fs.FS.OpenFile(fs.snapshotPath(name), flag, metadataOnly)
}
// Lstat wraps the Lstat method of the underlying file system.
func (fs *LocalVss) Lstat(name string) (*ExtendedFileInfo, error) {
return fs.FS.Lstat(fs.snapshotPath(name))
}
// isMountPointIncluded is true if given mountpoint included by user.
func (fs *LocalVss) isMountPointIncluded(mountPoint string) bool {
if fs.excludeVolumes == nil {
return true
}
volume, err := getVolumeNameForVolumeMountPoint(mountPoint)
if err != nil {
fs.msgError(mountPoint, errors.Errorf("failed to get volume from mount point [%s]: %s", mountPoint, err))
return true
}
_, ok := fs.excludeVolumes[strings.ToLower(volume)]
return !ok
}
// snapshotPath returns the path inside a VSS snapshots if it already exists.
// If the path is not yet available as a snapshot, a snapshot is created.
// If creation of a snapshot fails the file's original path is returned as
// a fallback.
func (fs *LocalVss) snapshotPath(path string) string {
fixPath := fixpath(path)
if strings.HasPrefix(fixPath, `\\?\UNC\`) {
// UNC network shares are currently not supported so we access the regular file
// without snapshotting
// TODO: right now there is a problem in fixpath(): "\\host\share" is not returned as a UNC path
// "\\host\share\" is returned as a valid UNC path
return path
}
fixPath = strings.TrimPrefix(fixPath, `\\?\`)
fixPathLower := strings.ToLower(fixPath)
volumeName := filepath.VolumeName(fixPath)
volumeNameLower := strings.ToLower(volumeName)
fs.mutex.RLock()
// ensure snapshot for volume exists
_, snapshotExists := fs.snapshots[volumeNameLower]
_, snapshotFailed := fs.failedSnapshots[volumeNameLower]
if !snapshotExists && !snapshotFailed {
fs.mutex.RUnlock()
fs.mutex.Lock()
defer fs.mutex.Unlock()
_, snapshotExists = fs.snapshots[volumeNameLower]
_, snapshotFailed = fs.failedSnapshots[volumeNameLower]
if !snapshotExists && !snapshotFailed {
vssVolume := volumeNameLower + string(filepath.Separator)
if !fs.isMountPointIncluded(vssVolume) {
fs.msgMessage("snapshots for [%s] excluded by user\n", vssVolume)
fs.failedSnapshots[volumeNameLower] = struct{}{}
} else {
fs.msgMessage("creating VSS snapshot for [%s]\n", vssVolume)
var includeVolume VolumeFilter
if !fs.excludeAllMountPoints {
includeVolume = func(volume string) bool {
return fs.isMountPointIncluded(volume)
}
}
if snapshot, err := NewVssSnapshot(fs.provider, vssVolume, fs.timeout, includeVolume, fs.msgError); err != nil {
fs.msgError(vssVolume, errors.Errorf("failed to create snapshot for [%s]: %s",
vssVolume, err))
fs.failedSnapshots[volumeNameLower] = struct{}{}
} else {
fs.snapshots[volumeNameLower] = snapshot
fs.msgMessage("successfully created snapshot for [%s]\n", vssVolume)
if len(snapshot.mountPointInfo) > 0 {
fs.msgMessage("mountpoints in snapshot volume [%s]:\n", vssVolume)
for mp, mpInfo := range snapshot.mountPointInfo {
info := ""
if !mpInfo.IsSnapshotted() {
info = " (not snapshotted)"
}
fs.msgMessage(" - %s%s\n", mp, info)
}
}
}
}
}
} else {
defer fs.mutex.RUnlock()
}
var snapshotPath string
if snapshot, ok := fs.snapshots[volumeNameLower]; ok {
// handle case when data is inside mountpoint
for mountPoint, info := range snapshot.mountPointInfo {
if HasPathPrefix(mountPoint, fixPathLower) {
if !info.IsSnapshotted() {
// requested path is under mount point but mount point is
// not available as a snapshot (e.g. no filesystem support,
// removable media, etc.)
// -> try to backup without a snapshot
return path
}
// filepath.rel() should always succeed because we checked that fixPath is either
// the same path or below mountPoint and operation is case-insensitive
relativeToMount, err := filepath.Rel(mountPoint, fixPath)
if err != nil {
panic(err)
}
snapshotPath = fs.Join(info.GetSnapshotDeviceObject(), relativeToMount)
if snapshotPath == info.GetSnapshotDeviceObject() {
snapshotPath += string(filepath.Separator)
}
return snapshotPath
}
}
// requested data is directly on the volume, not inside a mount point
snapshotPath = fs.Join(snapshot.GetSnapshotDeviceObject(),
strings.TrimPrefix(fixPath, volumeName))
if snapshotPath == snapshot.GetSnapshotDeviceObject() {
snapshotPath += string(filepath.Separator)
}
} else {
// no snapshot is available for the requested path:
// -> try to backup without a snapshot
// TODO: log warning?
snapshotPath = path
}
return snapshotPath
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/doc.go | internal/fs/doc.go | // Package fs implements an OS independent abstraction of a file system
// suitable for backup purposes.
package fs
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/stat_bsd.go | internal/fs/stat_bsd.go | //go:build freebsd || netbsd
package fs
import (
"os"
"syscall"
"time"
)
// extendedStat extracts info into an ExtendedFileInfo for unix based operating systems.
func extendedStat(fi os.FileInfo) *ExtendedFileInfo {
s := fi.Sys().(*syscall.Stat_t)
return &ExtendedFileInfo{
Name: fi.Name(),
Mode: fi.Mode(),
DeviceID: uint64(s.Dev),
Inode: uint64(s.Ino),
Links: uint64(s.Nlink),
UID: s.Uid,
GID: s.Gid,
Device: uint64(s.Rdev),
BlockSize: int64(s.Blksize),
Blocks: s.Blocks,
Size: s.Size,
AccessTime: time.Unix(s.Atimespec.Unix()),
ModTime: time.Unix(s.Mtimespec.Unix()),
ChangeTime: time.Unix(s.Ctimespec.Unix()),
}
}
// RecallOnDataAccess checks windows-specific attributes to determine if a file is a cloud-only placeholder.
func (*ExtendedFileInfo) RecallOnDataAccess() (bool, error) {
return false, nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/fs_reader_test.go | internal/fs/fs_reader_test.go | package fs
import (
"bytes"
"errors"
"io"
"os"
"path"
"sort"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/restic/restic/internal/test"
)
func verifyFileContentOpenFile(t testing.TB, fs FS, filename string, want []byte) {
f, err := fs.OpenFile(filename, O_RDONLY, false)
test.OK(t, err)
buf, err := io.ReadAll(f)
test.OK(t, err)
test.OK(t, f.Close())
if !cmp.Equal(want, buf) {
t.Error(cmp.Diff(want, buf))
}
}
func verifyDirectoryContents(t testing.TB, fs FS, dir string, want []string) {
f, err := fs.OpenFile(dir, O_RDONLY, false)
test.OK(t, err)
entries, err := f.Readdirnames(-1)
test.OK(t, err)
test.OK(t, f.Close())
sort.Strings(want)
sort.Strings(entries)
if !cmp.Equal(want, entries) {
t.Error(cmp.Diff(want, entries))
}
}
func checkFileInfo(t testing.TB, fi *ExtendedFileInfo, filename string, modtime time.Time, mode os.FileMode, isdir bool) {
if fi.Mode.IsDir() != isdir {
t.Errorf("IsDir returned %t, want %t", fi.Mode.IsDir(), isdir)
}
if fi.Mode != mode {
t.Errorf("Mode has wrong value, want 0%o, got 0%o", mode, fi.Mode)
}
if !fi.ModTime.Equal(modtime) {
t.Errorf("ModTime has wrong value, want %v, got %v", modtime, fi.ModTime)
}
if path.Base(fi.Name) != fi.Name {
t.Errorf("Name is not base, want %q, got %q", path.Base(fi.Name), fi.Name)
}
if fi.Name != path.Base(filename) {
t.Errorf("Name has wrong value, want %q, got %q", path.Base(filename), fi.Name)
}
}
type fsTest []struct {
name string
f func(t *testing.T, fs FS)
}
func createReadDirTest(fpath, filename string) fsTest {
return fsTest{
{
name: "Readdirnames-slash-" + fpath,
f: func(t *testing.T, fs FS) {
verifyDirectoryContents(t, fs, "/"+fpath, []string{filename})
},
},
{
name: "Readdirnames-current-" + fpath,
f: func(t *testing.T, fs FS) {
verifyDirectoryContents(t, fs, path.Clean(fpath), []string{filename})
},
},
}
}
func createFileTest(filename string, now time.Time, data []byte) fsTest {
return fsTest{
{
name: "file/OpenFile",
f: func(t *testing.T, fs FS) {
verifyFileContentOpenFile(t, fs, filename, data)
},
},
{
name: "file/Open-error-not-exist",
f: func(t *testing.T, fs FS) {
_, err := fs.OpenFile(filename+"/other", O_RDONLY, false)
test.Assert(t, errors.Is(err, os.ErrNotExist), "unexpected error, got %v, expected %v", err, os.ErrNotExist)
},
},
{
name: "file/Lstat",
f: func(t *testing.T, fs FS) {
fi, err := fs.Lstat(filename)
test.OK(t, err)
checkFileInfo(t, fi, filename, now, 0644, false)
},
},
{
name: "file/Stat",
f: func(t *testing.T, fs FS) {
fi := fsOpenAndStat(t, fs, filename, true)
checkFileInfo(t, fi, filename, now, 0644, false)
},
},
}
}
func createDirTest(fpath string, now time.Time) fsTest {
return fsTest{
{
name: "dir/Lstat-slash-" + fpath,
f: func(t *testing.T, fs FS) {
fi, err := fs.Lstat("/" + fpath)
test.OK(t, err)
checkFileInfo(t, fi, "/"+fpath, now, os.ModeDir|0755, true)
},
},
{
name: "dir/Lstat-current-" + fpath,
f: func(t *testing.T, fs FS) {
fi, err := fs.Lstat("./" + fpath)
test.OK(t, err)
checkFileInfo(t, fi, "/"+fpath, now, os.ModeDir|0755, true)
},
},
{
name: "dir/Lstat-error-not-exist-" + fpath,
f: func(t *testing.T, fs FS) {
_, err := fs.Lstat(fpath + "/other")
test.Assert(t, errors.Is(err, os.ErrNotExist), "unexpected error, got %v, expected %v", err, os.ErrNotExist)
},
},
{
name: "dir/Open-slash-" + fpath,
f: func(t *testing.T, fs FS) {
fi := fsOpenAndStat(t, fs, "/"+fpath, false)
checkFileInfo(t, fi, "/"+fpath, now, os.ModeDir|0755, true)
},
},
{
name: "dir/Open-current-" + fpath,
f: func(t *testing.T, fs FS) {
fi := fsOpenAndStat(t, fs, "./"+fpath, false)
checkFileInfo(t, fi, "/"+fpath, now, os.ModeDir|0755, true)
},
},
}
}
func fsOpenAndStat(t *testing.T, fs FS, fpath string, metadataOnly bool) *ExtendedFileInfo {
f, err := fs.OpenFile(fpath, O_RDONLY, metadataOnly)
test.OK(t, err)
fi, err := f.Stat()
test.OK(t, err)
test.OK(t, f.Close())
return fi
}
func TestFSReader(t *testing.T) {
data := test.Random(55, 1<<18+588)
now := time.Now()
filename := "foobar"
tests := createReadDirTest("", filename)
tests = append(tests, createFileTest(filename, now, data)...)
tests = append(tests, createDirTest("", now)...)
for _, tst := range tests {
fs, err := NewReader(filename, io.NopCloser(bytes.NewReader(data)), ReaderOptions{
Mode: 0644,
Size: int64(len(data)),
ModTime: now,
})
test.OK(t, err)
t.Run(tst.name, func(t *testing.T) {
tst.f(t, fs)
})
}
}
func TestFSReaderNested(t *testing.T) {
data := test.Random(55, 1<<18+588)
now := time.Now()
filename := "foo/sub/bar"
tests := createReadDirTest("", "foo")
tests = append(tests, createReadDirTest("foo", "sub")...)
tests = append(tests, createReadDirTest("foo/sub", "bar")...)
tests = append(tests, createFileTest(filename, now, data)...)
tests = append(tests, createDirTest("", now)...)
tests = append(tests, createDirTest("foo", now)...)
tests = append(tests, createDirTest("foo/sub", now)...)
for _, tst := range tests {
fs, err := NewReader(filename, io.NopCloser(bytes.NewReader(data)), ReaderOptions{
Mode: 0644,
Size: int64(len(data)),
ModTime: now,
})
test.OK(t, err)
t.Run(tst.name, func(t *testing.T) {
tst.f(t, fs)
})
}
}
func TestFSReaderDir(t *testing.T) {
data := test.Random(55, 1<<18+588)
now := time.Now()
var tests = []struct {
name string
filename string
}{
{
name: "Lstat-absolute",
filename: "/path/to/foobar",
},
{
name: "Lstat-relative",
filename: "path/to/foobar",
},
}
for _, tst := range tests {
t.Run(tst.name, func(t *testing.T) {
fs, err := NewReader(tst.filename, io.NopCloser(bytes.NewReader(data)), ReaderOptions{
Mode: 0644,
Size: int64(len(data)),
ModTime: now,
})
test.OK(t, err)
dir := path.Dir(tst.filename)
for dir != "/" && dir != "." {
fi, err := fs.Lstat(dir)
test.OK(t, err)
checkFileInfo(t, fi, dir, now, os.ModeDir|0755, true)
dir = path.Dir(dir)
}
})
}
}
func TestFSReaderMinFileSize(t *testing.T) {
var tests = []struct {
name string
data string
allowEmpty bool
readMustErr bool
}{
{
name: "regular",
data: "foobar",
},
{
name: "empty",
data: "",
allowEmpty: false,
readMustErr: true,
},
{
name: "empty2",
data: "",
allowEmpty: true,
readMustErr: false,
},
}
for _, tst := range tests {
t.Run(tst.name, func(t *testing.T) {
fs, err := NewReader("testfile", io.NopCloser(strings.NewReader(tst.data)), ReaderOptions{
Mode: 0644,
ModTime: time.Now(),
AllowEmptyFile: tst.allowEmpty,
})
test.OK(t, err)
f, err := fs.OpenFile("testfile", O_RDONLY, false)
test.OK(t, err)
buf, err := io.ReadAll(f)
if tst.readMustErr {
if err == nil {
t.Fatal("expected error not found, got nil")
}
} else {
test.OK(t, err)
}
if string(buf) != tst.data {
t.Fatalf("wrong data returned, want %q, got %q", tst.data, string(buf))
}
test.OK(t, f.Close())
})
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/stat_darwin_test.go | internal/fs/stat_darwin_test.go | package fs_test
import (
iofs "io/fs"
"os"
"path/filepath"
"syscall"
"testing"
"time"
"github.com/restic/restic/internal/fs"
rtest "github.com/restic/restic/internal/test"
"golang.org/x/sys/unix"
)
func TestRecallOnDataAccessRealFile(t *testing.T) {
// create a temp file for testing
tempdir := rtest.TempDir(t)
filename := filepath.Join(tempdir, "regular-file")
err := os.WriteFile(filename, []byte("foobar"), 0640)
rtest.OK(t, err)
fi, err := os.Stat(filename)
rtest.OK(t, err)
xs := fs.ExtendedStat(fi)
// ensure we can check attrs without error
recall, err := xs.RecallOnDataAccess()
rtest.Assert(t, err == nil, "err should be nil", err)
rtest.Assert(t, recall == false, "RecallOnDataAccess should be false")
}
// mockFileInfo implements os.FileInfo for mocking file attributes
type mockFileInfo struct {
Flags uint32
}
func (m mockFileInfo) IsDir() bool {
return false
}
func (m mockFileInfo) ModTime() time.Time {
return time.Now()
}
func (m mockFileInfo) Mode() iofs.FileMode {
return 0
}
func (m mockFileInfo) Name() string {
return "test"
}
func (m mockFileInfo) Size() int64 {
return 0
}
func (m mockFileInfo) Sys() any {
return &syscall.Stat_t{
Flags: m.Flags,
}
}
func TestRecallOnDataAccessMockCloudFile(t *testing.T) {
fi := mockFileInfo{
Flags: unix.SF_DATALESS,
}
xs := fs.ExtendedStat(fi)
recall, err := xs.RecallOnDataAccess()
rtest.Assert(t, err == nil, "err should be nil", err)
rtest.Assert(t, recall, "RecallOnDataAccess should be true")
}
func TestRecallOnDataAccessMockRegularFile(t *testing.T) {
fi := mockFileInfo{
Flags: 0,
}
xs := fs.ExtendedStat(fi)
recall, err := xs.RecallOnDataAccess()
rtest.Assert(t, err == nil, "err should be nil", err)
rtest.Assert(t, recall == false, "RecallOnDataAccess should be false")
}
func TestRecallOnDataAccessMockError(t *testing.T) {
efi := &fs.ExtendedFileInfo{
Name: "test-file-name",
}
recall, err := efi.RecallOnDataAccess()
rtest.Assert(t, err != nil, "err should be set", err)
rtest.Assert(t, err.Error() == "could not determine file attributes: test-file-name", "err message not correct", err)
rtest.Assert(t, recall == false, "RecallOnDataAccess should be false")
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/setflags_linux_test.go | internal/fs/setflags_linux_test.go | package fs
import (
"io"
"os"
"testing"
"time"
rtest "github.com/restic/restic/internal/test"
"golang.org/x/sys/unix"
)
func TestNoatime(t *testing.T) {
f, err := os.CreateTemp("", "restic-test-noatime")
if err != nil {
t.Fatal(err)
}
defer func() {
_ = f.Close()
err = os.Remove(f.Name())
if err != nil {
t.Fatal(err)
}
}()
// Only run this test on common filesystems that support O_NOATIME.
// On others, we may not get an error.
if !supportsNoatime(t, f) {
t.Skip("temp directory may not support O_NOATIME, skipping")
}
// From this point on, we own the file, so we should not get EPERM.
_, err = io.WriteString(f, "Hello!")
rtest.OK(t, err)
_, err = f.Seek(0, io.SeekStart)
rtest.OK(t, err)
getAtime := func() time.Time {
info, err := f.Stat()
rtest.OK(t, err)
return ExtendedStat(info).AccessTime
}
atime := getAtime()
err = setFlags(f)
rtest.OK(t, err)
_, err = f.Read(make([]byte, 1))
rtest.OK(t, err)
rtest.Equals(t, atime, getAtime())
}
func supportsNoatime(t *testing.T, f *os.File) bool {
var fsinfo unix.Statfs_t
err := unix.Fstatfs(int(f.Fd()), &fsinfo)
rtest.OK(t, err)
// The funky cast works around a compiler error on 32-bit archs:
// "unix.BTRFS_SUPER_MAGIC (untyped int constant 2435016766) overflows int32".
// https://github.com/golang/go/issues/52061
typ := int64(uint(fsinfo.Type))
return typ == unix.BTRFS_SUPER_MAGIC ||
typ == unix.EXT2_SUPER_MAGIC ||
typ == unix.EXT3_SUPER_MAGIC ||
typ == unix.EXT4_SUPER_MAGIC ||
typ == unix.TMPFS_MAGIC
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/fs_reader.go | internal/fs/fs_reader.go | package fs
import (
"fmt"
"io"
"os"
"path"
"slices"
"sync"
"syscall"
"time"
"github.com/restic/restic/internal/data"
"github.com/restic/restic/internal/errors"
)
// Reader is a file system which provides a directory with a single file. When
// this file is opened for reading, the reader is passed through. The file can
// be opened once, all subsequent open calls return syscall.EIO. For Lstat(),
// the provided FileInfo is returned.
type Reader struct {
items map[string]readerItem
}
type ReaderOptions struct {
Mode os.FileMode
ModTime time.Time
Size int64
AllowEmptyFile bool
}
type readerItem struct {
open *sync.Once
fi *ExtendedFileInfo
rc io.ReadCloser
allowEmptyFile bool
children []string
}
// statically ensure that Local implements FS.
var _ FS = &Reader{}
func NewReader(name string, r io.ReadCloser, opts ReaderOptions) (*Reader, error) {
items := make(map[string]readerItem)
name = readerCleanPath(name)
if name == "/" {
return nil, fmt.Errorf("invalid filename specified")
}
isFile := true
for {
if isFile {
fi := &ExtendedFileInfo{
Name: path.Base(name),
Mode: opts.Mode,
ModTime: opts.ModTime,
Size: opts.Size,
}
items[name] = readerItem{
open: &sync.Once{},
fi: fi,
rc: r,
allowEmptyFile: opts.AllowEmptyFile,
}
isFile = false
} else {
fi := &ExtendedFileInfo{
Name: path.Base(name),
Mode: os.ModeDir | 0755,
ModTime: opts.ModTime,
Size: 0,
}
items[name] = readerItem{
fi: fi,
// keep the children set during the previous iteration
children: items[name].children,
}
}
parent := path.Dir(name)
if parent == name {
break
}
// add the current file to the children of the parent directory
item := items[parent]
item.children = append(item.children, path.Base(name))
items[parent] = item
name = parent
}
return &Reader{
items: items,
}, nil
}
func readerCleanPath(name string) string {
return path.Clean("/" + name)
}
// VolumeName returns leading volume name, for the Reader file system it's
// always the empty string.
func (fs *Reader) VolumeName(_ string) string {
return ""
}
func (fs *Reader) OpenFile(name string, flag int, _ bool) (f File, err error) {
if flag & ^(O_RDONLY|O_NOFOLLOW) != 0 {
return nil, pathError("open", name,
fmt.Errorf("invalid combination of flags 0x%x", flag))
}
name = readerCleanPath(name)
item, ok := fs.items[name]
if !ok {
return nil, pathError("open", name, syscall.ENOENT)
}
// Check if the path matches our target file
if item.rc != nil {
item.open.Do(func() {
f = newReaderFile(item.rc, item.fi, item.allowEmptyFile)
})
if f == nil {
return nil, pathError("open", name, syscall.EIO)
}
return f, nil
}
f = fakeDir{
fakeFile: fakeFile{
fi: item.fi,
},
entries: slices.Clone(item.children),
}
return f, nil
}
// Lstat returns the FileInfo structure describing the named file.
// If there is an error, it will be of type *os.PathError.
func (fs *Reader) Lstat(name string) (*ExtendedFileInfo, error) {
name = readerCleanPath(name)
item, ok := fs.items[name]
if !ok {
return nil, pathError("lstat", name, os.ErrNotExist)
}
return item.fi, nil
}
// Join joins any number of path elements into a single path, adding a
// Separator if necessary. Join calls Clean on the result; in particular, all
// empty strings are ignored. On Windows, the result is a UNC path if and only
// if the first path element is a UNC path.
func (fs *Reader) Join(elem ...string) string {
return path.Join(elem...)
}
// Separator returns the OS and FS dependent separator for dirs/subdirs/files.
func (fs *Reader) Separator() string {
return "/"
}
// IsAbs reports whether the path is absolute. For the Reader, this is always the case.
func (fs *Reader) IsAbs(_ string) bool {
return true
}
// Abs returns an absolute representation of path. If the path is not absolute
// it will be joined with the current working directory to turn it into an
// absolute path. The absolute path name for a given file is not guaranteed to
// be unique. Abs calls Clean on the result.
//
// For the Reader, all paths are absolute.
func (fs *Reader) Abs(p string) (string, error) {
return readerCleanPath(p), nil
}
// Clean returns the cleaned path. For details, see filepath.Clean.
func (fs *Reader) Clean(p string) string {
return path.Clean(p)
}
// Base returns the last element of p.
func (fs *Reader) Base(p string) string {
return path.Base(p)
}
// Dir returns p without the last element.
func (fs *Reader) Dir(p string) string {
return path.Dir(p)
}
func newReaderFile(rd io.ReadCloser, fi *ExtendedFileInfo, allowEmptyFile bool) *readerFile {
return &readerFile{
ReadCloser: rd,
AllowEmptyFile: allowEmptyFile,
fakeFile: fakeFile{
fi: fi,
name: fi.Name,
},
}
}
type readerFile struct {
io.ReadCloser
AllowEmptyFile, bytesRead bool
fakeFile
}
// ErrFileEmpty is returned inside a *os.PathError by Read() for the file
// opened from the fs provided by Reader when no data could be read and
// AllowEmptyFile is not set.
var ErrFileEmpty = errors.New("no data read")
func (r *readerFile) Read(p []byte) (int, error) {
n, err := r.ReadCloser.Read(p)
if n > 0 {
r.bytesRead = true
}
// return an error if we did not read any data
if err == io.EOF && !r.AllowEmptyFile && !r.bytesRead {
return n, pathError("read", r.fakeFile.name, ErrFileEmpty)
}
return n, err
}
func (r *readerFile) Close() error {
return r.ReadCloser.Close()
}
// ensure that readerFile implements File
var _ File = &readerFile{}
// fakeFile implements all File methods, but only returns errors for anything
// except Stat()
type fakeFile struct {
name string
fi *ExtendedFileInfo
}
// ensure that fakeFile implements File
var _ File = fakeFile{}
func (f fakeFile) MakeReadable() error {
return nil
}
func (f fakeFile) Readdirnames(_ int) ([]string, error) {
return nil, pathError("readdirnames", f.name, os.ErrInvalid)
}
func (f fakeFile) Read(_ []byte) (int, error) {
return 0, pathError("read", f.name, os.ErrInvalid)
}
func (f fakeFile) Close() error {
return nil
}
func (f fakeFile) Stat() (*ExtendedFileInfo, error) {
return f.fi, nil
}
func (f fakeFile) ToNode(_ bool, _ func(format string, args ...any)) (*data.Node, error) {
node := buildBasicNode(f.name, f.fi)
// fill minimal info with current values for uid, gid
node.UID = uint32(os.Getuid())
node.GID = uint32(os.Getgid())
node.ChangeTime = node.ModTime
return node, nil
}
// fakeDir implements Readdirnames and Readdir, everything else is delegated to fakeFile.
type fakeDir struct {
entries []string
fakeFile
}
func (d fakeDir) Readdirnames(n int) ([]string, error) {
if n > 0 {
return nil, pathError("readdirnames", d.name, errors.New("not implemented"))
}
return slices.Clone(d.entries), nil
}
func pathError(op, name string, err error) *os.PathError {
return &os.PathError{Op: op, Path: name, Err: err}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/setflags_linux.go | internal/fs/setflags_linux.go | package fs
import (
"os"
"golang.org/x/sys/unix"
)
// SetFlags tries to set the O_NOATIME flag on f, which prevents the kernel
// from updating the atime on a read call.
//
// The call fails when we're not the owner of the file or root. The caller
// should ignore the error, which is returned for testing only.
func setFlags(f *os.File) error {
fd := f.Fd()
flags, err := unix.FcntlInt(fd, unix.F_GETFL, 0)
if err == nil {
_, err = unix.FcntlInt(fd, unix.F_SETFL, flags|unix.O_NOATIME)
}
return err
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/stat_windows.go | internal/fs/stat_windows.go | //go:build windows
package fs
import (
"fmt"
"os"
"syscall"
"time"
"golang.org/x/sys/windows"
)
// extendedStat extracts info into an ExtendedFileInfo for Windows.
func extendedStat(fi os.FileInfo) *ExtendedFileInfo {
s, ok := fi.Sys().(*syscall.Win32FileAttributeData)
if !ok {
panic(fmt.Sprintf("conversion to syscall.Win32FileAttributeData failed, type is %T", fi.Sys()))
}
extFI := ExtendedFileInfo{
Name: fi.Name(),
Mode: fi.Mode(),
Size: int64(s.FileSizeLow) | (int64(s.FileSizeHigh) << 32),
sys: fi.Sys(),
}
atime := syscall.NsecToTimespec(s.LastAccessTime.Nanoseconds())
extFI.AccessTime = time.Unix(atime.Unix())
mtime := syscall.NsecToTimespec(s.LastWriteTime.Nanoseconds())
extFI.ModTime = time.Unix(mtime.Unix())
// Windows does not have the concept of a "change time" in the sense Unix uses it, so we're using the LastWriteTime here.
extFI.ChangeTime = extFI.ModTime
return &extFI
}
// RecallOnDataAccess checks if a file is available locally on the disk or if the file is
// just a placeholder which must be downloaded from a remote server. This is typically used
// in cloud syncing services (e.g. OneDrive) to prevent downloading files from cloud storage
// until they are accessed.
func (fi *ExtendedFileInfo) RecallOnDataAccess() (bool, error) {
attrs, ok := fi.sys.(*syscall.Win32FileAttributeData)
if !ok {
return false, fmt.Errorf("could not determine file attributes: %s", fi.Name)
}
if attrs.FileAttributes&windows.FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS > 0 {
return true, nil
}
return false, nil
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/internal/fs/sd_windows_test_helpers.go | internal/fs/sd_windows_test_helpers.go | //go:build windows
package fs
import (
"os/user"
"testing"
"github.com/restic/restic/internal/errors"
"github.com/restic/restic/internal/test"
"golang.org/x/sys/windows"
)
var (
testFileSDs = []string{"AQAUvBQAAAAwAAAAAAAAAEwAAAABBQAAAAAABRUAAACIn1iuVqCC6sy9JqvqAwAAAQUAAAAAAAUVAAAAiJ9YrlaggurMvSarAQIAAAIAfAAEAAAAAAAkAKkAEgABBQAAAAAABRUAAACIn1iuVqCC6sy9JqvtAwAAABAUAP8BHwABAQAAAAAABRIAAAAAEBgA/wEfAAECAAAAAAAFIAAAACACAAAAECQA/wEfAAEFAAAAAAAFFQAAAIifWK5WoILqzL0mq+oDAAA=",
"AQAUvBQAAAAwAAAAAAAAAEwAAAABBQAAAAAABRUAAACIn1iuVqCC6sy9JqvqAwAAAQUAAAAAAAUVAAAAiJ9YrlaggurMvSarAQIAAAIAyAAHAAAAAAAUAKkAEgABAQAAAAAABQcAAAAAABQAiQASAAEBAAAAAAAFBwAAAAAAJACpABIAAQUAAAAAAAUVAAAAiJ9YrlaggurMvSar7QMAAAAAJAC/ARMAAQUAAAAAAAUVAAAAiJ9YrlaggurMvSar6gMAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHwABAgAAAAAABSAAAAAgAgAAAAAkAP8BHwABBQAAAAAABRUAAACIn1iuVqCC6sy9JqvqAwAA",
"AQAUvBQAAAAwAAAA7AAAAEwAAAABBQAAAAAABRUAAAAvr7t03PyHGk2FokNHCAAAAQUAAAAAAAUVAAAAiJ9YrlaggurMvSarAQIAAAIAoAAFAAAAAAAkAP8BHwABBQAAAAAABRUAAAAvr7t03PyHGk2FokNHCAAAAAAkAKkAEgABBQAAAAAABRUAAACIn1iuVqCC6sy9JqvtAwAAABAUAP8BHwABAQAAAAAABRIAAAAAEBgA/wEfAAECAAAAAAAFIAAAACACAAAAECQA/wEfAAEFAAAAAAAFFQAAAIifWK5WoILqzL0mq+oDAAACAHQAAwAAAAKAJAC/AQIAAQUAAAAAAAUVAAAAL6+7dNz8hxpNhaJDtgQAAALAJAC/AQMAAQUAAAAAAAUVAAAAL6+7dNz8hxpNhaJDPgkAAAJAJAD/AQ8AAQUAAAAAAAUVAAAAL6+7dNz8hxpNhaJDtQQAAA==",
}
testDirSDs = []string{"AQAUvBQAAAAwAAAAAAAAAEwAAAABBQAAAAAABRUAAACIn1iuVqCC6sy9JqvqAwAAAQUAAAAAAAUVAAAAiJ9YrlaggurMvSarAQIAAAIAfAAEAAAAAAAkAKkAEgABBQAAAAAABRUAAACIn1iuVqCC6sy9JqvtAwAAABMUAP8BHwABAQAAAAAABRIAAAAAExgA/wEfAAECAAAAAAAFIAAAACACAAAAEyQA/wEfAAEFAAAAAAAFFQAAAIifWK5WoILqzL0mq+oDAAA=",
"AQAUvBQAAAAwAAAAAAAAAEwAAAABBQAAAAAABRUAAACIn1iuVqCC6sy9JqvqAwAAAQUAAAAAAAUVAAAAiJ9YrlaggurMvSarAQIAAAIA3AAIAAAAAAIUAKkAEgABAQAAAAAABQcAAAAAAxQAiQASAAEBAAAAAAAFBwAAAAAAJACpABIAAQUAAAAAAAUVAAAAiJ9YrlaggurMvSar7QMAAAAAJAC/ARMAAQUAAAAAAAUVAAAAiJ9YrlaggurMvSar6gMAAAALFAC/ARMAAQEAAAAAAAMAAAAAABMUAP8BHwABAQAAAAAABRIAAAAAExgA/wEfAAECAAAAAAAFIAAAACACAAAAEyQA/wEfAAEFAAAAAAAFFQAAAIifWK5WoILqzL0mq+oDAAA=",
"AQAUvBQAAAAwAAAA7AAAAEwAAAABBQAAAAAABRUAAAAvr7t03PyHGk2FokNHCAAAAQUAAAAAAAUVAAAAiJ9YrlaggurMvSarAQIAAAIAoAAFAAAAAAAkAP8BHwABBQAAAAAABRUAAAAvr7t03PyHGk2FokNHCAAAAAAkAKkAEgABBQAAAAAABRUAAACIn1iuVqCC6sy9JqvtAwAAABMUAP8BHwABAQAAAAAABRIAAAAAExgA/wEfAAECAAAAAAAFIAAAACACAAAAEyQA/wEfAAEFAAAAAAAFFQAAAIifWK5WoILqzL0mq+oDAAACAHQAAwAAAAKAJAC/AQIAAQUAAAAAAAUVAAAAL6+7dNz8hxpNhaJDtgQAAALAJAC/AQMAAQUAAAAAAAUVAAAAL6+7dNz8hxpNhaJDPgkAAAJAJAD/AQ8AAQUAAAAAAAUVAAAAL6+7dNz8hxpNhaJDtQQAAA==",
}
)
// isAdmin checks if current user is an administrator.
func isAdmin() (isAdmin bool, err error) {
var sid *windows.SID
err = windows.AllocateAndInitializeSid(&windows.SECURITY_NT_AUTHORITY, 2, windows.SECURITY_BUILTIN_DOMAIN_RID, windows.DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, &sid)
if err != nil {
return false, errors.Errorf("sid error: %s", err)
}
windows.GetCurrentProcessToken()
token := windows.Token(0)
member, err := token.IsMember(sid)
if err != nil {
return false, errors.Errorf("token membership error: %s", err)
}
return member, nil
}
// compareSecurityDescriptors runs tests for comparing 2 security descriptors in []byte format.
func compareSecurityDescriptors(t *testing.T, testPath string, sdInputBytes, sdOutputBytes []byte) {
sdInput, err := securityDescriptorBytesToStruct(sdInputBytes)
test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %s", testPath))
sdOutput, err := securityDescriptorBytesToStruct(sdOutputBytes)
test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %s", testPath))
isAdmin, err := isAdmin()
test.OK(t, errors.Wrapf(err, "Error checking if user is admin: %s", testPath))
var ownerExpected *windows.SID
var defaultedOwnerExpected bool
var groupExpected *windows.SID
var defaultedGroupExpected bool
var daclExpected *windows.ACL
var defaultedDaclExpected bool
var saclExpected *windows.ACL
var defaultedSaclExpected bool
// The Dacl is set correctly whether or not application is running as admin.
daclExpected, defaultedDaclExpected, err = sdInput.DACL()
test.OK(t, errors.Wrapf(err, "Error getting input dacl for: %s", testPath))
if isAdmin {
// If application is running as admin, all sd values including owner, group, dacl, sacl are set correctly during restore.
// Hence we will use the input values for comparison with the output values.
ownerExpected, defaultedOwnerExpected, err = sdInput.Owner()
test.OK(t, errors.Wrapf(err, "Error getting input owner for: %s", testPath))
groupExpected, defaultedGroupExpected, err = sdInput.Group()
test.OK(t, errors.Wrapf(err, "Error getting input group for: %s", testPath))
saclExpected, defaultedSaclExpected, err = sdInput.SACL()
test.OK(t, errors.Wrapf(err, "Error getting input sacl for: %s", testPath))
} else {
// If application is not running as admin, owner and group are set as current user's SID/GID during restore and sacl is empty.
// Get the current user
user, err := user.Current()
test.OK(t, errors.Wrapf(err, "Could not get current user for: %s", testPath))
// Get current user's SID
currentUserSID, err := windows.StringToSid(user.Uid)
test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath))
// Get current user's Group SID
currentGroupSID, err := windows.StringToSid(user.Gid)
test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath))
// Set owner and group as current user's SID and GID during restore.
ownerExpected = currentUserSID
defaultedOwnerExpected = false
groupExpected = currentGroupSID
defaultedGroupExpected = false
// If application is not running as admin, SACL is returned empty.
saclExpected = nil
defaultedSaclExpected = false
}
// Now do all the comparisons
// Get owner SID from output file
ownerOut, defaultedOwnerOut, err := sdOutput.Owner()
test.OK(t, errors.Wrapf(err, "Error getting output owner for: %s", testPath))
// Compare owner SIDs. We must use the Equals method for comparison as a syscall is made for comparing SIDs.
test.Assert(t, ownerExpected.Equals(ownerOut), "Owner from SDs read from test path don't match: %s, cur:%s, exp: %s", testPath, ownerExpected.String(), ownerOut.String())
test.Equals(t, defaultedOwnerExpected, defaultedOwnerOut, "Defaulted for owner from SDs read from test path don't match: %s", testPath)
// Get group SID from output file
groupOut, defaultedGroupOut, err := sdOutput.Group()
test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath))
// Compare group SIDs. We must use the Equals method for comparison as a syscall is made for comparing SIDs.
test.Assert(t, groupExpected.Equals(groupOut), "Group from SDs read from test path don't match: %s, cur:%s, exp: %s", testPath, groupExpected.String(), groupOut.String())
test.Equals(t, defaultedGroupExpected, defaultedGroupOut, "Defaulted for group from SDs read from test path don't match: %s", testPath)
// Get dacl from output file
daclOut, defaultedDaclOut, err := sdOutput.DACL()
test.OK(t, errors.Wrapf(err, "Error getting output dacl for: %s", testPath))
// Compare dacls
test.Equals(t, daclExpected, daclOut, "DACL from SDs read from test path don't match: %s", testPath)
test.Equals(t, defaultedDaclExpected, defaultedDaclOut, "Defaulted for DACL from SDs read from test path don't match: %s", testPath)
// Get sacl from output file
saclOut, defaultedSaclOut, err := sdOutput.SACL()
test.OK(t, errors.Wrapf(err, "Error getting output sacl for: %s", testPath))
// Compare sacls
test.Equals(t, saclExpected, saclOut, "DACL from SDs read from test path don't match: %s", testPath)
test.Equals(t, defaultedSaclExpected, defaultedSaclOut, "Defaulted for SACL from SDs read from test path don't match: %s", testPath)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/common_test.go | pkg/release/common_test.go | /*
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 release
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
func TestNewDefaultAccessor(t *testing.T) {
// Testing the default implementation rather than NewAccessor which can be
// overridden by developers.
is := assert.New(t)
// Create release
info := &rspb.Info{Status: common.StatusDeployed, LastDeployed: time.Now().Add(1000)}
labels := make(map[string]string)
labels["foo"] = "bar"
rel := &rspb.Release{
Name: "happy-cats",
Version: 2,
Info: info,
Labels: labels,
Namespace: "default",
ApplyMethod: "csa",
}
// newDefaultAccessor should not be called directly Instead, NewAccessor should be
// called and it will call NewDefaultAccessor. NewAccessor can be changed to a
// non-default accessor by a user so the test calls the default implementation.
// The accessor provides a means to access data on resources that are different types
// but have the same interface. Instead of properties, methods are used to access
// information. Structs with properties are useful in Go when it comes to marshalling
// and unmarshalling data (e.g. coming and going from JSON or YAML). But, structs
// can't be used with interfaces. The accessors enable access to the underlying data
// in a manner that works with Go interfaces.
accessor, err := newDefaultAccessor(rel)
is.NoError(err)
// Verify information
is.Equal(rel.Name, accessor.Name())
is.Equal(rel.Namespace, accessor.Namespace())
is.Equal(rel.Version, accessor.Version())
is.Equal(rel.ApplyMethod, accessor.ApplyMethod())
is.Equal(rel.Labels, accessor.Labels())
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/interfaces.go | pkg/release/interfaces.go | /*
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 release
import (
"time"
"helm.sh/helm/v4/pkg/chart"
)
type Releaser interface{}
type Hook interface{}
type Accessor interface {
Name() string
Namespace() string
Version() int
Hooks() []Hook
Manifest() string
Notes() string
Labels() map[string]string
Chart() chart.Charter
Status() string
ApplyMethod() string
DeployedAt() time.Time
}
type HookAccessor interface {
Path() string
Manifest() string
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/responses.go | pkg/release/responses.go | /*
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 release
// UninstallReleaseResponse represents a successful response to an uninstall request.
type UninstallReleaseResponse struct {
// Release is the release that was marked deleted.
Release Releaser `json:"release,omitempty"`
// Info is an uninstall message
Info string `json:"info,omitempty"`
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/common.go | pkg/release/common.go | /*
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 release
import (
"errors"
"fmt"
"time"
"helm.sh/helm/v4/pkg/chart"
v1release "helm.sh/helm/v4/pkg/release/v1"
)
var NewAccessor func(rel Releaser) (Accessor, error) = newDefaultAccessor //nolint:revive
var NewHookAccessor func(rel Hook) (HookAccessor, error) = newDefaultHookAccessor //nolint:revive
func newDefaultAccessor(rel Releaser) (Accessor, error) {
switch v := rel.(type) {
case v1release.Release:
return &v1Accessor{&v}, nil
case *v1release.Release:
return &v1Accessor{v}, nil
default:
return nil, fmt.Errorf("unsupported release type: %T", rel)
}
}
func newDefaultHookAccessor(hook Hook) (HookAccessor, error) {
switch h := hook.(type) {
case v1release.Hook:
return &v1HookAccessor{&h}, nil
case *v1release.Hook:
return &v1HookAccessor{h}, nil
default:
return nil, errors.New("unsupported release hook type")
}
}
type v1Accessor struct {
rel *v1release.Release
}
func (a *v1Accessor) Name() string {
return a.rel.Name
}
func (a *v1Accessor) Namespace() string {
return a.rel.Namespace
}
func (a *v1Accessor) Version() int {
return a.rel.Version
}
func (a *v1Accessor) Hooks() []Hook {
var hooks = make([]Hook, len(a.rel.Hooks))
for i, h := range a.rel.Hooks {
hooks[i] = h
}
return hooks
}
func (a *v1Accessor) Manifest() string {
return a.rel.Manifest
}
func (a *v1Accessor) Notes() string {
return a.rel.Info.Notes
}
func (a *v1Accessor) Labels() map[string]string {
return a.rel.Labels
}
func (a *v1Accessor) Chart() chart.Charter {
return a.rel.Chart
}
func (a *v1Accessor) Status() string {
return a.rel.Info.Status.String()
}
func (a *v1Accessor) ApplyMethod() string {
return a.rel.ApplyMethod
}
func (a *v1Accessor) DeployedAt() time.Time {
return a.rel.Info.LastDeployed
}
type v1HookAccessor struct {
hook *v1release.Hook
}
func (a *v1HookAccessor) Path() string {
return a.hook.Path
}
func (a *v1HookAccessor) Manifest() string {
return a.hook.Manifest
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/hook.go | pkg/release/v1/hook.go | /*
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 v1
import (
"encoding/json"
"time"
)
// HookEvent specifies the hook event
type HookEvent string
// Hook event types
const (
HookPreInstall HookEvent = "pre-install"
HookPostInstall HookEvent = "post-install"
HookPreDelete HookEvent = "pre-delete"
HookPostDelete HookEvent = "post-delete"
HookPreUpgrade HookEvent = "pre-upgrade"
HookPostUpgrade HookEvent = "post-upgrade"
HookPreRollback HookEvent = "pre-rollback"
HookPostRollback HookEvent = "post-rollback"
HookTest HookEvent = "test"
)
func (x HookEvent) String() string { return string(x) }
// HookDeletePolicy specifies the hook delete policy
type HookDeletePolicy string
// Hook delete policy types
const (
HookSucceeded HookDeletePolicy = "hook-succeeded"
HookFailed HookDeletePolicy = "hook-failed"
HookBeforeHookCreation HookDeletePolicy = "before-hook-creation"
)
func (x HookDeletePolicy) String() string { return string(x) }
// HookOutputLogPolicy specifies the hook output log policy
type HookOutputLogPolicy string
// Hook output log policy types
const (
HookOutputOnSucceeded HookOutputLogPolicy = "hook-succeeded"
HookOutputOnFailed HookOutputLogPolicy = "hook-failed"
)
func (x HookOutputLogPolicy) String() string { return string(x) }
// HookAnnotation is the label name for a hook
const HookAnnotation = "helm.sh/hook"
// HookWeightAnnotation is the label name for a hook weight
const HookWeightAnnotation = "helm.sh/hook-weight"
// HookDeleteAnnotation is the label name for the delete policy for a hook
const HookDeleteAnnotation = "helm.sh/hook-delete-policy"
// HookOutputLogAnnotation is the label name for the output log policy for a hook
const HookOutputLogAnnotation = "helm.sh/hook-output-log-policy"
// Hook defines a hook object.
type Hook struct {
Name string `json:"name,omitempty"`
// Kind is the Kubernetes kind.
Kind string `json:"kind,omitempty"`
// Path is the chart-relative path to the template.
Path string `json:"path,omitempty"`
// Manifest is the manifest contents.
Manifest string `json:"manifest,omitempty"`
// Events are the events that this hook fires on.
Events []HookEvent `json:"events,omitempty"`
// LastRun indicates the date/time this was last run.
LastRun HookExecution `json:"last_run,omitempty"`
// Weight indicates the sort order for execution among similar Hook type
Weight int `json:"weight,omitempty"`
// DeletePolicies are the policies that indicate when to delete the hook
DeletePolicies []HookDeletePolicy `json:"delete_policies,omitempty"`
// OutputLogPolicies defines whether we should copy hook logs back to main process
OutputLogPolicies []HookOutputLogPolicy `json:"output_log_policies,omitempty"`
}
// A HookExecution records the result for the last execution of a hook for a given release.
type HookExecution struct {
// StartedAt indicates the date/time this hook was started
StartedAt time.Time `json:"started_at,omitzero"`
// CompletedAt indicates the date/time this hook was completed.
CompletedAt time.Time `json:"completed_at,omitzero"`
// Phase indicates whether the hook completed successfully
Phase HookPhase `json:"phase"`
}
// A HookPhase indicates the state of a hook execution
type HookPhase string
const (
// HookPhaseUnknown indicates that a hook is in an unknown state
HookPhaseUnknown HookPhase = "Unknown"
// HookPhaseRunning indicates that a hook is currently executing
HookPhaseRunning HookPhase = "Running"
// HookPhaseSucceeded indicates that hook execution succeeded
HookPhaseSucceeded HookPhase = "Succeeded"
// HookPhaseFailed indicates that hook execution failed
HookPhaseFailed HookPhase = "Failed"
)
// String converts a hook phase to a printable string
func (x HookPhase) String() string { return string(x) }
// hookExecutionJSON is used for custom JSON marshaling/unmarshaling
type hookExecutionJSON struct {
StartedAt *time.Time `json:"started_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
Phase HookPhase `json:"phase"`
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// It handles empty string time fields by treating them as zero values.
func (h *HookExecution) UnmarshalJSON(data []byte) error {
// First try to unmarshal into a map to handle empty string time fields
var raw map[string]interface{}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
// Replace empty string time fields with nil
for _, field := range []string{"started_at", "completed_at"} {
if val, ok := raw[field]; ok {
if str, ok := val.(string); ok && str == "" {
raw[field] = nil
}
}
}
// Re-marshal with cleaned data
cleaned, err := json.Marshal(raw)
if err != nil {
return err
}
// Unmarshal into temporary struct with pointer time fields
var tmp hookExecutionJSON
if err := json.Unmarshal(cleaned, &tmp); err != nil {
return err
}
// Copy values to HookExecution struct
if tmp.StartedAt != nil {
h.StartedAt = *tmp.StartedAt
}
if tmp.CompletedAt != nil {
h.CompletedAt = *tmp.CompletedAt
}
h.Phase = tmp.Phase
return nil
}
// MarshalJSON implements the json.Marshaler interface.
// It omits zero-value time fields from the JSON output.
func (h HookExecution) MarshalJSON() ([]byte, error) {
tmp := hookExecutionJSON{
Phase: h.Phase,
}
if !h.StartedAt.IsZero() {
tmp.StartedAt = &h.StartedAt
}
if !h.CompletedAt.IsZero() {
tmp.CompletedAt = &h.CompletedAt
}
return json.Marshal(tmp)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/mock.go | pkg/release/v1/mock.go | /*
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 v1
import (
"fmt"
"math/rand"
"time"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
rcommon "helm.sh/helm/v4/pkg/release/common"
)
// MockHookTemplate is the hook template used for all mock release objects.
var MockHookTemplate = `apiVersion: v1
kind: Job
metadata:
annotations:
"helm.sh/hook": pre-install
`
// MockManifest is the manifest used for all mock release objects.
var MockManifest = `apiVersion: v1
kind: Secret
metadata:
name: fixture
`
// MockReleaseOptions allows for user-configurable options on mock release objects.
type MockReleaseOptions struct {
Name string
Version int
Chart *chart.Chart
Status rcommon.Status
Namespace string
Labels map[string]string
}
// Mock creates a mock release object based on options set by MockReleaseOptions. This function should typically not be used outside of testing.
func Mock(opts *MockReleaseOptions) *Release {
date := time.Unix(242085845, 0).UTC()
name := opts.Name
if name == "" {
name = "testrelease-" + fmt.Sprint(rand.Intn(100))
}
version := 1
if opts.Version != 0 {
version = opts.Version
}
namespace := opts.Namespace
if namespace == "" {
namespace = "default"
}
var labels map[string]string
if len(opts.Labels) > 0 {
labels = opts.Labels
}
ch := opts.Chart
if opts.Chart == nil {
ch = &chart.Chart{
Metadata: &chart.Metadata{
Name: "foo",
Version: "0.1.0-beta.1",
AppVersion: "1.0",
Annotations: map[string]string{
"category": "web-apps",
"supported": "true",
},
Dependencies: []*chart.Dependency{
{
Name: "cool-plugin",
Version: "1.0.0",
Repository: "https://coolplugin.io/charts",
Condition: "coolPlugin.enabled",
Enabled: true,
},
{
Name: "crds",
Version: "2.7.1",
Condition: "crds.enabled",
},
},
},
Templates: []*common.File{
{Name: "templates/foo.tpl", ModTime: time.Now(), Data: []byte(MockManifest)},
},
}
}
scode := rcommon.StatusDeployed
if len(opts.Status) > 0 {
scode = opts.Status
}
info := &Info{
FirstDeployed: date,
LastDeployed: date,
Status: scode,
Description: "Release mock",
Notes: "Some mock release notes!",
}
return &Release{
Name: name,
Info: info,
Chart: ch,
Config: map[string]interface{}{"name": "value"},
Version: version,
Namespace: namespace,
Hooks: []*Hook{
{
Name: "pre-install-hook",
Kind: "Job",
Path: "pre-install-hook.yaml",
Manifest: MockHookTemplate,
LastRun: HookExecution{},
Events: []HookEvent{HookPreInstall},
},
},
Manifest: MockManifest,
Labels: labels,
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/hook_test.go | pkg/release/v1/hook_test.go | /*
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 v1
import (
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHookExecutionMarshalJSON(t *testing.T) {
started := time.Date(2025, 10, 8, 12, 0, 0, 0, time.UTC)
completed := time.Date(2025, 10, 8, 12, 5, 0, 0, time.UTC)
tests := []struct {
name string
exec HookExecution
expected string
}{
{
name: "all fields populated",
exec: HookExecution{
StartedAt: started,
CompletedAt: completed,
Phase: HookPhaseSucceeded,
},
expected: `{"started_at":"2025-10-08T12:00:00Z","completed_at":"2025-10-08T12:05:00Z","phase":"Succeeded"}`,
},
{
name: "only phase",
exec: HookExecution{
Phase: HookPhaseRunning,
},
expected: `{"phase":"Running"}`,
},
{
name: "with started time only",
exec: HookExecution{
StartedAt: started,
Phase: HookPhaseRunning,
},
expected: `{"started_at":"2025-10-08T12:00:00Z","phase":"Running"}`,
},
{
name: "failed phase",
exec: HookExecution{
StartedAt: started,
CompletedAt: completed,
Phase: HookPhaseFailed,
},
expected: `{"started_at":"2025-10-08T12:00:00Z","completed_at":"2025-10-08T12:05:00Z","phase":"Failed"}`,
},
{
name: "unknown phase",
exec: HookExecution{
Phase: HookPhaseUnknown,
},
expected: `{"phase":"Unknown"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
data, err := json.Marshal(&tt.exec)
require.NoError(t, err)
assert.JSONEq(t, tt.expected, string(data))
})
}
}
func TestHookExecutionUnmarshalJSON(t *testing.T) {
started := time.Date(2025, 10, 8, 12, 0, 0, 0, time.UTC)
completed := time.Date(2025, 10, 8, 12, 5, 0, 0, time.UTC)
tests := []struct {
name string
input string
expected HookExecution
wantErr bool
}{
{
name: "all fields populated",
input: `{"started_at":"2025-10-08T12:00:00Z","completed_at":"2025-10-08T12:05:00Z","phase":"Succeeded"}`,
expected: HookExecution{
StartedAt: started,
CompletedAt: completed,
Phase: HookPhaseSucceeded,
},
},
{
name: "only phase",
input: `{"phase":"Running"}`,
expected: HookExecution{
Phase: HookPhaseRunning,
},
},
{
name: "empty string time fields",
input: `{"started_at":"","completed_at":"","phase":"Succeeded"}`,
expected: HookExecution{
Phase: HookPhaseSucceeded,
},
},
{
name: "missing time fields",
input: `{"phase":"Failed"}`,
expected: HookExecution{
Phase: HookPhaseFailed,
},
},
{
name: "null time fields",
input: `{"started_at":null,"completed_at":null,"phase":"Unknown"}`,
expected: HookExecution{
Phase: HookPhaseUnknown,
},
},
{
name: "mixed empty and valid time fields",
input: `{"started_at":"2025-10-08T12:00:00Z","completed_at":"","phase":"Running"}`,
expected: HookExecution{
StartedAt: started,
Phase: HookPhaseRunning,
},
},
{
name: "with started time only",
input: `{"started_at":"2025-10-08T12:00:00Z","phase":"Running"}`,
expected: HookExecution{
StartedAt: started,
Phase: HookPhaseRunning,
},
},
{
name: "failed phase with times",
input: `{"started_at":"2025-10-08T12:00:00Z","completed_at":"2025-10-08T12:05:00Z","phase":"Failed"}`,
expected: HookExecution{
StartedAt: started,
CompletedAt: completed,
Phase: HookPhaseFailed,
},
},
{
name: "invalid time format",
input: `{"started_at":"invalid-time","phase":"Running"}`,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var exec HookExecution
err := json.Unmarshal([]byte(tt.input), &exec)
if tt.wantErr {
assert.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, tt.expected.StartedAt.Unix(), exec.StartedAt.Unix())
assert.Equal(t, tt.expected.CompletedAt.Unix(), exec.CompletedAt.Unix())
assert.Equal(t, tt.expected.Phase, exec.Phase)
})
}
}
func TestHookExecutionRoundTrip(t *testing.T) {
started := time.Date(2025, 10, 8, 12, 0, 0, 0, time.UTC)
completed := time.Date(2025, 10, 8, 12, 5, 0, 0, time.UTC)
original := HookExecution{
StartedAt: started,
CompletedAt: completed,
Phase: HookPhaseSucceeded,
}
data, err := json.Marshal(&original)
require.NoError(t, err)
var decoded HookExecution
err = json.Unmarshal(data, &decoded)
require.NoError(t, err)
assert.Equal(t, original.StartedAt.Unix(), decoded.StartedAt.Unix())
assert.Equal(t, original.CompletedAt.Unix(), decoded.CompletedAt.Unix())
assert.Equal(t, original.Phase, decoded.Phase)
}
func TestHookExecutionEmptyStringRoundTrip(t *testing.T) {
// This test specifically verifies that empty string time fields
// are handled correctly during parsing
input := `{"started_at":"","completed_at":"","phase":"Succeeded"}`
var exec HookExecution
err := json.Unmarshal([]byte(input), &exec)
require.NoError(t, err)
// Verify time fields are zero values
assert.True(t, exec.StartedAt.IsZero())
assert.True(t, exec.CompletedAt.IsZero())
assert.Equal(t, HookPhaseSucceeded, exec.Phase)
// Marshal back and verify empty time fields are omitted
data, err := json.Marshal(&exec)
require.NoError(t, err)
var result map[string]interface{}
err = json.Unmarshal(data, &result)
require.NoError(t, err)
// Zero time values should be omitted
assert.NotContains(t, result, "started_at")
assert.NotContains(t, result, "completed_at")
assert.Equal(t, "Succeeded", result["phase"])
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/release.go | pkg/release/v1/release.go | /*
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 v1
import (
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/release/common"
)
type ApplyMethod string
const ApplyMethodClientSideApply ApplyMethod = "csa"
const ApplyMethodServerSideApply ApplyMethod = "ssa"
// Release describes a deployment of a chart, together with the chart
// and the variables used to deploy that chart.
type Release struct {
// Name is the name of the release
Name string `json:"name,omitempty"`
// Info provides information about a release
Info *Info `json:"info,omitempty"`
// Chart is the chart that was released.
Chart *chart.Chart `json:"chart,omitempty"`
// Config is the set of extra Values added to the chart.
// These values override the default values inside of the chart.
Config map[string]interface{} `json:"config,omitempty"`
// Manifest is the string representation of the rendered template.
Manifest string `json:"manifest,omitempty"`
// Hooks are all of the hooks declared for this release.
Hooks []*Hook `json:"hooks,omitempty"`
// Version is an int which represents the revision of the release.
Version int `json:"version,omitempty"`
// Namespace is the kubernetes namespace of the release.
Namespace string `json:"namespace,omitempty"`
// Labels of the release.
// Disabled encoding into Json cause labels are stored in storage driver metadata field.
Labels map[string]string `json:"-"`
// ApplyMethod stores whether server-side or client-side apply was used for the release
// Unset (empty string) should be treated as the default of client-side apply
ApplyMethod string `json:"apply_method,omitempty"` // "ssa" | "csa"
}
// SetStatus is a helper for setting the status on a release.
func (r *Release) SetStatus(status common.Status, msg string) {
r.Info.Status = status
r.Info.Description = msg
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/info_test.go | pkg/release/v1/info_test.go | /*
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 v1
import (
"encoding/json"
"testing"
"time"
"helm.sh/helm/v4/pkg/release/common"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestInfoMarshalJSON(t *testing.T) {
now := time.Date(2025, 10, 8, 12, 0, 0, 0, time.UTC)
later := time.Date(2025, 10, 8, 13, 0, 0, 0, time.UTC)
deleted := time.Date(2025, 10, 8, 14, 0, 0, 0, time.UTC)
tests := []struct {
name string
info Info
expected string
}{
{
name: "all fields populated",
info: Info{
FirstDeployed: now,
LastDeployed: later,
Deleted: deleted,
Description: "Test release",
Status: common.StatusDeployed,
Notes: "Test notes",
},
expected: `{"first_deployed":"2025-10-08T12:00:00Z","last_deployed":"2025-10-08T13:00:00Z","deleted":"2025-10-08T14:00:00Z","description":"Test release","status":"deployed","notes":"Test notes"}`,
},
{
name: "only required fields",
info: Info{
FirstDeployed: now,
LastDeployed: later,
Status: common.StatusDeployed,
},
expected: `{"first_deployed":"2025-10-08T12:00:00Z","last_deployed":"2025-10-08T13:00:00Z","status":"deployed"}`,
},
{
name: "zero time values omitted",
info: Info{
Description: "Test release",
Status: common.StatusDeployed,
},
expected: `{"description":"Test release","status":"deployed"}`,
},
{
name: "with pending status",
info: Info{
FirstDeployed: now,
LastDeployed: later,
Status: common.StatusPendingInstall,
Description: "Installing release",
},
expected: `{"first_deployed":"2025-10-08T12:00:00Z","last_deployed":"2025-10-08T13:00:00Z","description":"Installing release","status":"pending-install"}`,
},
{
name: "uninstalled with deleted time",
info: Info{
FirstDeployed: now,
LastDeployed: later,
Deleted: deleted,
Status: common.StatusUninstalled,
Description: "Uninstalled release",
},
expected: `{"first_deployed":"2025-10-08T12:00:00Z","last_deployed":"2025-10-08T13:00:00Z","deleted":"2025-10-08T14:00:00Z","description":"Uninstalled release","status":"uninstalled"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
data, err := json.Marshal(&tt.info)
require.NoError(t, err)
assert.JSONEq(t, tt.expected, string(data))
})
}
}
func TestInfoUnmarshalJSON(t *testing.T) {
now := time.Date(2025, 10, 8, 12, 0, 0, 0, time.UTC)
later := time.Date(2025, 10, 8, 13, 0, 0, 0, time.UTC)
deleted := time.Date(2025, 10, 8, 14, 0, 0, 0, time.UTC)
tests := []struct {
name string
input string
expected Info
wantErr bool
}{
{
name: "all fields populated",
input: `{"first_deployed":"2025-10-08T12:00:00Z","last_deployed":"2025-10-08T13:00:00Z","deleted":"2025-10-08T14:00:00Z","description":"Test release","status":"deployed","notes":"Test notes"}`,
expected: Info{
FirstDeployed: now,
LastDeployed: later,
Deleted: deleted,
Description: "Test release",
Status: common.StatusDeployed,
Notes: "Test notes",
},
},
{
name: "only required fields",
input: `{"first_deployed":"2025-10-08T12:00:00Z","last_deployed":"2025-10-08T13:00:00Z","status":"deployed"}`,
expected: Info{
FirstDeployed: now,
LastDeployed: later,
Status: common.StatusDeployed,
},
},
{
name: "empty string time fields",
input: `{"first_deployed":"","last_deployed":"","deleted":"","description":"Test release","status":"deployed"}`,
expected: Info{
Description: "Test release",
Status: common.StatusDeployed,
},
},
{
name: "missing time fields",
input: `{"description":"Test release","status":"deployed"}`,
expected: Info{
Description: "Test release",
Status: common.StatusDeployed,
},
},
{
name: "null time fields",
input: `{"first_deployed":null,"last_deployed":null,"deleted":null,"description":"Test release","status":"deployed"}`,
expected: Info{
Description: "Test release",
Status: common.StatusDeployed,
},
},
{
name: "mixed empty and valid time fields",
input: `{"first_deployed":"2025-10-08T12:00:00Z","last_deployed":"","deleted":"","status":"deployed"}`,
expected: Info{
FirstDeployed: now,
Status: common.StatusDeployed,
},
},
{
name: "pending install status",
input: `{"first_deployed":"2025-10-08T12:00:00Z","status":"pending-install","description":"Installing"}`,
expected: Info{
FirstDeployed: now,
Status: common.StatusPendingInstall,
Description: "Installing",
},
},
{
name: "uninstalled with deleted time",
input: `{"first_deployed":"2025-10-08T12:00:00Z","last_deployed":"2025-10-08T13:00:00Z","deleted":"2025-10-08T14:00:00Z","status":"uninstalled"}`,
expected: Info{
FirstDeployed: now,
LastDeployed: later,
Deleted: deleted,
Status: common.StatusUninstalled,
},
},
{
name: "failed status",
input: `{"first_deployed":"2025-10-08T12:00:00Z","last_deployed":"2025-10-08T13:00:00Z","status":"failed","description":"Deployment failed"}`,
expected: Info{
FirstDeployed: now,
LastDeployed: later,
Status: common.StatusFailed,
Description: "Deployment failed",
},
},
{
name: "invalid time format",
input: `{"first_deployed":"invalid-time","status":"deployed"}`,
wantErr: true,
},
{
name: "empty object",
input: `{}`,
expected: Info{
Status: "",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var info Info
err := json.Unmarshal([]byte(tt.input), &info)
if tt.wantErr {
assert.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, tt.expected.FirstDeployed.Unix(), info.FirstDeployed.Unix())
assert.Equal(t, tt.expected.LastDeployed.Unix(), info.LastDeployed.Unix())
assert.Equal(t, tt.expected.Deleted.Unix(), info.Deleted.Unix())
assert.Equal(t, tt.expected.Description, info.Description)
assert.Equal(t, tt.expected.Status, info.Status)
assert.Equal(t, tt.expected.Notes, info.Notes)
assert.Equal(t, tt.expected.Resources, info.Resources)
})
}
}
func TestInfoRoundTrip(t *testing.T) {
now := time.Date(2025, 10, 8, 12, 0, 0, 0, time.UTC)
later := time.Date(2025, 10, 8, 13, 0, 0, 0, time.UTC)
original := Info{
FirstDeployed: now,
LastDeployed: later,
Description: "Test release",
Status: common.StatusDeployed,
Notes: "Release notes",
}
data, err := json.Marshal(&original)
require.NoError(t, err)
var decoded Info
err = json.Unmarshal(data, &decoded)
require.NoError(t, err)
assert.Equal(t, original.FirstDeployed.Unix(), decoded.FirstDeployed.Unix())
assert.Equal(t, original.LastDeployed.Unix(), decoded.LastDeployed.Unix())
assert.Equal(t, original.Deleted.Unix(), decoded.Deleted.Unix())
assert.Equal(t, original.Description, decoded.Description)
assert.Equal(t, original.Status, decoded.Status)
assert.Equal(t, original.Notes, decoded.Notes)
}
func TestInfoEmptyStringRoundTrip(t *testing.T) {
// This test specifically verifies that empty string time fields
// are handled correctly during parsing
input := `{"first_deployed":"","last_deployed":"","deleted":"","status":"deployed","description":"test"}`
var info Info
err := json.Unmarshal([]byte(input), &info)
require.NoError(t, err)
// Verify time fields are zero values
assert.True(t, info.FirstDeployed.IsZero())
assert.True(t, info.LastDeployed.IsZero())
assert.True(t, info.Deleted.IsZero())
assert.Equal(t, common.StatusDeployed, info.Status)
assert.Equal(t, "test", info.Description)
// Marshal back and verify empty time fields are omitted
data, err := json.Marshal(&info)
require.NoError(t, err)
var result map[string]interface{}
err = json.Unmarshal(data, &result)
require.NoError(t, err)
// Zero time values should be omitted due to omitzero tag
assert.NotContains(t, result, "first_deployed")
assert.NotContains(t, result, "last_deployed")
assert.NotContains(t, result, "deleted")
assert.Equal(t, "deployed", result["status"])
assert.Equal(t, "test", result["description"])
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/info.go | pkg/release/v1/info.go | /*
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 v1
import (
"encoding/json"
"time"
"helm.sh/helm/v4/pkg/release/common"
"k8s.io/apimachinery/pkg/runtime"
)
// Info describes release information.
type Info struct {
// FirstDeployed is when the release was first deployed.
FirstDeployed time.Time `json:"first_deployed,omitzero"`
// LastDeployed is when the release was last deployed.
LastDeployed time.Time `json:"last_deployed,omitzero"`
// Deleted tracks when this object was deleted.
Deleted time.Time `json:"deleted,omitzero"`
// Description is human-friendly "log entry" about this release.
Description string `json:"description,omitempty"`
// Status is the current state of the release
Status common.Status `json:"status,omitempty"`
// Contains the rendered templates/NOTES.txt if available
Notes string `json:"notes,omitempty"`
// Contains the deployed resources information
Resources map[string][]runtime.Object `json:"resources,omitempty"`
}
// infoJSON is used for custom JSON marshaling/unmarshaling
type infoJSON struct {
FirstDeployed *time.Time `json:"first_deployed,omitempty"`
LastDeployed *time.Time `json:"last_deployed,omitempty"`
Deleted *time.Time `json:"deleted,omitempty"`
Description string `json:"description,omitempty"`
Status common.Status `json:"status,omitempty"`
Notes string `json:"notes,omitempty"`
Resources map[string][]runtime.Object `json:"resources,omitempty"`
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// It handles empty string time fields by treating them as zero values.
func (i *Info) UnmarshalJSON(data []byte) error {
// First try to unmarshal into a map to handle empty string time fields
var raw map[string]interface{}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
// Replace empty string time fields with nil
for _, field := range []string{"first_deployed", "last_deployed", "deleted"} {
if val, ok := raw[field]; ok {
if str, ok := val.(string); ok && str == "" {
raw[field] = nil
}
}
}
// Re-marshal with cleaned data
cleaned, err := json.Marshal(raw)
if err != nil {
return err
}
// Unmarshal into temporary struct with pointer time fields
var tmp infoJSON
if err := json.Unmarshal(cleaned, &tmp); err != nil {
return err
}
// Copy values to Info struct
if tmp.FirstDeployed != nil {
i.FirstDeployed = *tmp.FirstDeployed
}
if tmp.LastDeployed != nil {
i.LastDeployed = *tmp.LastDeployed
}
if tmp.Deleted != nil {
i.Deleted = *tmp.Deleted
}
i.Description = tmp.Description
i.Status = tmp.Status
i.Notes = tmp.Notes
i.Resources = tmp.Resources
return nil
}
// MarshalJSON implements the json.Marshaler interface.
// It omits zero-value time fields from the JSON output.
func (i Info) MarshalJSON() ([]byte, error) {
tmp := infoJSON{
Description: i.Description,
Status: i.Status,
Notes: i.Notes,
Resources: i.Resources,
}
if !i.FirstDeployed.IsZero() {
tmp.FirstDeployed = &i.FirstDeployed
}
if !i.LastDeployed.IsZero() {
tmp.LastDeployed = &i.LastDeployed
}
if !i.Deleted.IsZero() {
tmp.Deleted = &i.Deleted
}
return json.Marshal(tmp)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/util/manifest.go | pkg/release/v1/util/manifest.go | /*
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 util
import (
"fmt"
"regexp"
"strconv"
"strings"
)
// SimpleHead defines what the structure of the head of a manifest file
type SimpleHead struct {
Version string `json:"apiVersion"`
Kind string `json:"kind,omitempty"`
Metadata *struct {
Name string `json:"name"`
Annotations map[string]string `json:"annotations"`
} `json:"metadata,omitempty"`
}
var sep = regexp.MustCompile("(?:^|\\s*\n)---\\s*")
// SplitManifests takes a string of manifest and returns a map contains individual manifests
func SplitManifests(bigFile string) map[string]string {
// Basically, we're quickly splitting a stream of YAML documents into an
// array of YAML docs. The file name is just a place holder, but should be
// integer-sortable so that manifests get output in the same order as the
// input (see `BySplitManifestsOrder`).
tpl := "manifest-%d"
res := map[string]string{}
// Making sure that any extra whitespace in YAML stream doesn't interfere in splitting documents correctly.
bigFileTmp := strings.TrimSpace(bigFile)
docs := sep.Split(bigFileTmp, -1)
var count int
for _, d := range docs {
if d == "" {
continue
}
d = strings.TrimSpace(d)
res[fmt.Sprintf(tpl, count)] = d
count = count + 1
}
return res
}
// BySplitManifestsOrder sorts by in-file manifest order, as provided in function `SplitManifests`
type BySplitManifestsOrder []string
func (a BySplitManifestsOrder) Len() int { return len(a) }
func (a BySplitManifestsOrder) Less(i, j int) bool {
// Split `manifest-%d`
anum, _ := strconv.ParseInt(a[i][len("manifest-"):], 10, 0)
bnum, _ := strconv.ParseInt(a[j][len("manifest-"):], 10, 0)
return anum < bnum
}
func (a BySplitManifestsOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/util/filter.go | pkg/release/v1/util/filter.go | /*
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 util // import "helm.sh/helm/v4/pkg/release/v1/util"
import (
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
// FilterFunc returns true if the release object satisfies
// the predicate of the underlying filter func.
type FilterFunc func(*rspb.Release) bool
// Check applies the FilterFunc to the release object.
func (fn FilterFunc) Check(rls *rspb.Release) bool {
if rls == nil {
return false
}
return fn(rls)
}
// Filter applies the filter(s) to the list of provided releases
// returning the list that satisfies the filtering predicate.
func (fn FilterFunc) Filter(rels []*rspb.Release) (rets []*rspb.Release) {
for _, rel := range rels {
if fn.Check(rel) {
rets = append(rets, rel)
}
}
return
}
// Any returns a FilterFunc that filters a list of releases
// determined by the predicate 'f0 || f1 || ... || fn'.
func Any(filters ...FilterFunc) FilterFunc {
return func(rls *rspb.Release) bool {
for _, filter := range filters {
if filter(rls) {
return true
}
}
return false
}
}
// All returns a FilterFunc that filters a list of releases
// determined by the predicate 'f0 && f1 && ... && fn'.
func All(filters ...FilterFunc) FilterFunc {
return func(rls *rspb.Release) bool {
for _, filter := range filters {
if !filter(rls) {
return false
}
}
return true
}
}
// StatusFilter filters a set of releases by status code.
func StatusFilter(status common.Status) FilterFunc {
return FilterFunc(func(rls *rspb.Release) bool {
if rls == nil {
return true
}
return rls.Info.Status == status
})
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/util/filter_test.go | pkg/release/v1/util/filter_test.go | /*
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 util // import "helm.sh/helm/v4/pkg/release/v1/util"
import (
"testing"
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
func TestFilterAny(t *testing.T) {
ls := Any(StatusFilter(common.StatusUninstalled)).Filter(releases)
if len(ls) != 2 {
t.Fatalf("expected 2 results, got '%d'", len(ls))
}
r0, r1 := ls[0], ls[1]
switch {
case r0.Info.Status != common.StatusUninstalled:
t.Fatalf("expected UNINSTALLED result, got '%s'", r1.Info.Status.String())
case r1.Info.Status != common.StatusUninstalled:
t.Fatalf("expected UNINSTALLED result, got '%s'", r1.Info.Status.String())
}
}
func TestFilterAll(t *testing.T) {
fn := FilterFunc(func(rls *rspb.Release) bool {
// true if not uninstalled and version < 4
v0 := !StatusFilter(common.StatusUninstalled).Check(rls)
v1 := rls.Version < 4
return v0 && v1
})
ls := All(fn).Filter(releases)
if len(ls) != 1 {
t.Fatalf("expected 1 result, got '%d'", len(ls))
}
switch r0 := ls[0]; {
case r0.Version == 4:
t.Fatal("got release with status revision 4")
case r0.Info.Status == common.StatusUninstalled:
t.Fatal("got release with status UNINSTALLED")
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/util/manifest_test.go | pkg/release/v1/util/manifest_test.go | /*
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 util // import "helm.sh/helm/v4/pkg/release/v1/util"
import (
"reflect"
"testing"
)
const mockManifestFile = `
---
apiVersion: v1
kind: Pod
metadata:
name: finding-nemo,
annotations:
"helm.sh/hook": test
spec:
containers:
- name: nemo-test
image: fake-image
cmd: fake-command
`
const expectedManifest = `apiVersion: v1
kind: Pod
metadata:
name: finding-nemo,
annotations:
"helm.sh/hook": test
spec:
containers:
- name: nemo-test
image: fake-image
cmd: fake-command`
func TestSplitManifest(t *testing.T) {
manifests := SplitManifests(mockManifestFile)
if len(manifests) != 1 {
t.Errorf("Expected 1 manifest, got %v", len(manifests))
}
expected := map[string]string{"manifest-0": expectedManifest}
if !reflect.DeepEqual(manifests, expected) {
t.Errorf("Expected %v, got %v", expected, manifests)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/util/manifest_sorter.go | pkg/release/v1/util/manifest_sorter.go | /*
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 util
import (
"fmt"
"log/slog"
"path"
"sort"
"strconv"
"strings"
"sigs.k8s.io/yaml"
"helm.sh/helm/v4/pkg/chart/common"
release "helm.sh/helm/v4/pkg/release/v1"
)
// Manifest represents a manifest file, which has a name and some content.
type Manifest struct {
Name string
Content string
Head *SimpleHead
}
// manifestFile represents a file that contains a manifest.
type manifestFile struct {
entries map[string]string
path string
}
// result is an intermediate structure used during sorting.
type result struct {
hooks []*release.Hook
generic []Manifest
}
// TODO: Refactor this out. It's here because naming conventions were not followed through.
// So fix the Test hook names and then remove this.
var events = map[string]release.HookEvent{
release.HookPreInstall.String(): release.HookPreInstall,
release.HookPostInstall.String(): release.HookPostInstall,
release.HookPreDelete.String(): release.HookPreDelete,
release.HookPostDelete.String(): release.HookPostDelete,
release.HookPreUpgrade.String(): release.HookPreUpgrade,
release.HookPostUpgrade.String(): release.HookPostUpgrade,
release.HookPreRollback.String(): release.HookPreRollback,
release.HookPostRollback.String(): release.HookPostRollback,
release.HookTest.String(): release.HookTest,
// Support test-success for backward compatibility with Helm 2 tests
"test-success": release.HookTest,
}
// SortManifests takes a map of filename/YAML contents, splits the file
// by manifest entries, and sorts the entries into hook types.
//
// The resulting hooks struct will be populated with all of the generated hooks.
// Any file that does not declare one of the hook types will be placed in the
// 'generic' bucket.
//
// Files that do not parse into the expected format are simply placed into a map and
// returned.
func SortManifests(files map[string]string, _ common.VersionSet, ordering KindSortOrder) ([]*release.Hook, []Manifest, error) {
result := &result{}
var sortedFilePaths []string
for filePath := range files {
sortedFilePaths = append(sortedFilePaths, filePath)
}
sort.Strings(sortedFilePaths)
for _, filePath := range sortedFilePaths {
content := files[filePath]
// Skip partials. We could return these as a separate map, but there doesn't
// seem to be any need for that at this time.
if strings.HasPrefix(path.Base(filePath), "_") {
continue
}
// Skip empty files and log this.
if strings.TrimSpace(content) == "" {
continue
}
manifestFile := &manifestFile{
entries: SplitManifests(content),
path: filePath,
}
if err := manifestFile.sort(result); err != nil {
return result.hooks, result.generic, err
}
}
return sortHooksByKind(result.hooks, ordering), sortManifestsByKind(result.generic, ordering), nil
}
// sort takes a manifestFile object which may contain multiple resource definition
// entries and sorts each entry by hook types, and saves the resulting hooks and
// generic manifests (or non-hooks) to the result struct.
//
// To determine hook type, it looks for a YAML structure like this:
//
// kind: SomeKind
// apiVersion: v1
// metadata:
// annotations:
// helm.sh/hook: pre-install
//
// To determine the policy to delete the hook, it looks for a YAML structure like this:
//
// kind: SomeKind
// apiVersion: v1
// metadata:
// annotations:
// helm.sh/hook-delete-policy: hook-succeeded
//
// To determine the policy to output logs of the hook (for Pod and Job only), it looks for a YAML structure like this:
//
// kind: Pod
// apiVersion: v1
// metadata:
// annotations:
// helm.sh/hook-output-log-policy: hook-succeeded,hook-failed
func (file *manifestFile) sort(result *result) error {
// Go through manifests in order found in file (function `SplitManifests` creates integer-sortable keys)
var sortedEntryKeys []string
for entryKey := range file.entries {
sortedEntryKeys = append(sortedEntryKeys, entryKey)
}
sort.Sort(BySplitManifestsOrder(sortedEntryKeys))
for _, entryKey := range sortedEntryKeys {
m := file.entries[entryKey]
var entry SimpleHead
if err := yaml.Unmarshal([]byte(m), &entry); err != nil {
return fmt.Errorf("YAML parse error on %s: %w", file.path, err)
}
if !hasAnyAnnotation(entry) {
result.generic = append(result.generic, Manifest{
Name: file.path,
Content: m,
Head: &entry,
})
continue
}
hookTypes, ok := entry.Metadata.Annotations[release.HookAnnotation]
if !ok {
result.generic = append(result.generic, Manifest{
Name: file.path,
Content: m,
Head: &entry,
})
continue
}
hw := calculateHookWeight(entry)
h := &release.Hook{
Name: entry.Metadata.Name,
Kind: entry.Kind,
Path: file.path,
Manifest: m,
Events: []release.HookEvent{},
Weight: hw,
DeletePolicies: []release.HookDeletePolicy{},
OutputLogPolicies: []release.HookOutputLogPolicy{},
}
isUnknownHook := false
for hookType := range strings.SplitSeq(hookTypes, ",") {
hookType = strings.ToLower(strings.TrimSpace(hookType))
e, ok := events[hookType]
if !ok {
isUnknownHook = true
break
}
h.Events = append(h.Events, e)
}
if isUnknownHook {
slog.Info("skipping unknown hooks", "hookTypes", hookTypes)
continue
}
result.hooks = append(result.hooks, h)
operateAnnotationValues(entry, release.HookDeleteAnnotation, func(value string) {
h.DeletePolicies = append(h.DeletePolicies, release.HookDeletePolicy(value))
})
operateAnnotationValues(entry, release.HookOutputLogAnnotation, func(value string) {
h.OutputLogPolicies = append(h.OutputLogPolicies, release.HookOutputLogPolicy(value))
})
}
return nil
}
// hasAnyAnnotation returns true if the given entry has any annotations at all.
func hasAnyAnnotation(entry SimpleHead) bool {
return entry.Metadata != nil &&
entry.Metadata.Annotations != nil &&
len(entry.Metadata.Annotations) != 0
}
// calculateHookWeight finds the weight in the hook weight annotation.
//
// If no weight is found, the assigned weight is 0
func calculateHookWeight(entry SimpleHead) int {
hws := entry.Metadata.Annotations[release.HookWeightAnnotation]
hw, err := strconv.Atoi(hws)
if err != nil {
hw = 0
}
return hw
}
// operateAnnotationValues finds the given annotation and runs the operate function with the value of that annotation
func operateAnnotationValues(entry SimpleHead, annotation string, operate func(p string)) {
if dps, ok := entry.Metadata.Annotations[annotation]; ok {
for dp := range strings.SplitSeq(dps, ",") {
dp = strings.ToLower(strings.TrimSpace(dp))
operate(dp)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/util/manifest_sorter_test.go | pkg/release/v1/util/manifest_sorter_test.go | /*
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 util
import (
"reflect"
"testing"
"sigs.k8s.io/yaml"
release "helm.sh/helm/v4/pkg/release/v1"
)
func TestSortManifests(t *testing.T) {
data := []struct {
name []string
path string
kind []string
hooks map[string][]release.HookEvent
manifest string
}{
{
name: []string{"first"},
path: "one",
kind: []string{"Job"},
hooks: map[string][]release.HookEvent{"first": {release.HookPreInstall}},
manifest: `apiVersion: v1
kind: Job
metadata:
name: first
labels:
doesnot: matter
annotations:
"helm.sh/hook": pre-install
`,
},
{
name: []string{"second"},
path: "two",
kind: []string{"ReplicaSet"},
hooks: map[string][]release.HookEvent{"second": {release.HookPostInstall}},
manifest: `kind: ReplicaSet
apiVersion: v1beta1
metadata:
name: second
annotations:
"helm.sh/hook": post-install
`,
}, {
name: []string{"third"},
path: "three",
kind: []string{"ReplicaSet"},
hooks: map[string][]release.HookEvent{"third": nil},
manifest: `kind: ReplicaSet
apiVersion: v1beta1
metadata:
name: third
annotations:
"helm.sh/hook": no-such-hook
`,
}, {
name: []string{"fourth"},
path: "four",
kind: []string{"Pod"},
hooks: map[string][]release.HookEvent{"fourth": nil},
manifest: `kind: Pod
apiVersion: v1
metadata:
name: fourth
annotations:
nothing: here`,
}, {
name: []string{"fifth"},
path: "five",
kind: []string{"ReplicaSet"},
hooks: map[string][]release.HookEvent{"fifth": {release.HookPostDelete, release.HookPostInstall}},
manifest: `kind: ReplicaSet
apiVersion: v1beta1
metadata:
name: fifth
annotations:
"helm.sh/hook": post-delete, post-install
`,
}, {
// Regression test: files with an underscore in the base name should be skipped.
name: []string{"sixth"},
path: "six/_six",
kind: []string{"ReplicaSet"},
hooks: map[string][]release.HookEvent{"sixth": nil},
manifest: `invalid manifest`, // This will fail if partial is not skipped.
}, {
// Regression test: files with no content should be skipped.
name: []string{"seventh"},
path: "seven",
kind: []string{"ReplicaSet"},
hooks: map[string][]release.HookEvent{"seventh": nil},
manifest: "",
},
{
name: []string{"eighth", "example-test"},
path: "eight",
kind: []string{"ConfigMap", "Pod"},
hooks: map[string][]release.HookEvent{"eighth": nil, "example-test": {release.HookTest}},
manifest: `kind: ConfigMap
apiVersion: v1
metadata:
name: eighth
data:
name: value
---
apiVersion: v1
kind: Pod
metadata:
name: example-test
annotations:
"helm.sh/hook": test
`,
},
}
manifests := make(map[string]string, len(data))
for _, o := range data {
manifests[o.path] = o.manifest
}
hs, generic, err := SortManifests(manifests, nil, InstallOrder)
if err != nil {
t.Fatalf("Unexpected error: %s", err)
}
// This test will fail if 'six' or 'seven' was added.
if len(generic) != 2 {
t.Errorf("Expected 2 generic manifests, got %d", len(generic))
}
if len(hs) != 4 {
t.Errorf("Expected 4 hooks, got %d", len(hs))
}
for _, out := range hs {
found := false
for _, expect := range data {
if out.Path == expect.path {
found = true
if out.Path != expect.path {
t.Errorf("Expected path %s, got %s", expect.path, out.Path)
}
nameFound := false
for _, expectedName := range expect.name {
if out.Name == expectedName {
nameFound = true
}
}
if !nameFound {
t.Errorf("Got unexpected name %s", out.Name)
}
kindFound := false
for _, expectedKind := range expect.kind {
if out.Kind == expectedKind {
kindFound = true
}
}
if !kindFound {
t.Errorf("Got unexpected kind %s", out.Kind)
}
expectedHooks := expect.hooks[out.Name]
if !reflect.DeepEqual(expectedHooks, out.Events) {
t.Errorf("expected events: %v but got: %v", expectedHooks, out.Events)
}
}
}
if !found {
t.Errorf("Result not found: %v", out)
}
}
// Verify the sort order
sorted := []Manifest{}
for _, s := range data {
manifests := SplitManifests(s.manifest)
for _, m := range manifests {
var sh SimpleHead
if err := yaml.Unmarshal([]byte(m), &sh); err != nil {
// This is expected for manifests that are corrupt or empty.
t.Log(err)
continue
}
name := sh.Metadata.Name
// only keep track of non-hook manifests
if s.hooks[name] == nil {
another := Manifest{
Content: m,
Name: name,
Head: &sh,
}
sorted = append(sorted, another)
}
}
}
sorted = sortManifestsByKind(sorted, InstallOrder)
for i, m := range generic {
if m.Content != sorted[i].Content {
t.Errorf("Expected %q, got %q", m.Content, sorted[i].Content)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/util/sorter_test.go | pkg/release/v1/util/sorter_test.go | /*
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 util // import "helm.sh/helm/v4/pkg/release/v1/util"
import (
"testing"
"time"
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
// note: this test data is shared with filter_test.go.
var releases = []*rspb.Release{
tsRelease("quiet-bear", 2, 2000, common.StatusSuperseded),
tsRelease("angry-bird", 4, 3000, common.StatusDeployed),
tsRelease("happy-cats", 1, 4000, common.StatusUninstalled),
tsRelease("vocal-dogs", 3, 6000, common.StatusUninstalled),
}
func tsRelease(name string, vers int, dur time.Duration, status common.Status) *rspb.Release {
info := &rspb.Info{Status: status, LastDeployed: time.Now().Add(dur)}
return &rspb.Release{
Name: name,
Version: vers,
Info: info,
}
}
func check(t *testing.T, by string, fn func(int, int) bool) {
t.Helper()
for i := len(releases) - 1; i > 0; i-- {
if fn(i, i-1) {
t.Errorf("release at positions '(%d,%d)' not sorted by %s", i-1, i, by)
}
}
}
func TestSortByName(t *testing.T) {
SortByName(releases)
check(t, "ByName", func(i, j int) bool {
ni := releases[i].Name
nj := releases[j].Name
return ni < nj
})
}
func TestSortByDate(t *testing.T) {
SortByDate(releases)
check(t, "ByDate", func(i, j int) bool {
ti := releases[i].Info.LastDeployed.Second()
tj := releases[j].Info.LastDeployed.Second()
return ti < tj
})
}
func TestSortByRevision(t *testing.T) {
SortByRevision(releases)
check(t, "ByRevision", func(i, j int) bool {
vi := releases[i].Version
vj := releases[j].Version
return vi < vj
})
}
func TestReverseSortByName(t *testing.T) {
Reverse(releases, SortByName)
check(t, "ByName", func(i, j int) bool {
ni := releases[i].Name
nj := releases[j].Name
return ni > nj
})
}
func TestReverseSortByDate(t *testing.T) {
Reverse(releases, SortByDate)
check(t, "ByDate", func(i, j int) bool {
ti := releases[i].Info.LastDeployed.Second()
tj := releases[j].Info.LastDeployed.Second()
return ti > tj
})
}
func TestReverseSortByRevision(t *testing.T) {
Reverse(releases, SortByRevision)
check(t, "ByRevision", func(i, j int) bool {
vi := releases[i].Version
vj := releases[j].Version
return vi > vj
})
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/util/sorter.go | pkg/release/v1/util/sorter.go | /*
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 util // import "helm.sh/helm/v4/pkg/release/v1/util"
import (
"sort"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
// Reverse reverses the list of releases sorted by the sort func.
func Reverse(list []*rspb.Release, sortFn func([]*rspb.Release)) {
sortFn(list)
for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 {
list[i], list[j] = list[j], list[i]
}
}
// SortByName returns the list of releases sorted
// in lexicographical order.
func SortByName(list []*rspb.Release) {
sort.Slice(list, func(i, j int) bool {
return list[i].Name < list[j].Name
})
}
// SortByDate returns the list of releases sorted by a
// release's last deployed time (in seconds).
func SortByDate(list []*rspb.Release) {
sort.Slice(list, func(i, j int) bool {
ti := list[i].Info.LastDeployed.Unix()
tj := list[j].Info.LastDeployed.Unix()
if ti != tj {
return ti < tj
}
// Use name as tie-breaker for stable sorting
return list[i].Name < list[j].Name
})
}
// SortByRevision returns the list of releases sorted by a
// release's revision number (release.Version).
func SortByRevision(list []*rspb.Release) {
sort.Slice(list, func(i, j int) bool {
return list[i].Version < list[j].Version
})
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/util/kind_sorter_test.go | pkg/release/v1/util/kind_sorter_test.go | /*
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 util
import (
"bytes"
"testing"
release "helm.sh/helm/v4/pkg/release/v1"
)
func TestKindSorter(t *testing.T) {
manifests := []Manifest{
{
Name: "U",
Head: &SimpleHead{Kind: "IngressClass"},
},
{
Name: "E",
Head: &SimpleHead{Kind: "SecretList"},
},
{
Name: "i",
Head: &SimpleHead{Kind: "ClusterRole"},
},
{
Name: "I",
Head: &SimpleHead{Kind: "ClusterRoleList"},
},
{
Name: "j",
Head: &SimpleHead{Kind: "ClusterRoleBinding"},
},
{
Name: "J",
Head: &SimpleHead{Kind: "ClusterRoleBindingList"},
},
{
Name: "f",
Head: &SimpleHead{Kind: "ConfigMap"},
},
{
Name: "u",
Head: &SimpleHead{Kind: "CronJob"},
},
{
Name: "2",
Head: &SimpleHead{Kind: "CustomResourceDefinition"},
},
{
Name: "n",
Head: &SimpleHead{Kind: "DaemonSet"},
},
{
Name: "r",
Head: &SimpleHead{Kind: "Deployment"},
},
{
Name: "!",
Head: &SimpleHead{Kind: "HonkyTonkSet"},
},
{
Name: "v",
Head: &SimpleHead{Kind: "Ingress"},
},
{
Name: "t",
Head: &SimpleHead{Kind: "Job"},
},
{
Name: "c",
Head: &SimpleHead{Kind: "LimitRange"},
},
{
Name: "a",
Head: &SimpleHead{Kind: "Namespace"},
},
{
Name: "A",
Head: &SimpleHead{Kind: "NetworkPolicy"},
},
{
Name: "g",
Head: &SimpleHead{Kind: "PersistentVolume"},
},
{
Name: "h",
Head: &SimpleHead{Kind: "PersistentVolumeClaim"},
},
{
Name: "o",
Head: &SimpleHead{Kind: "Pod"},
},
{
Name: "3",
Head: &SimpleHead{Kind: "PodDisruptionBudget"},
},
{
Name: "C",
Head: &SimpleHead{Kind: "PodSecurityPolicy"},
},
{
Name: "q",
Head: &SimpleHead{Kind: "ReplicaSet"},
},
{
Name: "p",
Head: &SimpleHead{Kind: "ReplicationController"},
},
{
Name: "b",
Head: &SimpleHead{Kind: "ResourceQuota"},
},
{
Name: "k",
Head: &SimpleHead{Kind: "Role"},
},
{
Name: "K",
Head: &SimpleHead{Kind: "RoleList"},
},
{
Name: "l",
Head: &SimpleHead{Kind: "RoleBinding"},
},
{
Name: "L",
Head: &SimpleHead{Kind: "RoleBindingList"},
},
{
Name: "e",
Head: &SimpleHead{Kind: "Secret"},
},
{
Name: "m",
Head: &SimpleHead{Kind: "Service"},
},
{
Name: "d",
Head: &SimpleHead{Kind: "ServiceAccount"},
},
{
Name: "s",
Head: &SimpleHead{Kind: "StatefulSet"},
},
{
Name: "1",
Head: &SimpleHead{Kind: "StorageClass"},
},
{
Name: "w",
Head: &SimpleHead{Kind: "APIService"},
},
{
Name: "x",
Head: &SimpleHead{Kind: "HorizontalPodAutoscaler"},
},
{
Name: "F",
Head: &SimpleHead{Kind: "PriorityClass"},
},
{
Name: "M",
Head: &SimpleHead{Kind: "MutatingWebhookConfiguration"},
},
{
Name: "V",
Head: &SimpleHead{Kind: "ValidatingWebhookConfiguration"},
},
}
for _, test := range []struct {
description string
order KindSortOrder
expected string
}{
{"install", InstallOrder, "FaAbcC3deEf1gh2iIjJkKlLmnopqrxstuUvwMV!"},
{"uninstall", UninstallOrder, "VMwvUmutsxrqponLlKkJjIi2hg1fEed3CcbAaF!"},
} {
var buf bytes.Buffer
t.Run(test.description, func(t *testing.T) {
if got, want := len(test.expected), len(manifests); got != want {
t.Fatalf("Expected %d names in order, got %d", want, got)
}
defer buf.Reset()
orig := manifests
for _, r := range sortManifestsByKind(manifests, test.order) {
buf.WriteString(r.Name)
}
if got := buf.String(); got != test.expected {
t.Errorf("Expected %q, got %q", test.expected, got)
}
for i, manifest := range orig {
if manifest != manifests[i] {
t.Fatal("Expected input to sortManifestsByKind to stay the same")
}
}
})
}
}
// TestKindSorterKeepOriginalOrder verifies manifests of same kind are kept in original order
func TestKindSorterKeepOriginalOrder(t *testing.T) {
manifests := []Manifest{
{
Name: "a",
Head: &SimpleHead{Kind: "ClusterRole"},
},
{
Name: "A",
Head: &SimpleHead{Kind: "ClusterRole"},
},
{
Name: "0",
Head: &SimpleHead{Kind: "ConfigMap"},
},
{
Name: "1",
Head: &SimpleHead{Kind: "ConfigMap"},
},
{
Name: "z",
Head: &SimpleHead{Kind: "ClusterRoleBinding"},
},
{
Name: "!",
Head: &SimpleHead{Kind: "ClusterRoleBinding"},
},
{
Name: "u2",
Head: &SimpleHead{Kind: "Unknown"},
},
{
Name: "u1",
Head: &SimpleHead{Kind: "Unknown"},
},
{
Name: "t3",
Head: &SimpleHead{Kind: "Unknown2"},
},
}
for _, test := range []struct {
description string
order KindSortOrder
expected string
}{
// expectation is sorted by kind (unknown is last) and within each group of same kind, the order is kept
{"cm,clusterRole,clusterRoleBinding,Unknown,Unknown2", InstallOrder, "01aAz!u2u1t3"},
} {
var buf bytes.Buffer
t.Run(test.description, func(t *testing.T) {
defer buf.Reset()
for _, r := range sortManifestsByKind(manifests, test.order) {
buf.WriteString(r.Name)
}
if got := buf.String(); got != test.expected {
t.Errorf("Expected %q, got %q", test.expected, got)
}
})
}
}
func TestKindSorterNamespaceAgainstUnknown(t *testing.T) {
unknown := Manifest{
Name: "a",
Head: &SimpleHead{Kind: "Unknown"},
}
namespace := Manifest{
Name: "b",
Head: &SimpleHead{Kind: "Namespace"},
}
manifests := []Manifest{unknown, namespace}
manifests = sortManifestsByKind(manifests, InstallOrder)
expectedOrder := []Manifest{namespace, unknown}
for i, manifest := range manifests {
if expectedOrder[i].Name != manifest.Name {
t.Errorf("Expected %s, got %s", expectedOrder[i].Name, manifest.Name)
}
}
}
// test hook sorting with a small subset of kinds, since it uses the same algorithm as sortManifestsByKind
func TestKindSorterForHooks(t *testing.T) {
hooks := []*release.Hook{
{
Name: "i",
Kind: "ClusterRole",
},
{
Name: "j",
Kind: "ClusterRoleBinding",
},
{
Name: "c",
Kind: "LimitRange",
},
{
Name: "a",
Kind: "Namespace",
},
}
for _, test := range []struct {
description string
order KindSortOrder
expected string
}{
{"install", InstallOrder, "acij"},
{"uninstall", UninstallOrder, "jica"},
} {
var buf bytes.Buffer
t.Run(test.description, func(t *testing.T) {
if got, want := len(test.expected), len(hooks); got != want {
t.Fatalf("Expected %d names in order, got %d", want, got)
}
defer buf.Reset()
orig := hooks
for _, r := range sortHooksByKind(hooks, test.order) {
buf.WriteString(r.Name)
}
for i, hook := range orig {
if hook != hooks[i] {
t.Fatal("Expected input to sortHooksByKind to stay the same")
}
}
if got := buf.String(); got != test.expected {
t.Errorf("Expected %q, got %q", test.expected, got)
}
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/v1/util/kind_sorter.go | pkg/release/v1/util/kind_sorter.go | /*
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 util
import (
"sort"
release "helm.sh/helm/v4/pkg/release/v1"
)
// KindSortOrder is an ordering of Kinds.
type KindSortOrder []string
// InstallOrder is the order in which manifests should be installed (by Kind).
//
// Those occurring earlier in the list get installed before those occurring later in the list.
var InstallOrder KindSortOrder = []string{
"PriorityClass",
"Namespace",
"NetworkPolicy",
"ResourceQuota",
"LimitRange",
"PodSecurityPolicy",
"PodDisruptionBudget",
"ServiceAccount",
"Secret",
"SecretList",
"ConfigMap",
"StorageClass",
"PersistentVolume",
"PersistentVolumeClaim",
"CustomResourceDefinition",
"ClusterRole",
"ClusterRoleList",
"ClusterRoleBinding",
"ClusterRoleBindingList",
"Role",
"RoleList",
"RoleBinding",
"RoleBindingList",
"Service",
"DaemonSet",
"Pod",
"ReplicationController",
"ReplicaSet",
"Deployment",
"HorizontalPodAutoscaler",
"StatefulSet",
"Job",
"CronJob",
"IngressClass",
"Ingress",
"APIService",
"MutatingWebhookConfiguration",
"ValidatingWebhookConfiguration",
}
// UninstallOrder is the order in which manifests should be uninstalled (by Kind).
//
// Those occurring earlier in the list get uninstalled before those occurring later in the list.
var UninstallOrder KindSortOrder = []string{
// For uninstall, we remove validation before mutation to ensure webhooks don't block removal
"ValidatingWebhookConfiguration",
"MutatingWebhookConfiguration",
"APIService",
"Ingress",
"IngressClass",
"Service",
"CronJob",
"Job",
"StatefulSet",
"HorizontalPodAutoscaler",
"Deployment",
"ReplicaSet",
"ReplicationController",
"Pod",
"DaemonSet",
"RoleBindingList",
"RoleBinding",
"RoleList",
"Role",
"ClusterRoleBindingList",
"ClusterRoleBinding",
"ClusterRoleList",
"ClusterRole",
"CustomResourceDefinition",
"PersistentVolumeClaim",
"PersistentVolume",
"StorageClass",
"ConfigMap",
"SecretList",
"Secret",
"ServiceAccount",
"PodDisruptionBudget",
"PodSecurityPolicy",
"LimitRange",
"ResourceQuota",
"NetworkPolicy",
"Namespace",
"PriorityClass",
}
// sort manifests by kind.
//
// Results are sorted by 'ordering', keeping order of items with equal kind/priority
func sortManifestsByKind(manifests []Manifest, ordering KindSortOrder) []Manifest {
sort.SliceStable(manifests, func(i, j int) bool {
return lessByKind(manifests[i], manifests[j], manifests[i].Head.Kind, manifests[j].Head.Kind, ordering)
})
return manifests
}
// sort hooks by kind, using an out-of-place sort to preserve the input parameters.
//
// Results are sorted by 'ordering', keeping order of items with equal kind/priority
func sortHooksByKind(hooks []*release.Hook, ordering KindSortOrder) []*release.Hook {
h := hooks
sort.SliceStable(h, func(i, j int) bool {
return lessByKind(h[i], h[j], h[i].Kind, h[j].Kind, ordering)
})
return h
}
func lessByKind(_ interface{}, _ interface{}, kindA string, kindB string, o KindSortOrder) bool {
ordering := make(map[string]int, len(o))
for v, k := range o {
ordering[k] = v
}
first, aok := ordering[kindA]
second, bok := ordering[kindB]
if !aok && !bok {
// if both are unknown then sort alphabetically by kind, keep original order if same kind
if kindA != kindB {
return kindA < kindB
}
return first < second
}
// unknown kind is last
if !aok {
return false
}
if !bok {
return true
}
// sort different kinds, keep original order if same priority
return first < second
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/release/common/status.go | pkg/release/common/status.go | /*
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 common
// Status is the status of a release
type Status string
// Describe the status of a release
// NOTE: Make sure to update cmd/helm/status.go when adding or modifying any of these statuses.
const (
// StatusUnknown indicates that a release is in an uncertain state.
StatusUnknown Status = "unknown"
// StatusDeployed indicates that the release has been pushed to Kubernetes.
StatusDeployed Status = "deployed"
// StatusUninstalled indicates that a release has been uninstalled from Kubernetes.
StatusUninstalled Status = "uninstalled"
// StatusSuperseded indicates that this release object is outdated and a newer one exists.
StatusSuperseded Status = "superseded"
// StatusFailed indicates that the release was not successfully deployed.
StatusFailed Status = "failed"
// StatusUninstalling indicates that an uninstall operation is underway.
StatusUninstalling Status = "uninstalling"
// StatusPendingInstall indicates that an install operation is underway.
StatusPendingInstall Status = "pending-install"
// StatusPendingUpgrade indicates that an upgrade operation is underway.
StatusPendingUpgrade Status = "pending-upgrade"
// StatusPendingRollback indicates that a rollback operation is underway.
StatusPendingRollback Status = "pending-rollback"
)
func (x Status) String() string { return string(x) }
// IsPending determines if this status is a state or a transition.
func (x Status) IsPending() bool {
return x == StatusPendingInstall || x == StatusPendingUpgrade || x == StatusPendingRollback
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/storage.go | pkg/storage/storage.go | /*
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 storage // import "helm.sh/helm/v4/pkg/storage"
import (
"errors"
"fmt"
"log/slog"
"strings"
"helm.sh/helm/v4/internal/logging"
"helm.sh/helm/v4/pkg/release"
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
relutil "helm.sh/helm/v4/pkg/release/v1/util"
"helm.sh/helm/v4/pkg/storage/driver"
)
// HelmStorageType is the type field of the Kubernetes storage object which stores the Helm release
// version. It is modified slightly replacing the '/': sh.helm/release.v1
// Note: The version 'v1' is incremented if the release object metadata is
// modified between major releases.
// This constant is used as a prefix for the Kubernetes storage object name.
const HelmStorageType = "sh.helm.release.v1"
// Storage represents a storage engine for a Release.
type Storage struct {
driver.Driver
// MaxHistory specifies the maximum number of historical releases that will
// be retained, including the most recent release. Values of 0 or less are
// ignored (meaning no limits are imposed).
MaxHistory int
// Embed a LogHolder to provide logger functionality
logging.LogHolder
}
// Get retrieves the release from storage. An error is returned
// if the storage driver failed to fetch the release, or the
// release identified by the key, version pair does not exist.
func (s *Storage) Get(name string, version int) (release.Releaser, error) {
s.Logger().Debug("getting release", "key", makeKey(name, version))
return s.Driver.Get(makeKey(name, version))
}
// Create creates a new storage entry holding the release. An
// error is returned if the storage driver fails to store the
// release, or a release with an identical key already exists.
func (s *Storage) Create(rls release.Releaser) error {
rac, err := release.NewAccessor(rls)
if err != nil {
return err
}
s.Logger().Debug("creating release", "key", makeKey(rac.Name(), rac.Version()))
if s.MaxHistory > 0 {
// Want to make space for one more release.
if err := s.removeLeastRecent(rac.Name(), s.MaxHistory-1); err != nil &&
!errors.Is(err, driver.ErrReleaseNotFound) {
return err
}
}
return s.Driver.Create(makeKey(rac.Name(), rac.Version()), rls)
}
// Update updates the release in storage. An error is returned if the
// storage backend fails to update the release or if the release
// does not exist.
func (s *Storage) Update(rls release.Releaser) error {
rac, err := release.NewAccessor(rls)
if err != nil {
return err
}
s.Logger().Debug("updating release", "key", makeKey(rac.Name(), rac.Version()))
return s.Driver.Update(makeKey(rac.Name(), rac.Version()), rls)
}
// Delete deletes the release from storage. An error is returned if
// the storage backend fails to delete the release or if the release
// does not exist.
func (s *Storage) Delete(name string, version int) (release.Releaser, error) {
s.Logger().Debug("deleting release", "key", makeKey(name, version))
return s.Driver.Delete(makeKey(name, version))
}
// ListReleases returns all releases from storage. An error is returned if the
// storage backend fails to retrieve the releases.
func (s *Storage) ListReleases() ([]release.Releaser, error) {
s.Logger().Debug("listing all releases in storage")
return s.List(func(_ release.Releaser) bool { return true })
}
// releaserToV1Release is a helper function to convert a v1 release passed by interface
// into the type object.
func releaserToV1Release(rel release.Releaser) (*rspb.Release, error) {
switch r := rel.(type) {
case rspb.Release:
return &r, nil
case *rspb.Release:
return r, nil
case nil:
return nil, nil
default:
return nil, fmt.Errorf("unsupported release type: %T", rel)
}
}
// ListUninstalled returns all releases with Status == UNINSTALLED. An error is returned
// if the storage backend fails to retrieve the releases.
func (s *Storage) ListUninstalled() ([]release.Releaser, error) {
s.Logger().Debug("listing uninstalled releases in storage")
return s.List(func(rls release.Releaser) bool {
rel, err := releaserToV1Release(rls)
if err != nil {
// This will only happen if calling code does not pass the proper types. This is
// a problem with the application and not user data.
s.Logger().Error("unable to convert release to typed release", slog.Any("error", err))
panic(fmt.Sprintf("unable to convert release to typed release: %s", err))
}
return relutil.StatusFilter(common.StatusUninstalled).Check(rel)
})
}
// ListDeployed returns all releases with Status == DEPLOYED. An error is returned
// if the storage backend fails to retrieve the releases.
func (s *Storage) ListDeployed() ([]release.Releaser, error) {
s.Logger().Debug("listing all deployed releases in storage")
return s.List(func(rls release.Releaser) bool {
rel, err := releaserToV1Release(rls)
if err != nil {
// This will only happen if calling code does not pass the proper types. This is
// a problem with the application and not user data.
s.Logger().Error("unable to convert release to typed release", slog.Any("error", err))
panic(fmt.Sprintf("unable to convert release to typed release: %s", err))
}
return relutil.StatusFilter(common.StatusDeployed).Check(rel)
})
}
// Deployed returns the last deployed release with the provided release name, or
// returns driver.NewErrNoDeployedReleases if not found.
func (s *Storage) Deployed(name string) (release.Releaser, error) {
ls, err := s.DeployedAll(name)
if err != nil {
return nil, err
}
if len(ls) == 0 {
return nil, driver.NewErrNoDeployedReleases(name)
}
rls, err := releaseListToV1List(ls)
if err != nil {
return nil, err
}
// If executed concurrently, Helm's database gets corrupted
// and multiple releases are DEPLOYED. Take the latest.
relutil.Reverse(rls, relutil.SortByRevision)
return rls[0], nil
}
func releaseListToV1List(ls []release.Releaser) ([]*rspb.Release, error) {
rls := make([]*rspb.Release, 0, len(ls))
for _, val := range ls {
rel, err := releaserToV1Release(val)
if err != nil {
return nil, err
}
rls = append(rls, rel)
}
return rls, nil
}
// DeployedAll returns all deployed releases with the provided name, or
// returns driver.NewErrNoDeployedReleases if not found.
func (s *Storage) DeployedAll(name string) ([]release.Releaser, error) {
s.Logger().Debug("getting deployed releases", "name", name)
ls, err := s.Query(map[string]string{
"name": name,
"owner": "helm",
"status": "deployed",
})
if err == nil {
return ls, nil
}
if strings.Contains(err.Error(), "not found") {
return nil, driver.NewErrNoDeployedReleases(name)
}
return nil, err
}
// History returns the revision history for the release with the provided name, or
// returns driver.ErrReleaseNotFound if no such release name exists.
func (s *Storage) History(name string) ([]release.Releaser, error) {
s.Logger().Debug("getting release history", "name", name)
return s.Query(map[string]string{"name": name, "owner": "helm"})
}
// removeLeastRecent removes items from history until the length number of releases
// does not exceed max.
//
// We allow max to be set explicitly so that calling functions can "make space"
// for the new records they are going to write.
func (s *Storage) removeLeastRecent(name string, maximum int) error {
if maximum < 0 {
return nil
}
h, err := s.History(name)
if err != nil {
return err
}
if len(h) <= maximum {
return nil
}
rls, err := releaseListToV1List(h)
if err != nil {
return err
}
// We want oldest to newest
relutil.SortByRevision(rls)
lastDeployed, err := s.Deployed(name)
if err != nil && !errors.Is(err, driver.ErrNoDeployedReleases) {
return err
}
var toDelete []release.Releaser
for _, rel := range rls {
// once we have enough releases to delete to reach the maximum, stop
if len(rls)-len(toDelete) == maximum {
break
}
if lastDeployed != nil {
ldac, err := release.NewAccessor(lastDeployed)
if err != nil {
return err
}
if rel.Version != ldac.Version() {
toDelete = append(toDelete, rel)
}
} else {
toDelete = append(toDelete, rel)
}
}
// Delete as many as possible. In the case of API throughput limitations,
// multiple invocations of this function will eventually delete them all.
errs := []error{}
for _, rel := range toDelete {
rac, err := release.NewAccessor(rel)
if err != nil {
errs = append(errs, err)
continue
}
err = s.deleteReleaseVersion(name, rac.Version())
if err != nil {
errs = append(errs, err)
}
}
s.Logger().Debug("pruned records", "count", len(toDelete), "release", name, "errors", len(errs))
switch c := len(errs); c {
case 0:
return nil
case 1:
return errs[0]
default:
return fmt.Errorf("encountered %d deletion errors. First is: %w", c, errs[0])
}
}
func (s *Storage) deleteReleaseVersion(name string, version int) error {
key := makeKey(name, version)
_, err := s.Delete(name, version)
if err != nil {
s.Logger().Debug("error pruning release", slog.String("key", key), slog.Any("error", err))
return err
}
return nil
}
// Last fetches the last revision of the named release.
func (s *Storage) Last(name string) (release.Releaser, error) {
s.Logger().Debug("getting last revision", "name", name)
h, err := s.History(name)
if err != nil {
return nil, err
}
if len(h) == 0 {
return nil, fmt.Errorf("no revision for release %q", name)
}
rls, err := releaseListToV1List(h)
if err != nil {
return nil, err
}
relutil.Reverse(rls, relutil.SortByRevision)
return rls[0], nil
}
// makeKey concatenates the Kubernetes storage object type, a release name and version
// into a string with format:```<helm_storage_type>.<release_name>.v<release_version>```.
// The storage type is prepended to keep name uniqueness between different
// release storage types. An example of clash when not using the type:
// https://github.com/helm/helm/issues/6435.
// This key is used to uniquely identify storage objects.
func makeKey(rlsname string, version int) string {
return fmt.Sprintf("%s.%s.v%d", HelmStorageType, rlsname, version)
}
// Init initializes a new storage backend with the driver d.
// If d is nil, the default in-memory driver is used.
func Init(d driver.Driver) *Storage {
// default driver is in memory
if d == nil {
d = driver.NewMemory()
}
s := &Storage{
Driver: d,
}
// Get logger from driver if it implements the LoggerSetterGetter interface
if ls, ok := d.(logging.LoggerSetterGetter); ok {
ls.SetLogger(s.Logger().Handler())
} else {
// If the driver does not implement the LoggerSetterGetter interface, set the default logger
s.SetLogger(slog.Default().Handler())
}
return s
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/storage_test.go | pkg/storage/storage_test.go | /*
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 storage // import "helm.sh/helm/v4/pkg/storage"
import (
"errors"
"fmt"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/pkg/release"
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
"helm.sh/helm/v4/pkg/storage/driver"
)
func TestStorageCreate(t *testing.T) {
// initialize storage
storage := Init(driver.NewMemory())
// create fake release
rls := ReleaseTestData{
Name: "angry-beaver",
Version: 1,
}.ToRelease()
assertErrNil(t.Fatal, storage.Create(rls), "StoreRelease")
// fetch the release
res, err := storage.Get(rls.Name, rls.Version)
assertErrNil(t.Fatal, err, "QueryRelease")
// verify the fetched and created release are the same
if !reflect.DeepEqual(rls, res) {
t.Fatalf("Expected %v, got %v", rls, res)
}
}
func TestStorageUpdate(t *testing.T) {
// initialize storage
storage := Init(driver.NewMemory())
// create fake release
rls := ReleaseTestData{
Name: "angry-beaver",
Version: 1,
Status: common.StatusDeployed,
}.ToRelease()
assertErrNil(t.Fatal, storage.Create(rls), "StoreRelease")
// modify the release
rls.Info.Status = common.StatusUninstalled
assertErrNil(t.Fatal, storage.Update(rls), "UpdateRelease")
// retrieve the updated release
res, err := storage.Get(rls.Name, rls.Version)
assertErrNil(t.Fatal, err, "QueryRelease")
// verify updated and fetched releases are the same.
if !reflect.DeepEqual(rls, res) {
t.Fatalf("Expected %v, got %v", rls, res)
}
}
func TestStorageDelete(t *testing.T) {
// initialize storage
storage := Init(driver.NewMemory())
// create fake release
rls := ReleaseTestData{
Name: "angry-beaver",
Version: 1,
}.ToRelease()
rls2 := ReleaseTestData{
Name: "angry-beaver",
Version: 2,
}.ToRelease()
assertErrNil(t.Fatal, storage.Create(rls), "StoreRelease")
assertErrNil(t.Fatal, storage.Create(rls2), "StoreRelease")
// delete the release
res, err := storage.Delete(rls.Name, rls.Version)
assertErrNil(t.Fatal, err, "DeleteRelease")
// verify updated and fetched releases are the same.
if !reflect.DeepEqual(rls, res) {
t.Fatalf("Expected %v, got %v", rls, res)
}
hist, err := storage.History(rls.Name)
if err != nil {
t.Errorf("unexpected error: %s", err)
}
rhist, err := releaseListToV1List(hist)
assert.NoError(t, err)
// We have now deleted one of the two records.
if len(rhist) != 1 {
t.Errorf("expected 1 record for deleted release version, got %d", len(hist))
}
if rhist[0].Version != 2 {
t.Errorf("Expected version to be 2, got %d", rhist[0].Version)
}
}
func TestStorageList(t *testing.T) {
// initialize storage
storage := Init(driver.NewMemory())
// setup storage with test releases
setup := func() {
// release records
rls0 := ReleaseTestData{Name: "happy-catdog", Status: common.StatusSuperseded}.ToRelease()
rls1 := ReleaseTestData{Name: "livid-human", Status: common.StatusSuperseded}.ToRelease()
rls2 := ReleaseTestData{Name: "relaxed-cat", Status: common.StatusSuperseded}.ToRelease()
rls3 := ReleaseTestData{Name: "hungry-hippo", Status: common.StatusDeployed}.ToRelease()
rls4 := ReleaseTestData{Name: "angry-beaver", Status: common.StatusDeployed}.ToRelease()
rls5 := ReleaseTestData{Name: "opulent-frog", Status: common.StatusUninstalled}.ToRelease()
rls6 := ReleaseTestData{Name: "happy-liger", Status: common.StatusUninstalled}.ToRelease()
// create the release records in the storage
assertErrNil(t.Fatal, storage.Create(rls0), "Storing release 'rls0'")
assertErrNil(t.Fatal, storage.Create(rls1), "Storing release 'rls1'")
assertErrNil(t.Fatal, storage.Create(rls2), "Storing release 'rls2'")
assertErrNil(t.Fatal, storage.Create(rls3), "Storing release 'rls3'")
assertErrNil(t.Fatal, storage.Create(rls4), "Storing release 'rls4'")
assertErrNil(t.Fatal, storage.Create(rls5), "Storing release 'rls5'")
assertErrNil(t.Fatal, storage.Create(rls6), "Storing release 'rls6'")
}
var listTests = []struct {
Description string
NumExpected int
ListFunc func() ([]release.Releaser, error)
}{
{"ListDeployed", 2, storage.ListDeployed},
{"ListReleases", 7, storage.ListReleases},
{"ListUninstalled", 2, storage.ListUninstalled},
}
setup()
for _, tt := range listTests {
list, err := tt.ListFunc()
assertErrNil(t.Fatal, err, tt.Description)
// verify the count of releases returned
if len(list) != tt.NumExpected {
t.Errorf("ListReleases(%s): expected %d, actual %d",
tt.Description,
tt.NumExpected,
len(list))
}
}
}
func TestStorageDeployed(t *testing.T) {
storage := Init(driver.NewMemory())
const name = "angry-bird"
const vers = 4
// setup storage with test releases
setup := func() {
// release records
rls0 := ReleaseTestData{Name: name, Version: 1, Status: common.StatusSuperseded}.ToRelease()
rls1 := ReleaseTestData{Name: name, Version: 2, Status: common.StatusSuperseded}.ToRelease()
rls2 := ReleaseTestData{Name: name, Version: 3, Status: common.StatusSuperseded}.ToRelease()
rls3 := ReleaseTestData{Name: name, Version: 4, Status: common.StatusDeployed}.ToRelease()
// create the release records in the storage
assertErrNil(t.Fatal, storage.Create(rls0), "Storing release 'angry-bird' (v1)")
assertErrNil(t.Fatal, storage.Create(rls1), "Storing release 'angry-bird' (v2)")
assertErrNil(t.Fatal, storage.Create(rls2), "Storing release 'angry-bird' (v3)")
assertErrNil(t.Fatal, storage.Create(rls3), "Storing release 'angry-bird' (v4)")
}
setup()
rls, err := storage.Last(name)
if err != nil {
t.Fatalf("Failed to query for deployed release: %s\n", err)
}
rel, err := releaserToV1Release(rls)
assert.NoError(t, err)
switch {
case rls == nil:
t.Fatalf("Release is nil")
case rel.Name != name:
t.Fatalf("Expected release name %q, actual %q\n", name, rel.Name)
case rel.Version != vers:
t.Fatalf("Expected release version %d, actual %d\n", vers, rel.Version)
case rel.Info.Status != common.StatusDeployed:
t.Fatalf("Expected release status 'DEPLOYED', actual %s\n", rel.Info.Status.String())
}
}
func TestStorageDeployedWithCorruption(t *testing.T) {
storage := Init(driver.NewMemory())
const name = "angry-bird"
const vers = int(4)
// setup storage with test releases
setup := func() {
// release records (notice odd order and corruption)
rls0 := ReleaseTestData{Name: name, Version: 1, Status: common.StatusSuperseded}.ToRelease()
rls1 := ReleaseTestData{Name: name, Version: 4, Status: common.StatusDeployed}.ToRelease()
rls2 := ReleaseTestData{Name: name, Version: 3, Status: common.StatusSuperseded}.ToRelease()
rls3 := ReleaseTestData{Name: name, Version: 2, Status: common.StatusDeployed}.ToRelease()
// create the release records in the storage
assertErrNil(t.Fatal, storage.Create(rls0), "Storing release 'angry-bird' (v1)")
assertErrNil(t.Fatal, storage.Create(rls1), "Storing release 'angry-bird' (v2)")
assertErrNil(t.Fatal, storage.Create(rls2), "Storing release 'angry-bird' (v3)")
assertErrNil(t.Fatal, storage.Create(rls3), "Storing release 'angry-bird' (v4)")
}
setup()
rls, err := storage.Deployed(name)
if err != nil {
t.Fatalf("Failed to query for deployed release: %s\n", err)
}
rel, err := releaserToV1Release(rls)
assert.NoError(t, err)
switch {
case rls == nil:
t.Fatalf("Release is nil")
case rel.Name != name:
t.Fatalf("Expected release name %q, actual %q\n", name, rel.Name)
case rel.Version != vers:
t.Fatalf("Expected release version %d, actual %d\n", vers, rel.Version)
case rel.Info.Status != common.StatusDeployed:
t.Fatalf("Expected release status 'DEPLOYED', actual %s\n", rel.Info.Status.String())
}
}
func TestStorageHistory(t *testing.T) {
storage := Init(driver.NewMemory())
const name = "angry-bird"
// setup storage with test releases
setup := func() {
// release records
rls0 := ReleaseTestData{Name: name, Version: 1, Status: common.StatusSuperseded}.ToRelease()
rls1 := ReleaseTestData{Name: name, Version: 2, Status: common.StatusSuperseded}.ToRelease()
rls2 := ReleaseTestData{Name: name, Version: 3, Status: common.StatusSuperseded}.ToRelease()
rls3 := ReleaseTestData{Name: name, Version: 4, Status: common.StatusDeployed}.ToRelease()
// create the release records in the storage
assertErrNil(t.Fatal, storage.Create(rls0), "Storing release 'angry-bird' (v1)")
assertErrNil(t.Fatal, storage.Create(rls1), "Storing release 'angry-bird' (v2)")
assertErrNil(t.Fatal, storage.Create(rls2), "Storing release 'angry-bird' (v3)")
assertErrNil(t.Fatal, storage.Create(rls3), "Storing release 'angry-bird' (v4)")
}
setup()
h, err := storage.History(name)
if err != nil {
t.Fatalf("Failed to query for release history (%q): %s\n", name, err)
}
if len(h) != 4 {
t.Fatalf("Release history (%q) is empty\n", name)
}
}
var errMaxHistoryMockDriverSomethingHappened = errors.New("something happened")
type MaxHistoryMockDriver struct {
Driver driver.Driver
}
func NewMaxHistoryMockDriver(d driver.Driver) *MaxHistoryMockDriver {
return &MaxHistoryMockDriver{Driver: d}
}
func (d *MaxHistoryMockDriver) Create(key string, rls release.Releaser) error {
return d.Driver.Create(key, rls)
}
func (d *MaxHistoryMockDriver) Update(key string, rls release.Releaser) error {
return d.Driver.Update(key, rls)
}
func (d *MaxHistoryMockDriver) Delete(_ string) (release.Releaser, error) {
return nil, errMaxHistoryMockDriverSomethingHappened
}
func (d *MaxHistoryMockDriver) Get(key string) (release.Releaser, error) {
return d.Driver.Get(key)
}
func (d *MaxHistoryMockDriver) List(filter func(release.Releaser) bool) ([]release.Releaser, error) {
return d.Driver.List(filter)
}
func (d *MaxHistoryMockDriver) Query(labels map[string]string) ([]release.Releaser, error) {
return d.Driver.Query(labels)
}
func (d *MaxHistoryMockDriver) Name() string {
return d.Driver.Name()
}
func TestMaxHistoryErrorHandling(t *testing.T) {
//func TestStorageRemoveLeastRecentWithError(t *testing.T) {
storage := Init(NewMaxHistoryMockDriver(driver.NewMemory()))
storage.MaxHistory = 1
const name = "angry-bird"
// setup storage with test releases
setup := func() {
// release records
rls1 := ReleaseTestData{Name: name, Version: 1, Status: common.StatusSuperseded}.ToRelease()
// create the release records in the storage
assertErrNil(t.Fatal, storage.Driver.Create(makeKey(rls1.Name, rls1.Version), rls1), "Storing release 'angry-bird' (v1)")
}
setup()
rls2 := ReleaseTestData{Name: name, Version: 2, Status: common.StatusSuperseded}.ToRelease()
wantErr := errMaxHistoryMockDriverSomethingHappened
gotErr := storage.Create(rls2)
if !errors.Is(gotErr, wantErr) {
t.Fatalf("Storing release 'angry-bird' (v2) should return the error %#v, but returned %#v", wantErr, gotErr)
}
}
func TestStorageRemoveLeastRecent(t *testing.T) {
storage := Init(driver.NewMemory())
// Make sure that specifying this at the outset doesn't cause any bugs.
storage.MaxHistory = 10
const name = "angry-bird"
// setup storage with test releases
setup := func() {
// release records
rls0 := ReleaseTestData{Name: name, Version: 1, Status: common.StatusSuperseded}.ToRelease()
rls1 := ReleaseTestData{Name: name, Version: 2, Status: common.StatusSuperseded}.ToRelease()
rls2 := ReleaseTestData{Name: name, Version: 3, Status: common.StatusSuperseded}.ToRelease()
rls3 := ReleaseTestData{Name: name, Version: 4, Status: common.StatusDeployed}.ToRelease()
// create the release records in the storage
assertErrNil(t.Fatal, storage.Create(rls0), "Storing release 'angry-bird' (v1)")
assertErrNil(t.Fatal, storage.Create(rls1), "Storing release 'angry-bird' (v2)")
assertErrNil(t.Fatal, storage.Create(rls2), "Storing release 'angry-bird' (v3)")
assertErrNil(t.Fatal, storage.Create(rls3), "Storing release 'angry-bird' (v4)")
}
setup()
// Because we have not set a limit, we expect 4.
expect := 4
if hist, err := storage.History(name); err != nil {
t.Fatal(err)
} else if len(hist) != expect {
t.Fatalf("expected %d items in history, got %d", expect, len(hist))
}
storage.MaxHistory = 3
rls5 := ReleaseTestData{Name: name, Version: 5, Status: common.StatusDeployed}.ToRelease()
assertErrNil(t.Fatal, storage.Create(rls5), "Storing release 'angry-bird' (v5)")
// On inserting the 5th record, we expect two records to be pruned from history.
hist, err := storage.History(name)
assert.NoError(t, err)
rhist, err := releaseListToV1List(hist)
assert.NoError(t, err)
if err != nil {
t.Fatal(err)
} else if len(rhist) != storage.MaxHistory {
for _, item := range rhist {
t.Logf("%s %v", item.Name, item.Version)
}
t.Fatalf("expected %d items in history, got %d", storage.MaxHistory, len(rhist))
}
// We expect the existing records to be 3, 4, and 5.
for i, item := range rhist {
v := item.Version
if expect := i + 3; v != expect {
t.Errorf("Expected release %d, got %d", expect, v)
}
}
}
func TestStorageDoNotDeleteDeployed(t *testing.T) {
storage := Init(driver.NewMemory())
storage.MaxHistory = 3
const name = "angry-bird"
// setup storage with test releases
setup := func() {
// release records
rls0 := ReleaseTestData{Name: name, Version: 1, Status: common.StatusSuperseded}.ToRelease()
rls1 := ReleaseTestData{Name: name, Version: 2, Status: common.StatusDeployed}.ToRelease()
rls2 := ReleaseTestData{Name: name, Version: 3, Status: common.StatusFailed}.ToRelease()
rls3 := ReleaseTestData{Name: name, Version: 4, Status: common.StatusFailed}.ToRelease()
// create the release records in the storage
assertErrNil(t.Fatal, storage.Create(rls0), "Storing release 'angry-bird' (v1)")
assertErrNil(t.Fatal, storage.Create(rls1), "Storing release 'angry-bird' (v2)")
assertErrNil(t.Fatal, storage.Create(rls2), "Storing release 'angry-bird' (v3)")
assertErrNil(t.Fatal, storage.Create(rls3), "Storing release 'angry-bird' (v4)")
}
setup()
rls5 := ReleaseTestData{Name: name, Version: 5, Status: common.StatusFailed}.ToRelease()
assertErrNil(t.Fatal, storage.Create(rls5), "Storing release 'angry-bird' (v5)")
// On inserting the 5th record, we expect a total of 3 releases, but we expect version 2
// (the only deployed release), to still exist
hist, err := storage.History(name)
if err != nil {
t.Fatal(err)
} else if len(hist) != storage.MaxHistory {
rhist, err := releaseListToV1List(hist)
assert.NoError(t, err)
for _, item := range rhist {
t.Logf("%s %v", item.Name, item.Version)
}
t.Fatalf("expected %d items in history, got %d", storage.MaxHistory, len(rhist))
}
expectedVersions := map[int]bool{
2: true,
4: true,
5: true,
}
rhist, err := releaseListToV1List(hist)
assert.NoError(t, err)
for _, item := range rhist {
if !expectedVersions[item.Version] {
t.Errorf("Release version %d, found when not expected", item.Version)
}
}
}
func TestStorageLast(t *testing.T) {
storage := Init(driver.NewMemory())
const name = "angry-bird"
// Set up storage with test releases.
setup := func() {
// release records
rls0 := ReleaseTestData{Name: name, Version: 1, Status: common.StatusSuperseded}.ToRelease()
rls1 := ReleaseTestData{Name: name, Version: 2, Status: common.StatusSuperseded}.ToRelease()
rls2 := ReleaseTestData{Name: name, Version: 3, Status: common.StatusSuperseded}.ToRelease()
rls3 := ReleaseTestData{Name: name, Version: 4, Status: common.StatusFailed}.ToRelease()
// create the release records in the storage
assertErrNil(t.Fatal, storage.Create(rls0), "Storing release 'angry-bird' (v1)")
assertErrNil(t.Fatal, storage.Create(rls1), "Storing release 'angry-bird' (v2)")
assertErrNil(t.Fatal, storage.Create(rls2), "Storing release 'angry-bird' (v3)")
assertErrNil(t.Fatal, storage.Create(rls3), "Storing release 'angry-bird' (v4)")
}
setup()
h, err := storage.Last(name)
if err != nil {
t.Fatalf("Failed to query for release history (%q): %s\n", name, err)
}
rel, err := releaserToV1Release(h)
assert.NoError(t, err)
if rel.Version != 4 {
t.Errorf("Expected revision 4, got %d", rel.Version)
}
}
// TestUpgradeInitiallyFailedReleaseWithHistoryLimit tests a case when there are no deployed release yet, but history limit has been
// reached: the has-no-deployed-releases error should not occur in such case.
func TestUpgradeInitiallyFailedReleaseWithHistoryLimit(t *testing.T) {
storage := Init(driver.NewMemory())
storage.MaxHistory = 4
const name = "angry-bird"
// setup storage with test releases
setup := func() {
// release records
rls0 := ReleaseTestData{Name: name, Version: 1, Status: common.StatusFailed}.ToRelease()
rls1 := ReleaseTestData{Name: name, Version: 2, Status: common.StatusFailed}.ToRelease()
rls2 := ReleaseTestData{Name: name, Version: 3, Status: common.StatusFailed}.ToRelease()
rls3 := ReleaseTestData{Name: name, Version: 4, Status: common.StatusFailed}.ToRelease()
// create the release records in the storage
assertErrNil(t.Fatal, storage.Create(rls0), "Storing release 'angry-bird' (v1)")
assertErrNil(t.Fatal, storage.Create(rls1), "Storing release 'angry-bird' (v2)")
assertErrNil(t.Fatal, storage.Create(rls2), "Storing release 'angry-bird' (v3)")
assertErrNil(t.Fatal, storage.Create(rls3), "Storing release 'angry-bird' (v4)")
hist, err := storage.History(name)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
wantHistoryLen := 4
if len(hist) != wantHistoryLen {
t.Fatalf("expected history of release %q to contain %d releases, got %d", name, wantHistoryLen, len(hist))
}
}
setup()
rls5 := ReleaseTestData{Name: name, Version: 5, Status: common.StatusFailed}.ToRelease()
err := storage.Create(rls5)
if err != nil {
t.Fatalf("Failed to create a new release version: %s", err)
}
hist, err := storage.History(name)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
rhist, err := releaseListToV1List(hist)
assert.NoError(t, err)
for i, rel := range rhist {
wantVersion := i + 2
if rel.Version != wantVersion {
t.Fatalf("Expected history release %d version to equal %d, got %d", i+1, wantVersion, rel.Version)
}
wantStatus := common.StatusFailed
if rel.Info.Status != wantStatus {
t.Fatalf("Expected history release %d status to equal %q, got %q", i+1, wantStatus, rel.Info.Status)
}
}
}
type ReleaseTestData struct {
Name string
Version int
Manifest string
Namespace string
Status common.Status
}
func (test ReleaseTestData) ToRelease() *rspb.Release {
return &rspb.Release{
Name: test.Name,
Version: test.Version,
Manifest: test.Manifest,
Namespace: test.Namespace,
Info: &rspb.Info{Status: test.Status},
}
}
func assertErrNil(eh func(args ...interface{}), err error, message string) {
if err != nil {
eh(fmt.Sprintf("%s: %q", message, err))
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/memory_test.go | pkg/storage/driver/memory_test.go | /*
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 driver
import (
"fmt"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/pkg/release"
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
func TestMemoryName(t *testing.T) {
if mem := NewMemory(); mem.Name() != MemoryDriverName {
t.Errorf("Expected name to be %q, got %q", MemoryDriverName, mem.Name())
}
}
func TestMemoryCreate(t *testing.T) {
var tests = []struct {
desc string
rls *rspb.Release
err bool
}{
{
"create should succeed",
releaseStub("rls-c", 1, "default", common.StatusDeployed),
false,
},
{
"create should fail (release already exists)",
releaseStub("rls-a", 1, "default", common.StatusDeployed),
true,
},
{
"create in namespace should succeed",
releaseStub("rls-a", 1, "mynamespace", common.StatusDeployed),
false,
},
{
"create in other namespace should fail (release already exists)",
releaseStub("rls-c", 1, "mynamespace", common.StatusDeployed),
true,
},
}
ts := tsFixtureMemory(t)
for _, tt := range tests {
key := testKey(tt.rls.Name, tt.rls.Version)
rls := tt.rls
if err := ts.Create(key, rls); err != nil {
if !tt.err {
t.Fatalf("failed to create %q: %s", tt.desc, err)
}
} else if tt.err {
t.Fatalf("Did not get expected error for %q\n", tt.desc)
}
}
}
func TestMemoryGet(t *testing.T) {
var tests = []struct {
desc string
key string
namespace string
err bool
}{
{"release key should exist", "rls-a.v1", "default", false},
{"release key should not exist", "rls-a.v5", "default", true},
{"release key in namespace should exist", "rls-c.v1", "mynamespace", false},
{"release key in namespace should not exist", "rls-a.v1", "mynamespace", true},
}
ts := tsFixtureMemory(t)
for _, tt := range tests {
ts.SetNamespace(tt.namespace)
if _, err := ts.Get(tt.key); err != nil {
if !tt.err {
t.Fatalf("Failed %q to get '%s': %q\n", tt.desc, tt.key, err)
}
} else if tt.err {
t.Fatalf("Did not get expected error for %q '%s'\n", tt.desc, tt.key)
}
}
}
func TestMemoryList(t *testing.T) {
ts := tsFixtureMemory(t)
ts.SetNamespace("default")
// list all deployed releases
dpl, err := ts.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusDeployed
})
// check
if err != nil {
t.Errorf("Failed to list deployed releases: %s", err)
}
if len(dpl) != 2 {
t.Errorf("Expected 2 deployed, got %d", len(dpl))
}
// list all superseded releases
ssd, err := ts.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusSuperseded
})
// check
if err != nil {
t.Errorf("Failed to list superseded releases: %s", err)
}
if len(ssd) != 6 {
t.Errorf("Expected 6 superseded, got %d", len(ssd))
}
// list all deleted releases
del, err := ts.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusUninstalled
})
// check
if err != nil {
t.Errorf("Failed to list deleted releases: %s", err)
}
if len(del) != 0 {
t.Errorf("Expected 0 deleted, got %d", len(del))
}
}
func TestMemoryQuery(t *testing.T) {
var tests = []struct {
desc string
xlen int
namespace string
lbs map[string]string
}{
{
"should be 2 query results",
2,
"default",
map[string]string{"status": "deployed"},
},
{
"should be 1 query result",
1,
"mynamespace",
map[string]string{"status": "deployed"},
},
}
ts := tsFixtureMemory(t)
for _, tt := range tests {
ts.SetNamespace(tt.namespace)
l, err := ts.Query(tt.lbs)
if err != nil {
t.Fatalf("Failed to query: %s\n", err)
}
if tt.xlen != len(l) {
t.Fatalf("Expected %d results, actual %d\n", tt.xlen, len(l))
}
}
}
func TestMemoryUpdate(t *testing.T) {
var tests = []struct {
desc string
key string
rls *rspb.Release
err bool
}{
{
"update release status",
"rls-a.v4",
releaseStub("rls-a", 4, "default", common.StatusSuperseded),
false,
},
{
"update release does not exist",
"rls-c.v1",
releaseStub("rls-c", 1, "default", common.StatusUninstalled),
true,
},
{
"update release status in namespace",
"rls-c.v4",
releaseStub("rls-c", 4, "mynamespace", common.StatusSuperseded),
false,
},
{
"update release in namespace does not exist",
"rls-a.v1",
releaseStub("rls-a", 1, "mynamespace", common.StatusUninstalled),
true,
},
}
ts := tsFixtureMemory(t)
for _, tt := range tests {
if err := ts.Update(tt.key, tt.rls); err != nil {
if !tt.err {
t.Fatalf("Failed %q: %s\n", tt.desc, err)
}
continue
} else if tt.err {
t.Fatalf("Did not get expected error for %q '%s'\n", tt.desc, tt.key)
}
ts.SetNamespace(tt.rls.Namespace)
r, err := ts.Get(tt.key)
if err != nil {
t.Fatalf("Failed to get: %s\n", err)
}
if !reflect.DeepEqual(r, tt.rls) {
t.Fatalf("Expected %v, actual %v\n", tt.rls, r)
}
}
}
func TestMemoryDelete(t *testing.T) {
var tests = []struct {
desc string
key string
namespace string
err bool
}{
{"release key should exist", "rls-a.v4", "default", false},
{"release key should not exist", "rls-a.v5", "default", true},
{"release key from other namespace should not exist", "rls-c.v4", "default", true},
{"release key from namespace should exist", "rls-c.v4", "mynamespace", false},
{"release key from namespace should not exist", "rls-c.v5", "mynamespace", true},
{"release key from namespace2 should not exist", "rls-a.v4", "mynamespace", true},
}
ts := tsFixtureMemory(t)
ts.SetNamespace("")
start, err := ts.Query(map[string]string{"status": "deployed"})
if err != nil {
t.Errorf("Query failed: %s", err)
}
startLen := len(start)
for _, tt := range tests {
ts.SetNamespace(tt.namespace)
rel, err := ts.Delete(tt.key)
var rls *rspb.Release
if err == nil {
rls = convertReleaserToV1(t, rel)
}
if err != nil {
if !tt.err {
t.Fatalf("Failed %q to get '%s': %q\n", tt.desc, tt.key, err)
}
continue
} else if tt.err {
t.Fatalf("Did not get expected error for %q '%s'\n", tt.desc, tt.key)
} else if fmt.Sprintf("%s.v%d", rls.Name, rls.Version) != tt.key {
t.Fatalf("Asked for delete on %s, but deleted %d", tt.key, rls.Version)
}
_, err = ts.Get(tt.key)
if err == nil {
t.Errorf("Expected an error when asking for a deleted key")
}
}
// Make sure that the deleted records are gone.
ts.SetNamespace("")
end, err := ts.Query(map[string]string{"status": "deployed"})
if err != nil {
t.Errorf("Query failed: %s", err)
}
endLen := len(end)
if startLen-2 != endLen {
t.Errorf("expected end to be %d instead of %d", startLen-2, endLen)
for _, ee := range end {
rac, err := release.NewAccessor(ee)
assert.NoError(t, err, "unable to get release accessor")
t.Logf("Name: %s, Version: %d", rac.Name(), rac.Version())
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/cfgmaps_test.go | pkg/storage/driver/cfgmaps_test.go | /*
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 driver
import (
"encoding/base64"
"encoding/json"
"errors"
"reflect"
"testing"
v1 "k8s.io/api/core/v1"
"helm.sh/helm/v4/pkg/release"
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
func TestConfigMapName(t *testing.T) {
c := newTestFixtureCfgMaps(t)
if c.Name() != ConfigMapsDriverName {
t.Errorf("Expected name to be %q, got %q", ConfigMapsDriverName, c.Name())
}
}
func TestConfigMapGet(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
cfgmaps := newTestFixtureCfgMaps(t, []*rspb.Release{rel}...)
// get release with key
got, err := cfgmaps.Get(key)
if err != nil {
t.Fatalf("Failed to get release: %s", err)
}
// compare fetched release with original
if !reflect.DeepEqual(rel, got) {
t.Errorf("Expected {%v}, got {%v}", rel, got)
}
}
func TestUncompressedConfigMapGet(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
// Create a test fixture which contains an uncompressed release
cfgmap, err := newConfigMapsObject(key, rel, nil)
if err != nil {
t.Fatalf("Failed to create configmap: %s", err)
}
b, err := json.Marshal(rel)
if err != nil {
t.Fatalf("Failed to marshal release: %s", err)
}
cfgmap.Data["release"] = base64.StdEncoding.EncodeToString(b)
var mock MockConfigMapsInterface
mock.objects = map[string]*v1.ConfigMap{key: cfgmap}
cfgmaps := NewConfigMaps(&mock)
// get release with key
got, err := cfgmaps.Get(key)
if err != nil {
t.Fatalf("Failed to get release: %s", err)
}
// compare fetched release with original
if !reflect.DeepEqual(rel, got) {
t.Errorf("Expected {%v}, got {%v}", rel, got)
}
}
func convertReleaserToV1(t *testing.T, rel release.Releaser) *rspb.Release {
t.Helper()
switch r := rel.(type) {
case rspb.Release:
return &r
case *rspb.Release:
return r
case nil:
return nil
}
t.Fatalf("Unsupported release type: %T", rel)
return nil
}
func TestConfigMapList(t *testing.T) {
cfgmaps := newTestFixtureCfgMaps(t, []*rspb.Release{
releaseStub("key-1", 1, "default", common.StatusUninstalled),
releaseStub("key-2", 1, "default", common.StatusUninstalled),
releaseStub("key-3", 1, "default", common.StatusDeployed),
releaseStub("key-4", 1, "default", common.StatusDeployed),
releaseStub("key-5", 1, "default", common.StatusSuperseded),
releaseStub("key-6", 1, "default", common.StatusSuperseded),
}...)
// list all deleted releases
del, err := cfgmaps.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusUninstalled
})
// check
if err != nil {
t.Errorf("Failed to list deleted: %s", err)
}
if len(del) != 2 {
t.Errorf("Expected 2 deleted, got %d:\n%v\n", len(del), del)
}
// list all deployed releases
dpl, err := cfgmaps.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusDeployed
})
// check
if err != nil {
t.Errorf("Failed to list deployed: %s", err)
}
if len(dpl) != 2 {
t.Errorf("Expected 2 deployed, got %d", len(dpl))
}
// list all superseded releases
ssd, err := cfgmaps.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusSuperseded
})
// check
if err != nil {
t.Errorf("Failed to list superseded: %s", err)
}
if len(ssd) != 2 {
t.Errorf("Expected 2 superseded, got %d", len(ssd))
}
// Check if release having both system and custom labels, this is needed to ensure that selector filtering would work.
rls := convertReleaserToV1(t, ssd[0])
_, ok := rls.Labels["name"]
if !ok {
t.Fatalf("Expected 'name' label in results, actual %v", rls.Labels)
}
_, ok = rls.Labels["key1"]
if !ok {
t.Fatalf("Expected 'key1' label in results, actual %v", rls.Labels)
}
}
func TestConfigMapQuery(t *testing.T) {
cfgmaps := newTestFixtureCfgMaps(t, []*rspb.Release{
releaseStub("key-1", 1, "default", common.StatusUninstalled),
releaseStub("key-2", 1, "default", common.StatusUninstalled),
releaseStub("key-3", 1, "default", common.StatusDeployed),
releaseStub("key-4", 1, "default", common.StatusDeployed),
releaseStub("key-5", 1, "default", common.StatusSuperseded),
releaseStub("key-6", 1, "default", common.StatusSuperseded),
}...)
rls, err := cfgmaps.Query(map[string]string{"status": "deployed"})
if err != nil {
t.Errorf("Failed to query: %s", err)
}
if len(rls) != 2 {
t.Errorf("Expected 2 results, got %d", len(rls))
}
_, err = cfgmaps.Query(map[string]string{"name": "notExist"})
if err != ErrReleaseNotFound {
t.Errorf("Expected {%v}, got {%v}", ErrReleaseNotFound, err)
}
}
func TestConfigMapCreate(t *testing.T) {
cfgmaps := newTestFixtureCfgMaps(t)
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
// store the release in a configmap
if err := cfgmaps.Create(key, rel); err != nil {
t.Fatalf("Failed to create release with key %q: %s", key, err)
}
// get the release back
got, err := cfgmaps.Get(key)
if err != nil {
t.Fatalf("Failed to get release with key %q: %s", key, err)
}
// compare created release with original
if !reflect.DeepEqual(rel, got) {
t.Errorf("Expected {%v}, got {%v}", rel, got)
}
}
func TestConfigMapUpdate(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
cfgmaps := newTestFixtureCfgMaps(t, []*rspb.Release{rel}...)
// modify release status code
rel.Info.Status = common.StatusSuperseded
// perform the update
if err := cfgmaps.Update(key, rel); err != nil {
t.Fatalf("Failed to update release: %s", err)
}
// fetch the updated release
goti, err := cfgmaps.Get(key)
if err != nil {
t.Fatalf("Failed to get release with key %q: %s", key, err)
}
got := convertReleaserToV1(t, goti)
// check release has actually been updated by comparing modified fields
if rel.Info.Status != got.Info.Status {
t.Errorf("Expected status %s, got status %s", rel.Info.Status.String(), got.Info.Status.String())
}
}
func TestConfigMapDelete(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
cfgmaps := newTestFixtureCfgMaps(t, []*rspb.Release{rel}...)
// perform the delete on a non-existent release
_, err := cfgmaps.Delete("nonexistent")
if err != ErrReleaseNotFound {
t.Fatalf("Expected ErrReleaseNotFound: got {%v}", err)
}
// perform the delete
rls, err := cfgmaps.Delete(key)
if err != nil {
t.Fatalf("Failed to delete release with key %q: %s", key, err)
}
if !reflect.DeepEqual(rel, rls) {
t.Errorf("Expected {%v}, got {%v}", rel, rls)
}
_, err = cfgmaps.Get(key)
if !errors.Is(err, ErrReleaseNotFound) {
t.Errorf("Expected {%v}, got {%v}", ErrReleaseNotFound, err)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/driver.go | pkg/storage/driver/driver.go | /*
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 driver // import "helm.sh/helm/v4/pkg/storage/driver"
import (
"errors"
"fmt"
"helm.sh/helm/v4/pkg/release"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
var (
// ErrReleaseNotFound indicates that a release is not found.
ErrReleaseNotFound = errors.New("release: not found")
// ErrReleaseExists indicates that a release already exists.
ErrReleaseExists = errors.New("release: already exists")
// ErrInvalidKey indicates that a release key could not be parsed.
ErrInvalidKey = errors.New("release: invalid key")
// ErrNoDeployedReleases indicates that there are no releases with the given key in the deployed state
ErrNoDeployedReleases = errors.New("has no deployed releases")
)
// StorageDriverError records an error and the release name that caused it
type StorageDriverError struct {
ReleaseName string
Err error
}
func (e *StorageDriverError) Error() string {
return fmt.Sprintf("%q %s", e.ReleaseName, e.Err.Error())
}
func (e *StorageDriverError) Unwrap() error { return e.Err }
func NewErrNoDeployedReleases(releaseName string) error {
return &StorageDriverError{
ReleaseName: releaseName,
Err: ErrNoDeployedReleases,
}
}
// Creator is the interface that wraps the Create method.
//
// Create stores the release or returns ErrReleaseExists
// if an identical release already exists.
type Creator interface {
Create(key string, rls release.Releaser) error
}
// Updator is the interface that wraps the Update method.
//
// Update updates an existing release or returns
// ErrReleaseNotFound if the release does not exist.
type Updator interface {
Update(key string, rls release.Releaser) error
}
// Deletor is the interface that wraps the Delete method.
//
// Delete deletes the release named by key or returns
// ErrReleaseNotFound if the release does not exist.
type Deletor interface {
Delete(key string) (release.Releaser, error)
}
// Queryor is the interface that wraps the Get and List methods.
//
// Get returns the release named by key or returns ErrReleaseNotFound
// if the release does not exist.
//
// List returns the set of all releases that satisfy the filter predicate.
//
// Query returns the set of all releases that match the provided label set.
type Queryor interface {
Get(key string) (release.Releaser, error)
List(filter func(release.Releaser) bool) ([]release.Releaser, error)
Query(labels map[string]string) ([]release.Releaser, error)
}
// Driver is the interface composed of Creator, Updator, Deletor, and Queryor
// interfaces. It defines the behavior for storing, updating, deleted,
// and retrieving Helm releases from some underlying storage mechanism,
// e.g. memory, configmaps.
type Driver interface {
Creator
Updator
Deletor
Queryor
Name() string
}
// releaserToV1Release is a helper function to convert a v1 release passed by interface
// into the type object.
func releaserToV1Release(rel release.Releaser) (*rspb.Release, error) {
switch r := rel.(type) {
case rspb.Release:
return &r, nil
case *rspb.Release:
return r, nil
case nil:
return nil, nil
default:
return nil, fmt.Errorf("unsupported release type: %T", rel)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/memory.go | pkg/storage/driver/memory.go | /*
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 driver
import (
"log/slog"
"strconv"
"strings"
"sync"
"helm.sh/helm/v4/internal/logging"
"helm.sh/helm/v4/pkg/release"
)
var _ Driver = (*Memory)(nil)
const (
// MemoryDriverName is the string name of this driver.
MemoryDriverName = "Memory"
defaultNamespace = "default"
)
// A map of release names to list of release records
type memReleases map[string]records
// Memory is the in-memory storage driver implementation.
type Memory struct {
sync.RWMutex
namespace string
// A map of namespaces to releases
cache map[string]memReleases
// Embed a LogHolder to provide logger functionality
logging.LogHolder
}
// NewMemory initializes a new memory driver.
func NewMemory() *Memory {
m := &Memory{cache: map[string]memReleases{}, namespace: "default"}
m.SetLogger(slog.Default().Handler())
return m
}
// SetNamespace sets a specific namespace in which releases will be accessed.
// An empty string indicates all namespaces (for the list operation)
func (mem *Memory) SetNamespace(ns string) {
mem.namespace = ns
}
// Name returns the name of the driver.
func (mem *Memory) Name() string {
return MemoryDriverName
}
// Get returns the release named by key or returns ErrReleaseNotFound.
func (mem *Memory) Get(key string) (release.Releaser, error) {
defer unlock(mem.rlock())
keyWithoutPrefix := strings.TrimPrefix(key, "sh.helm.release.v1.")
switch elems := strings.Split(keyWithoutPrefix, ".v"); len(elems) {
case 2:
name, ver := elems[0], elems[1]
if _, err := strconv.Atoi(ver); err != nil {
return nil, ErrInvalidKey
}
if recs, ok := mem.cache[mem.namespace][name]; ok {
if r := recs.Get(key); r != nil {
return r.rls, nil
}
}
return nil, ErrReleaseNotFound
default:
return nil, ErrInvalidKey
}
}
// List returns the list of all releases such that filter(release) == true
func (mem *Memory) List(filter func(release.Releaser) bool) ([]release.Releaser, error) {
defer unlock(mem.rlock())
var ls []release.Releaser
for namespace := range mem.cache {
if mem.namespace != "" {
// Should only list releases of this namespace
namespace = mem.namespace
}
for _, recs := range mem.cache[namespace] {
recs.Iter(func(_ int, rec *record) bool {
if filter(rec.rls) {
ls = append(ls, rec.rls)
}
return true
})
}
if mem.namespace != "" {
// Should only list releases of this namespace
break
}
}
return ls, nil
}
// Query returns the set of releases that match the provided set of labels
func (mem *Memory) Query(keyvals map[string]string) ([]release.Releaser, error) {
defer unlock(mem.rlock())
var lbs labels
lbs.init()
lbs.fromMap(keyvals)
var ls []release.Releaser
for namespace := range mem.cache {
if mem.namespace != "" {
// Should only query releases of this namespace
namespace = mem.namespace
}
for _, recs := range mem.cache[namespace] {
recs.Iter(func(_ int, rec *record) bool {
// A query for a release name that doesn't exist (has been deleted)
// can cause rec to be nil.
if rec == nil {
return false
}
if rec.lbs.match(lbs) {
ls = append(ls, rec.rls)
}
return true
})
}
if mem.namespace != "" {
// Should only query releases of this namespace
break
}
}
if len(ls) == 0 {
return nil, ErrReleaseNotFound
}
return ls, nil
}
// Create creates a new release or returns ErrReleaseExists.
func (mem *Memory) Create(key string, rel release.Releaser) error {
defer unlock(mem.wlock())
rls, err := releaserToV1Release(rel)
if err != nil {
return err
}
// For backwards compatibility, we protect against an unset namespace
namespace := rls.Namespace
if namespace == "" {
namespace = defaultNamespace
}
mem.SetNamespace(namespace)
if _, ok := mem.cache[namespace]; !ok {
mem.cache[namespace] = memReleases{}
}
if recs, ok := mem.cache[namespace][rls.Name]; ok {
if err := recs.Add(newRecord(key, rls)); err != nil {
return err
}
mem.cache[namespace][rls.Name] = recs
return nil
}
mem.cache[namespace][rls.Name] = records{newRecord(key, rls)}
return nil
}
// Update updates a release or returns ErrReleaseNotFound.
func (mem *Memory) Update(key string, rel release.Releaser) error {
defer unlock(mem.wlock())
rls, err := releaserToV1Release(rel)
if err != nil {
return err
}
// For backwards compatibility, we protect against an unset namespace
namespace := rls.Namespace
if namespace == "" {
namespace = defaultNamespace
}
mem.SetNamespace(namespace)
if _, ok := mem.cache[namespace]; ok {
if rs, ok := mem.cache[namespace][rls.Name]; ok && rs.Exists(key) {
rs.Replace(key, newRecord(key, rls))
return nil
}
}
return ErrReleaseNotFound
}
// Delete deletes a release or returns ErrReleaseNotFound.
func (mem *Memory) Delete(key string) (release.Releaser, error) {
defer unlock(mem.wlock())
keyWithoutPrefix := strings.TrimPrefix(key, "sh.helm.release.v1.")
elems := strings.Split(keyWithoutPrefix, ".v")
if len(elems) != 2 {
return nil, ErrInvalidKey
}
name, ver := elems[0], elems[1]
if _, err := strconv.Atoi(ver); err != nil {
return nil, ErrInvalidKey
}
if _, ok := mem.cache[mem.namespace]; ok {
if recs, ok := mem.cache[mem.namespace][name]; ok {
if r := recs.Remove(key); r != nil {
// recs.Remove changes the slice reference, so we have to re-assign it.
mem.cache[mem.namespace][name] = recs
return r.rls, nil
}
}
}
return nil, ErrReleaseNotFound
}
// wlock locks mem for writing
func (mem *Memory) wlock() func() {
mem.Lock()
return func() { mem.Unlock() }
}
// rlock locks mem for reading
func (mem *Memory) rlock() func() {
mem.RLock()
return func() { mem.RUnlock() }
}
// unlock calls fn which reverses a mem.rlock or mem.wlock. e.g:
// ```defer unlock(mem.rlock())```, locks mem for reading at the
// call point of defer and unlocks upon exiting the block.
func unlock(fn func()) { fn() }
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/mock_test.go | pkg/storage/driver/mock_test.go | /*
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 driver // import "helm.sh/helm/v4/pkg/storage/driver"
import (
"context"
"fmt"
"testing"
sqlmock "github.com/DATA-DOG/go-sqlmock"
sq "github.com/Masterminds/squirrel"
"github.com/jmoiron/sqlx"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kblabels "k8s.io/apimachinery/pkg/labels"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
func releaseStub(name string, vers int, namespace string, status common.Status) *rspb.Release {
return &rspb.Release{
Name: name,
Version: vers,
Namespace: namespace,
Info: &rspb.Info{Status: status},
Labels: map[string]string{
"key1": "val1",
"key2": "val2",
},
}
}
func testKey(name string, vers int) string {
return fmt.Sprintf("%s.v%d", name, vers)
}
func tsFixtureMemory(t *testing.T) *Memory {
t.Helper()
hs := []*rspb.Release{
// rls-a
releaseStub("rls-a", 4, "default", common.StatusDeployed),
releaseStub("rls-a", 1, "default", common.StatusSuperseded),
releaseStub("rls-a", 3, "default", common.StatusSuperseded),
releaseStub("rls-a", 2, "default", common.StatusSuperseded),
// rls-b
releaseStub("rls-b", 4, "default", common.StatusDeployed),
releaseStub("rls-b", 1, "default", common.StatusSuperseded),
releaseStub("rls-b", 3, "default", common.StatusSuperseded),
releaseStub("rls-b", 2, "default", common.StatusSuperseded),
// rls-c in other namespace
releaseStub("rls-c", 4, "mynamespace", common.StatusDeployed),
releaseStub("rls-c", 1, "mynamespace", common.StatusSuperseded),
releaseStub("rls-c", 3, "mynamespace", common.StatusSuperseded),
releaseStub("rls-c", 2, "mynamespace", common.StatusSuperseded),
}
mem := NewMemory()
for _, tt := range hs {
err := mem.Create(testKey(tt.Name, tt.Version), tt)
if err != nil {
t.Fatalf("Test setup failed to create: %s\n", err)
}
}
return mem
}
// newTestFixtureCfgMaps initializes a MockConfigMapsInterface.
// ConfigMaps are created for each release provided.
func newTestFixtureCfgMaps(t *testing.T, releases ...*rspb.Release) *ConfigMaps {
t.Helper()
var mock MockConfigMapsInterface
mock.Init(t, releases...)
return NewConfigMaps(&mock)
}
// MockConfigMapsInterface mocks a kubernetes ConfigMapsInterface
type MockConfigMapsInterface struct {
corev1.ConfigMapInterface
objects map[string]*v1.ConfigMap
}
// Init initializes the MockConfigMapsInterface with the set of releases.
func (mock *MockConfigMapsInterface) Init(t *testing.T, releases ...*rspb.Release) {
t.Helper()
mock.objects = map[string]*v1.ConfigMap{}
for _, rls := range releases {
objkey := testKey(rls.Name, rls.Version)
cfgmap, err := newConfigMapsObject(objkey, rls, nil)
if err != nil {
t.Fatalf("Failed to create configmap: %s", err)
}
mock.objects[objkey] = cfgmap
}
}
// Get returns the ConfigMap by name.
func (mock *MockConfigMapsInterface) Get(_ context.Context, name string, _ metav1.GetOptions) (*v1.ConfigMap, error) {
object, ok := mock.objects[name]
if !ok {
return nil, apierrors.NewNotFound(v1.Resource("tests"), name)
}
return object, nil
}
// List returns all ConfigMaps.
func (mock *MockConfigMapsInterface) List(_ context.Context, opts metav1.ListOptions) (*v1.ConfigMapList, error) {
var list v1.ConfigMapList
labelSelector, err := kblabels.Parse(opts.LabelSelector)
if err != nil {
return nil, err
}
for _, cfgmap := range mock.objects {
if labelSelector.Matches(kblabels.Set(cfgmap.Labels)) {
list.Items = append(list.Items, *cfgmap)
}
}
return &list, nil
}
// Create creates a new ConfigMap.
func (mock *MockConfigMapsInterface) Create(_ context.Context, cfgmap *v1.ConfigMap, _ metav1.CreateOptions) (*v1.ConfigMap, error) {
name := cfgmap.Name
if object, ok := mock.objects[name]; ok {
return object, apierrors.NewAlreadyExists(v1.Resource("tests"), name)
}
mock.objects[name] = cfgmap
return cfgmap, nil
}
// Update updates a ConfigMap.
func (mock *MockConfigMapsInterface) Update(_ context.Context, cfgmap *v1.ConfigMap, _ metav1.UpdateOptions) (*v1.ConfigMap, error) {
name := cfgmap.Name
if _, ok := mock.objects[name]; !ok {
return nil, apierrors.NewNotFound(v1.Resource("tests"), name)
}
mock.objects[name] = cfgmap
return cfgmap, nil
}
// Delete deletes a ConfigMap by name.
func (mock *MockConfigMapsInterface) Delete(_ context.Context, name string, _ metav1.DeleteOptions) error {
if _, ok := mock.objects[name]; !ok {
return apierrors.NewNotFound(v1.Resource("tests"), name)
}
delete(mock.objects, name)
return nil
}
// newTestFixtureSecrets initializes a MockSecretsInterface.
// Secrets are created for each release provided.
func newTestFixtureSecrets(t *testing.T, releases ...*rspb.Release) *Secrets {
t.Helper()
var mock MockSecretsInterface
mock.Init(t, releases...)
return NewSecrets(&mock)
}
// MockSecretsInterface mocks a kubernetes SecretsInterface
type MockSecretsInterface struct {
corev1.SecretInterface
objects map[string]*v1.Secret
}
// Init initializes the MockSecretsInterface with the set of releases.
func (mock *MockSecretsInterface) Init(t *testing.T, releases ...*rspb.Release) {
t.Helper()
mock.objects = map[string]*v1.Secret{}
for _, rls := range releases {
objkey := testKey(rls.Name, rls.Version)
secret, err := newSecretsObject(objkey, rls, nil)
if err != nil {
t.Fatalf("Failed to create secret: %s", err)
}
mock.objects[objkey] = secret
}
}
// Get returns the Secret by name.
func (mock *MockSecretsInterface) Get(_ context.Context, name string, _ metav1.GetOptions) (*v1.Secret, error) {
object, ok := mock.objects[name]
if !ok {
return nil, apierrors.NewNotFound(v1.Resource("tests"), name)
}
return object, nil
}
// List returns all Secrets.
func (mock *MockSecretsInterface) List(_ context.Context, opts metav1.ListOptions) (*v1.SecretList, error) {
var list v1.SecretList
labelSelector, err := kblabels.Parse(opts.LabelSelector)
if err != nil {
return nil, err
}
for _, secret := range mock.objects {
if labelSelector.Matches(kblabels.Set(secret.Labels)) {
list.Items = append(list.Items, *secret)
}
}
return &list, nil
}
// Create creates a new Secret.
func (mock *MockSecretsInterface) Create(_ context.Context, secret *v1.Secret, _ metav1.CreateOptions) (*v1.Secret, error) {
name := secret.Name
if object, ok := mock.objects[name]; ok {
return object, apierrors.NewAlreadyExists(v1.Resource("tests"), name)
}
mock.objects[name] = secret
return secret, nil
}
// Update updates a Secret.
func (mock *MockSecretsInterface) Update(_ context.Context, secret *v1.Secret, _ metav1.UpdateOptions) (*v1.Secret, error) {
name := secret.Name
if _, ok := mock.objects[name]; !ok {
return nil, apierrors.NewNotFound(v1.Resource("tests"), name)
}
mock.objects[name] = secret
return secret, nil
}
// Delete deletes a Secret by name.
func (mock *MockSecretsInterface) Delete(_ context.Context, name string, _ metav1.DeleteOptions) error {
if _, ok := mock.objects[name]; !ok {
return apierrors.NewNotFound(v1.Resource("tests"), name)
}
delete(mock.objects, name)
return nil
}
// newTestFixtureSQL mocks the SQL database (for testing purposes)
func newTestFixtureSQL(t *testing.T, _ ...*rspb.Release) (*SQL, sqlmock.Sqlmock) {
t.Helper()
sqlDB, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("error when opening stub database connection: %v", err)
}
sqlxDB := sqlx.NewDb(sqlDB, "sqlmock")
return &SQL{
db: sqlxDB,
namespace: "default",
statementBuilder: sq.StatementBuilder.PlaceholderFormat(sq.Dollar),
}, mock
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/util.go | pkg/storage/driver/util.go | /*
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 driver // import "helm.sh/helm/v4/pkg/storage/driver"
import (
"bytes"
"compress/gzip"
"encoding/base64"
"encoding/json"
"io"
"slices"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
var b64 = base64.StdEncoding
var magicGzip = []byte{0x1f, 0x8b, 0x08}
var systemLabels = []string{"name", "owner", "status", "version", "createdAt", "modifiedAt"}
// encodeRelease encodes a release returning a base64 encoded
// gzipped string representation, or error.
func encodeRelease(rls *rspb.Release) (string, error) {
b, err := json.Marshal(rls)
if err != nil {
return "", err
}
var buf bytes.Buffer
w, err := gzip.NewWriterLevel(&buf, gzip.BestCompression)
if err != nil {
return "", err
}
if _, err = w.Write(b); err != nil {
return "", err
}
w.Close()
return b64.EncodeToString(buf.Bytes()), nil
}
// decodeRelease decodes the bytes of data into a release
// type. Data must contain a base64 encoded gzipped string of a
// valid release, otherwise an error is returned.
func decodeRelease(data string) (*rspb.Release, error) {
// base64 decode string
b, err := b64.DecodeString(data)
if err != nil {
return nil, err
}
// For backwards compatibility with releases that were stored before
// compression was introduced we skip decompression if the
// gzip magic header is not found
if len(b) > 3 && bytes.Equal(b[0:3], magicGzip) {
r, err := gzip.NewReader(bytes.NewReader(b))
if err != nil {
return nil, err
}
defer r.Close()
b2, err := io.ReadAll(r)
if err != nil {
return nil, err
}
b = b2
}
var rls rspb.Release
// unmarshal release object bytes
if err := json.Unmarshal(b, &rls); err != nil {
return nil, err
}
return &rls, nil
}
// Checks if label is system
func isSystemLabel(key string) bool {
return slices.Contains(GetSystemLabels(), key)
}
// Removes system labels from labels map
func filterSystemLabels(lbs map[string]string) map[string]string {
result := make(map[string]string)
for k, v := range lbs {
if !isSystemLabel(k) {
result[k] = v
}
}
return result
}
// Checks if labels array contains system labels
func ContainsSystemLabels(lbs map[string]string) bool {
for k := range lbs {
if isSystemLabel(k) {
return true
}
}
return false
}
func GetSystemLabels() []string {
return systemLabels
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/cfgmaps.go | pkg/storage/driver/cfgmaps.go | /*
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 driver // import "helm.sh/helm/v4/pkg/storage/driver"
import (
"context"
"fmt"
"log/slog"
"strconv"
"strings"
"time"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kblabels "k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/validation"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"helm.sh/helm/v4/internal/logging"
"helm.sh/helm/v4/pkg/release"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
var _ Driver = (*ConfigMaps)(nil)
// ConfigMapsDriverName is the string name of the driver.
const ConfigMapsDriverName = "ConfigMap"
// ConfigMaps is a wrapper around an implementation of a kubernetes
// ConfigMapsInterface.
type ConfigMaps struct {
impl corev1.ConfigMapInterface
// Embed a LogHolder to provide logger functionality
logging.LogHolder
}
// NewConfigMaps initializes a new ConfigMaps wrapping an implementation of
// the kubernetes ConfigMapsInterface.
func NewConfigMaps(impl corev1.ConfigMapInterface) *ConfigMaps {
c := &ConfigMaps{
impl: impl,
}
c.SetLogger(slog.Default().Handler())
return c
}
// Name returns the name of the driver.
func (cfgmaps *ConfigMaps) Name() string {
return ConfigMapsDriverName
}
// Get fetches the release named by key. The corresponding release is returned
// or error if not found.
func (cfgmaps *ConfigMaps) Get(key string) (release.Releaser, error) {
// fetch the configmap holding the release named by key
obj, err := cfgmaps.impl.Get(context.Background(), key, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
return nil, ErrReleaseNotFound
}
cfgmaps.Logger().Debug("failed to get release", slog.String("key", key), slog.Any("error", err))
return nil, err
}
// found the configmap, decode the base64 data string
r, err := decodeRelease(obj.Data["release"])
if err != nil {
cfgmaps.Logger().Debug("failed to decode data", slog.String("key", key), slog.Any("error", err))
return nil, err
}
r.Labels = filterSystemLabels(obj.Labels)
// return the release object
return r, nil
}
// List fetches all releases and returns the list releases such
// that filter(release) == true. An error is returned if the
// configmap fails to retrieve the releases.
func (cfgmaps *ConfigMaps) List(filter func(release.Releaser) bool) ([]release.Releaser, error) {
lsel := kblabels.Set{"owner": "helm"}.AsSelector()
opts := metav1.ListOptions{LabelSelector: lsel.String()}
list, err := cfgmaps.impl.List(context.Background(), opts)
if err != nil {
cfgmaps.Logger().Debug("failed to list releases", slog.Any("error", err))
return nil, err
}
var results []release.Releaser
// iterate over the configmaps object list
// and decode each release
for _, item := range list.Items {
rls, err := decodeRelease(item.Data["release"])
if err != nil {
cfgmaps.Logger().Debug("failed to decode release", slog.Any("item", item), slog.Any("error", err))
continue
}
rls.Labels = item.Labels
if filter(rls) {
results = append(results, rls)
}
}
return results, nil
}
// Query fetches all releases that match the provided map of labels.
// An error is returned if the configmap fails to retrieve the releases.
func (cfgmaps *ConfigMaps) Query(labels map[string]string) ([]release.Releaser, error) {
ls := kblabels.Set{}
for k, v := range labels {
if errs := validation.IsValidLabelValue(v); len(errs) != 0 {
return nil, fmt.Errorf("invalid label value: %q: %s", v, strings.Join(errs, "; "))
}
ls[k] = v
}
opts := metav1.ListOptions{LabelSelector: ls.AsSelector().String()}
list, err := cfgmaps.impl.List(context.Background(), opts)
if err != nil {
cfgmaps.Logger().Debug("failed to query with labels", slog.Any("error", err))
return nil, err
}
if len(list.Items) == 0 {
return nil, ErrReleaseNotFound
}
var results []release.Releaser
for _, item := range list.Items {
rls, err := decodeRelease(item.Data["release"])
if err != nil {
cfgmaps.Logger().Debug("failed to decode release", slog.Any("error", err))
continue
}
rls.Labels = item.Labels
results = append(results, rls)
}
return results, nil
}
// Create creates a new ConfigMap holding the release. If the
// ConfigMap already exists, ErrReleaseExists is returned.
func (cfgmaps *ConfigMaps) Create(key string, rls release.Releaser) error {
// set labels for configmaps object meta data
var lbs labels
rac, err := release.NewAccessor(rls)
if err != nil {
return err
}
lbs.init()
lbs.fromMap(rac.Labels())
lbs.set("createdAt", fmt.Sprintf("%v", time.Now().Unix()))
rel, err := releaserToV1Release(rls)
if err != nil {
return err
}
// create a new configmap to hold the release
obj, err := newConfigMapsObject(key, rel, lbs)
if err != nil {
cfgmaps.Logger().Debug("failed to encode release", slog.String("name", rac.Name()), slog.Any("error", err))
return err
}
// push the configmap object out into the kubiverse
if _, err := cfgmaps.impl.Create(context.Background(), obj, metav1.CreateOptions{}); err != nil {
if apierrors.IsAlreadyExists(err) {
return ErrReleaseExists
}
cfgmaps.Logger().Debug("failed to create release", slog.Any("error", err))
return err
}
return nil
}
// Update updates the ConfigMap holding the release. If not found
// the ConfigMap is created to hold the release.
func (cfgmaps *ConfigMaps) Update(key string, rel release.Releaser) error {
// set labels for configmaps object meta data
var lbs labels
rls, err := releaserToV1Release(rel)
if err != nil {
return err
}
lbs.init()
lbs.fromMap(rls.Labels)
lbs.set("modifiedAt", fmt.Sprintf("%v", time.Now().Unix()))
// create a new configmap object to hold the release
obj, err := newConfigMapsObject(key, rls, lbs)
if err != nil {
cfgmaps.Logger().Debug(
"failed to encode release",
slog.String("name", rls.Name),
slog.Any("error", err),
)
return err
}
// push the configmap object out into the kubiverse
_, err = cfgmaps.impl.Update(context.Background(), obj, metav1.UpdateOptions{})
if err != nil {
cfgmaps.Logger().Debug("failed to update release", slog.Any("error", err))
return err
}
return nil
}
// Delete deletes the ConfigMap holding the release named by key.
func (cfgmaps *ConfigMaps) Delete(key string) (rls release.Releaser, err error) {
// fetch the release to check existence
if rls, err = cfgmaps.Get(key); err != nil {
return nil, err
}
// delete the release
if err = cfgmaps.impl.Delete(context.Background(), key, metav1.DeleteOptions{}); err != nil {
return rls, err
}
return rls, nil
}
// newConfigMapsObject constructs a kubernetes ConfigMap object
// to store a release. Each configmap data entry is the base64
// encoded gzipped string of a release.
//
// The following labels are used within each configmap:
//
// "modifiedAt" - timestamp indicating when this configmap was last modified. (set in Update)
// "createdAt" - timestamp indicating when this configmap was created. (set in Create)
// "version" - version of the release.
// "status" - status of the release (see pkg/release/status.go for variants)
// "owner" - owner of the configmap, currently "helm".
// "name" - name of the release.
func newConfigMapsObject(key string, rls *rspb.Release, lbs labels) (*v1.ConfigMap, error) {
const owner = "helm"
// encode the release
s, err := encodeRelease(rls)
if err != nil {
return nil, err
}
if lbs == nil {
lbs.init()
}
// apply custom labels
lbs.fromMap(rls.Labels)
// apply labels
lbs.set("name", rls.Name)
lbs.set("owner", owner)
lbs.set("status", rls.Info.Status.String())
lbs.set("version", strconv.Itoa(rls.Version))
// create and return configmap object
return &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: key,
Labels: lbs.toMap(),
},
Data: map[string]string{"release": s},
}, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/records.go | pkg/storage/driver/records.go | /*
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 driver // import "helm.sh/helm/v4/pkg/storage/driver"
import (
"sort"
"strconv"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
// records holds a list of in-memory release records
type records []*record
func (rs records) Len() int { return len(rs) }
func (rs records) Swap(i, j int) { rs[i], rs[j] = rs[j], rs[i] }
func (rs records) Less(i, j int) bool { return rs[i].rls.Version < rs[j].rls.Version }
func (rs *records) Add(r *record) error {
if r == nil {
return nil
}
if rs.Exists(r.key) {
return ErrReleaseExists
}
*rs = append(*rs, r)
sort.Sort(*rs)
return nil
}
func (rs records) Get(key string) *record {
if i, ok := rs.Index(key); ok {
return rs[i]
}
return nil
}
func (rs *records) Iter(fn func(int, *record) bool) {
cp := make([]*record, len(*rs))
copy(cp, *rs)
for i, r := range cp {
if !fn(i, r) {
return
}
}
}
func (rs *records) Index(key string) (int, bool) {
for i, r := range *rs {
if r.key == key {
return i, true
}
}
return -1, false
}
func (rs records) Exists(key string) bool {
_, ok := rs.Index(key)
return ok
}
func (rs *records) Remove(key string) (r *record) {
if i, ok := rs.Index(key); ok {
return rs.removeAt(i)
}
return nil
}
func (rs *records) Replace(key string, rec *record) *record {
if i, ok := rs.Index(key); ok {
old := (*rs)[i]
(*rs)[i] = rec
return old
}
return nil
}
func (rs *records) removeAt(index int) *record {
r := (*rs)[index]
(*rs)[index] = nil
copy((*rs)[index:], (*rs)[index+1:])
*rs = (*rs)[:len(*rs)-1]
return r
}
// record is the data structure used to cache releases
// for the in-memory storage driver
type record struct {
key string
lbs labels
rls *rspb.Release
}
// newRecord creates a new in-memory release record
func newRecord(key string, rls *rspb.Release) *record {
var lbs labels
lbs.init()
lbs.set("name", rls.Name)
lbs.set("owner", "helm")
lbs.set("status", rls.Info.Status.String())
lbs.set("version", strconv.Itoa(rls.Version))
// return &record{key: key, lbs: lbs, rls: proto.Clone(rls).(*rspb.Release)}
return &record{key: key, lbs: lbs, rls: rls}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/labels.go | pkg/storage/driver/labels.go | /*
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 driver
// labels is a map of key value pairs to be included as metadata in a configmap object.
type labels map[string]string
func (lbs *labels) init() { *lbs = labels(make(map[string]string)) }
func (lbs labels) get(key string) string { return lbs[key] }
func (lbs labels) set(key, val string) { lbs[key] = val }
func (lbs labels) keys() (ls []string) {
for key := range lbs {
ls = append(ls, key)
}
return
}
func (lbs labels) match(set labels) bool {
for _, key := range set.keys() {
if lbs.get(key) != set.get(key) {
return false
}
}
return true
}
func (lbs labels) toMap() map[string]string { return lbs }
func (lbs *labels) fromMap(kvs map[string]string) {
for k, v := range kvs {
lbs.set(k, v)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/secrets.go | pkg/storage/driver/secrets.go | /*
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 driver // import "helm.sh/helm/v4/pkg/storage/driver"
import (
"context"
"fmt"
"log/slog"
"strconv"
"strings"
"time"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kblabels "k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/validation"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"helm.sh/helm/v4/internal/logging"
"helm.sh/helm/v4/pkg/release"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
var _ Driver = (*Secrets)(nil)
// SecretsDriverName is the string name of the driver.
const SecretsDriverName = "Secret"
// Secrets is a wrapper around an implementation of a kubernetes
// SecretsInterface.
type Secrets struct {
impl corev1.SecretInterface
// Embed a LogHolder to provide logger functionality
logging.LogHolder
}
// NewSecrets initializes a new Secrets wrapping an implementation of
// the kubernetes SecretsInterface.
func NewSecrets(impl corev1.SecretInterface) *Secrets {
s := &Secrets{
impl: impl,
}
s.SetLogger(slog.Default().Handler())
return s
}
// Name returns the name of the driver.
func (secrets *Secrets) Name() string {
return SecretsDriverName
}
// Get fetches the release named by key. The corresponding release is returned
// or error if not found.
func (secrets *Secrets) Get(key string) (release.Releaser, error) {
// fetch the secret holding the release named by key
obj, err := secrets.impl.Get(context.Background(), key, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
return nil, ErrReleaseNotFound
}
return nil, fmt.Errorf("get: failed to get %q: %w", key, err)
}
// found the secret, decode the base64 data string
r, err := decodeRelease(string(obj.Data["release"]))
if err != nil {
return r, fmt.Errorf("get: failed to decode data %q: %w", key, err)
}
r.Labels = filterSystemLabels(obj.Labels)
return r, nil
}
// List fetches all releases and returns the list releases such
// that filter(release) == true. An error is returned if the
// secret fails to retrieve the releases.
func (secrets *Secrets) List(filter func(release.Releaser) bool) ([]release.Releaser, error) {
lsel := kblabels.Set{"owner": "helm"}.AsSelector()
opts := metav1.ListOptions{LabelSelector: lsel.String()}
list, err := secrets.impl.List(context.Background(), opts)
if err != nil {
return nil, fmt.Errorf("list: failed to list: %w", err)
}
var results []release.Releaser
// iterate over the secrets object list
// and decode each release
for _, item := range list.Items {
rls, err := decodeRelease(string(item.Data["release"]))
if err != nil {
secrets.Logger().Debug(
"list failed to decode release", slog.String("key", item.Name),
slog.Any("error", err),
)
continue
}
rls.Labels = item.Labels
if filter(rls) {
results = append(results, rls)
}
}
return results, nil
}
// Query fetches all releases that match the provided map of labels.
// An error is returned if the secret fails to retrieve the releases.
func (secrets *Secrets) Query(labels map[string]string) ([]release.Releaser, error) {
ls := kblabels.Set{}
for k, v := range labels {
if errs := validation.IsValidLabelValue(v); len(errs) != 0 {
return nil, fmt.Errorf("invalid label value: %q: %s", v, strings.Join(errs, "; "))
}
ls[k] = v
}
opts := metav1.ListOptions{LabelSelector: ls.AsSelector().String()}
list, err := secrets.impl.List(context.Background(), opts)
if err != nil {
return nil, fmt.Errorf("query: failed to query with labels: %w", err)
}
if len(list.Items) == 0 {
return nil, ErrReleaseNotFound
}
var results []release.Releaser
for _, item := range list.Items {
rls, err := decodeRelease(string(item.Data["release"]))
if err != nil {
secrets.Logger().Debug(
"failed to decode release",
slog.String("key", item.Name),
slog.Any("error", err),
)
continue
}
rls.Labels = item.Labels
results = append(results, rls)
}
return results, nil
}
// Create creates a new Secret holding the release. If the
// Secret already exists, ErrReleaseExists is returned.
func (secrets *Secrets) Create(key string, rel release.Releaser) error {
// set labels for secrets object meta data
var lbs labels
rls, err := releaserToV1Release(rel)
if err != nil {
return err
}
lbs.init()
lbs.fromMap(rls.Labels)
lbs.set("createdAt", fmt.Sprintf("%v", time.Now().Unix()))
// create a new secret to hold the release
obj, err := newSecretsObject(key, rls, lbs)
if err != nil {
return fmt.Errorf("create: failed to encode release %q: %w", rls.Name, err)
}
// push the secret object out into the kubiverse
if _, err := secrets.impl.Create(context.Background(), obj, metav1.CreateOptions{}); err != nil {
if apierrors.IsAlreadyExists(err) {
return ErrReleaseExists
}
return fmt.Errorf("create: failed to create: %w", err)
}
return nil
}
// Update updates the Secret holding the release. If not found
// the Secret is created to hold the release.
func (secrets *Secrets) Update(key string, rel release.Releaser) error {
// set labels for secrets object meta data
var lbs labels
rls, err := releaserToV1Release(rel)
if err != nil {
return err
}
lbs.init()
lbs.fromMap(rls.Labels)
lbs.set("modifiedAt", fmt.Sprintf("%v", time.Now().Unix()))
// create a new secret object to hold the release
obj, err := newSecretsObject(key, rls, lbs)
if err != nil {
return fmt.Errorf("update: failed to encode release %q: %w", rls.Name, err)
}
// push the secret object out into the kubiverse
_, err = secrets.impl.Update(context.Background(), obj, metav1.UpdateOptions{})
if err != nil {
return fmt.Errorf("update: failed to update: %w", err)
}
return nil
}
// Delete deletes the Secret holding the release named by key.
func (secrets *Secrets) Delete(key string) (rls release.Releaser, err error) {
// fetch the release to check existence
if rls, err = secrets.Get(key); err != nil {
return nil, err
}
// delete the release
err = secrets.impl.Delete(context.Background(), key, metav1.DeleteOptions{})
if err != nil {
return nil, err
}
return rls, nil
}
// newSecretsObject constructs a kubernetes Secret object
// to store a release. Each secret data entry is the base64
// encoded gzipped string of a release.
//
// The following labels are used within each secret:
//
// "modifiedAt" - timestamp indicating when this secret was last modified. (set in Update)
// "createdAt" - timestamp indicating when this secret was created. (set in Create)
// "version" - version of the release.
// "status" - status of the release (see pkg/release/status.go for variants)
// "owner" - owner of the secret, currently "helm".
// "name" - name of the release.
func newSecretsObject(key string, rls *rspb.Release, lbs labels) (*v1.Secret, error) {
const owner = "helm"
// encode the release
s, err := encodeRelease(rls)
if err != nil {
return nil, err
}
if lbs == nil {
lbs.init()
}
// apply custom labels
lbs.fromMap(rls.Labels)
// apply labels
lbs.set("name", rls.Name)
lbs.set("owner", owner)
lbs.set("status", rls.Info.Status.String())
lbs.set("version", strconv.Itoa(rls.Version))
// create and return secret object.
// Helm 3 introduced setting the 'Type' field
// in the Kubernetes storage object.
// Helm defines the field content as follows:
// <helm_domain>/<helm_object>.v<helm_object_version>
// Type field for Helm 3: helm.sh/release.v1
// Note: Version starts at 'v1' for Helm 3 and
// should be incremented if the release object
// metadata is modified.
// This would potentially be a breaking change
// and should only happen between major versions.
return &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: key,
Labels: lbs.toMap(),
},
Type: "helm.sh/release.v1",
Data: map[string][]byte{"release": []byte(s)},
}, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/labels_test.go | pkg/storage/driver/labels_test.go | /*
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 driver // import "helm.sh/helm/v4/pkg/storage/driver"
import (
"testing"
)
func TestLabelsMatch(t *testing.T) {
var tests = []struct {
desc string
set1 labels
set2 labels
expect bool
}{
{
"equal labels sets",
labels(map[string]string{"KEY_A": "VAL_A", "KEY_B": "VAL_B"}),
labels(map[string]string{"KEY_A": "VAL_A", "KEY_B": "VAL_B"}),
true,
},
{
"disjoint label sets",
labels(map[string]string{"KEY_C": "VAL_C", "KEY_D": "VAL_D"}),
labels(map[string]string{"KEY_A": "VAL_A", "KEY_B": "VAL_B"}),
false,
},
}
for _, tt := range tests {
if !tt.set1.match(tt.set2) && tt.expect {
t.Fatalf("Expected match '%s'\n", tt.desc)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/sql.go | pkg/storage/driver/sql.go | /*
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 driver // import "helm.sh/helm/v4/pkg/storage/driver"
import (
"fmt"
"log/slog"
"maps"
"sort"
"strconv"
"time"
"github.com/jmoiron/sqlx"
migrate "github.com/rubenv/sql-migrate"
sq "github.com/Masterminds/squirrel"
// Import pq for postgres dialect
_ "github.com/lib/pq"
"helm.sh/helm/v4/internal/logging"
"helm.sh/helm/v4/pkg/release"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
var _ Driver = (*SQL)(nil)
var labelMap = map[string]struct{}{
"modifiedAt": {},
"createdAt": {},
"version": {},
"status": {},
"owner": {},
"name": {},
}
const postgreSQLDialect = "postgres"
// SQLDriverName is the string name of this driver.
const SQLDriverName = "SQL"
const sqlReleaseTableName = "releases_v1"
const sqlCustomLabelsTableName = "custom_labels_v1"
const (
sqlReleaseTableKeyColumn = "key"
sqlReleaseTableTypeColumn = "type"
sqlReleaseTableBodyColumn = "body"
sqlReleaseTableNameColumn = "name"
sqlReleaseTableNamespaceColumn = "namespace"
sqlReleaseTableVersionColumn = "version"
sqlReleaseTableStatusColumn = "status"
sqlReleaseTableOwnerColumn = "owner"
sqlReleaseTableCreatedAtColumn = "createdAt"
sqlReleaseTableModifiedAtColumn = "modifiedAt"
sqlCustomLabelsTableReleaseKeyColumn = "releaseKey"
sqlCustomLabelsTableReleaseNamespaceColumn = "releaseNamespace"
sqlCustomLabelsTableKeyColumn = "key"
sqlCustomLabelsTableValueColumn = "value"
)
// Following limits based on k8s labels limits - https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set
const (
sqlCustomLabelsTableKeyMaxLength = 253 + 1 + 63
sqlCustomLabelsTableValueMaxLength = 63
)
const (
sqlReleaseDefaultOwner = "helm"
sqlReleaseDefaultType = "helm.sh/release.v1"
)
// SQL is the sql storage driver implementation.
type SQL struct {
db *sqlx.DB
namespace string
statementBuilder sq.StatementBuilderType
// Embed a LogHolder to provide logger functionality
logging.LogHolder
}
// Name returns the name of the driver.
func (s *SQL) Name() string {
return SQLDriverName
}
// Check if all migrations al
func (s *SQL) checkAlreadyApplied(migrations []*migrate.Migration) bool {
// make map (set) of ids for fast search
migrationsIDs := make(map[string]struct{})
for _, migration := range migrations {
migrationsIDs[migration.Id] = struct{}{}
}
// get list of applied migrations
migrate.SetDisableCreateTable(true)
records, err := migrate.GetMigrationRecords(s.db.DB, postgreSQLDialect)
migrate.SetDisableCreateTable(false)
if err != nil {
s.Logger().Debug("failed to get migration records", slog.Any("error", err))
return false
}
for _, record := range records {
if _, ok := migrationsIDs[record.Id]; ok {
s.Logger().Debug("found previous migration", "id", record.Id, "appliedAt", record.AppliedAt)
delete(migrationsIDs, record.Id)
}
}
// check if all migrations applied
if len(migrationsIDs) != 0 {
for id := range migrationsIDs {
s.Logger().Debug("find unapplied migration", "id", id)
}
return false
}
return true
}
func (s *SQL) ensureDBSetup() error {
migrations := &migrate.MemoryMigrationSource{
Migrations: []*migrate.Migration{
{
Id: "init",
Up: []string{
fmt.Sprintf(`
CREATE TABLE %s (
%s VARCHAR(90),
%s VARCHAR(64) NOT NULL,
%s TEXT NOT NULL,
%s VARCHAR(64) NOT NULL,
%s VARCHAR(64) NOT NULL,
%s INTEGER NOT NULL,
%s TEXT NOT NULL,
%s TEXT NOT NULL,
%s INTEGER NOT NULL,
%s INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY(%s, %s)
);
CREATE INDEX ON %s (%s, %s);
CREATE INDEX ON %s (%s);
CREATE INDEX ON %s (%s);
CREATE INDEX ON %s (%s);
CREATE INDEX ON %s (%s);
CREATE INDEX ON %s (%s);
GRANT ALL ON %s TO PUBLIC;
ALTER TABLE %s ENABLE ROW LEVEL SECURITY;
`,
sqlReleaseTableName,
sqlReleaseTableKeyColumn,
sqlReleaseTableTypeColumn,
sqlReleaseTableBodyColumn,
sqlReleaseTableNameColumn,
sqlReleaseTableNamespaceColumn,
sqlReleaseTableVersionColumn,
sqlReleaseTableStatusColumn,
sqlReleaseTableOwnerColumn,
sqlReleaseTableCreatedAtColumn,
sqlReleaseTableModifiedAtColumn,
sqlReleaseTableKeyColumn,
sqlReleaseTableNamespaceColumn,
sqlReleaseTableName,
sqlReleaseTableKeyColumn,
sqlReleaseTableNamespaceColumn,
sqlReleaseTableName,
sqlReleaseTableVersionColumn,
sqlReleaseTableName,
sqlReleaseTableStatusColumn,
sqlReleaseTableName,
sqlReleaseTableOwnerColumn,
sqlReleaseTableName,
sqlReleaseTableCreatedAtColumn,
sqlReleaseTableName,
sqlReleaseTableModifiedAtColumn,
sqlReleaseTableName,
sqlReleaseTableName,
),
},
Down: []string{
fmt.Sprintf(`
DROP TABLE %s;
`, sqlReleaseTableName),
},
},
{
Id: "custom_labels",
Up: []string{
fmt.Sprintf(`
CREATE TABLE %s (
%s VARCHAR(64),
%s VARCHAR(67),
%s VARCHAR(%d),
%s VARCHAR(%d)
);
CREATE INDEX ON %s (%s, %s);
GRANT ALL ON %s TO PUBLIC;
ALTER TABLE %s ENABLE ROW LEVEL SECURITY;
`,
sqlCustomLabelsTableName,
sqlCustomLabelsTableReleaseKeyColumn,
sqlCustomLabelsTableReleaseNamespaceColumn,
sqlCustomLabelsTableKeyColumn,
sqlCustomLabelsTableKeyMaxLength,
sqlCustomLabelsTableValueColumn,
sqlCustomLabelsTableValueMaxLength,
sqlCustomLabelsTableName,
sqlCustomLabelsTableReleaseKeyColumn,
sqlCustomLabelsTableReleaseNamespaceColumn,
sqlCustomLabelsTableName,
sqlCustomLabelsTableName,
),
},
Down: []string{
fmt.Sprintf(`
DELETE TABLE %s;
`, sqlCustomLabelsTableName),
},
},
},
}
// Check that init migration already applied
if s.checkAlreadyApplied(migrations.Migrations) {
return nil
}
// Populate the database with the relations we need if they don't exist yet
_, err := migrate.Exec(s.db.DB, postgreSQLDialect, migrations, migrate.Up)
return err
}
// SQLReleaseWrapper describes how Helm releases are stored in an SQL database
type SQLReleaseWrapper struct {
// The primary key, made of {release-name}.{release-version}
Key string `db:"key"`
// See https://github.com/helm/helm/blob/c9fe3d118caec699eb2565df9838673af379ce12/pkg/storage/driver/secrets.go#L231
Type string `db:"type"`
// The rspb.Release body, as a base64-encoded string
Body string `db:"body"`
// Release "labels" that can be used as filters in the storage.Query(labels map[string]string)
// we implemented. Note that allowing Helm users to filter against new dimensions will require a
// new migration to be added, and the Create and/or update functions to be updated accordingly.
Name string `db:"name"`
Namespace string `db:"namespace"`
Version int `db:"version"`
Status string `db:"status"`
Owner string `db:"owner"`
CreatedAt int `db:"createdAt"`
ModifiedAt int `db:"modifiedAt"`
}
type SQLReleaseCustomLabelWrapper struct {
ReleaseKey string `db:"release_key"`
ReleaseNamespace string `db:"release_namespace"`
Key string `db:"key"`
Value string `db:"value"`
}
// NewSQL initializes a new sql driver.
func NewSQL(connectionString string, namespace string) (*SQL, error) {
db, err := sqlx.Connect(postgreSQLDialect, connectionString)
if err != nil {
return nil, err
}
driver := &SQL{
db: db,
statementBuilder: sq.StatementBuilder.PlaceholderFormat(sq.Dollar),
}
if err := driver.ensureDBSetup(); err != nil {
return nil, err
}
driver.namespace = namespace
driver.SetLogger(slog.Default().Handler())
return driver, nil
}
// Get returns the release named by key.
func (s *SQL) Get(key string) (release.Releaser, error) {
var record SQLReleaseWrapper
qb := s.statementBuilder.
Select(sqlReleaseTableBodyColumn).
From(sqlReleaseTableName).
Where(sq.Eq{sqlReleaseTableKeyColumn: key}).
Where(sq.Eq{sqlReleaseTableNamespaceColumn: s.namespace})
query, args, err := qb.ToSql()
if err != nil {
s.Logger().Debug("failed to build query", slog.Any("error", err))
return nil, err
}
// Get will return an error if the result is empty
if err := s.db.Get(&record, query, args...); err != nil {
s.Logger().Debug("got SQL error when getting release", slog.String("key", key), slog.Any("error", err))
return nil, ErrReleaseNotFound
}
release, err := decodeRelease(record.Body)
if err != nil {
s.Logger().Debug("failed to decode data", slog.String("key", key), slog.Any("error", err))
return nil, err
}
if release.Labels, err = s.getReleaseCustomLabels(key, s.namespace); err != nil {
s.Logger().Debug(
"failed to get release custom labels",
slog.String("namespace", s.namespace),
slog.String("key", key),
slog.Any("error", err),
)
return nil, err
}
return release, nil
}
// List returns the list of all releases such that filter(release) == true
func (s *SQL) List(filter func(release.Releaser) bool) ([]release.Releaser, error) {
sb := s.statementBuilder.
Select(sqlReleaseTableKeyColumn, sqlReleaseTableNamespaceColumn, sqlReleaseTableBodyColumn).
From(sqlReleaseTableName).
Where(sq.Eq{sqlReleaseTableOwnerColumn: sqlReleaseDefaultOwner})
// If a namespace was specified, we only list releases from that namespace
if s.namespace != "" {
sb = sb.Where(sq.Eq{sqlReleaseTableNamespaceColumn: s.namespace})
}
query, args, err := sb.ToSql()
if err != nil {
s.Logger().Debug("failed to build query", slog.Any("error", err))
return nil, err
}
var records = []SQLReleaseWrapper{}
if err := s.db.Select(&records, query, args...); err != nil {
s.Logger().Debug("failed to list", slog.Any("error", err))
return nil, err
}
var releases []release.Releaser
for _, record := range records {
release, err := decodeRelease(record.Body)
if err != nil {
s.Logger().Debug("failed to decode release", slog.Any("record", record), slog.Any("error", err))
continue
}
if release.Labels, err = s.getReleaseCustomLabels(record.Key, record.Namespace); err != nil {
s.Logger().Debug(
"failed to get release custom labels",
slog.String("namespace", record.Namespace),
slog.String("key", record.Key),
slog.Any("error", err),
)
return nil, err
}
maps.Copy(release.Labels, getReleaseSystemLabels(release))
if filter(release) {
releases = append(releases, release)
}
}
return releases, nil
}
// Query returns the set of releases that match the provided set of labels.
func (s *SQL) Query(labels map[string]string) ([]release.Releaser, error) {
sb := s.statementBuilder.
Select(sqlReleaseTableKeyColumn, sqlReleaseTableNamespaceColumn, sqlReleaseTableBodyColumn).
From(sqlReleaseTableName)
keys := make([]string, 0, len(labels))
for key := range labels {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
if _, ok := labelMap[key]; ok {
sb = sb.Where(sq.Eq{key: labels[key]})
} else {
s.Logger().Debug("unknown label", "key", key)
return nil, fmt.Errorf("unknown label %s", key)
}
}
// If a namespace was specified, we only list releases from that namespace
if s.namespace != "" {
sb = sb.Where(sq.Eq{sqlReleaseTableNamespaceColumn: s.namespace})
}
// Build our query
query, args, err := sb.ToSql()
if err != nil {
s.Logger().Debug("failed to build query", slog.Any("error", err))
return nil, err
}
var records = []SQLReleaseWrapper{}
if err := s.db.Select(&records, query, args...); err != nil {
s.Logger().Debug("failed to query with labels", slog.Any("error", err))
return nil, err
}
if len(records) == 0 {
return nil, ErrReleaseNotFound
}
var releases []release.Releaser
for _, record := range records {
release, err := decodeRelease(record.Body)
if err != nil {
s.Logger().Debug("failed to decode release", slog.Any("record", record), slog.Any("error", err))
continue
}
if release.Labels, err = s.getReleaseCustomLabels(record.Key, record.Namespace); err != nil {
s.Logger().Debug(
"failed to get release custom labels",
slog.String("namespace", record.Namespace),
slog.String("key", record.Key),
slog.Any("error", err),
)
return nil, err
}
releases = append(releases, release)
}
if len(releases) == 0 {
return nil, ErrReleaseNotFound
}
return releases, nil
}
// Create creates a new release.
func (s *SQL) Create(key string, rel release.Releaser) error {
rls, err := releaserToV1Release(rel)
if err != nil {
return err
}
namespace := rls.Namespace
if namespace == "" {
namespace = defaultNamespace
}
s.namespace = namespace
body, err := encodeRelease(rls)
if err != nil {
s.Logger().Debug("failed to encode release", slog.Any("error", err))
return err
}
transaction, err := s.db.Beginx()
if err != nil {
s.Logger().Debug("failed to start SQL transaction", slog.Any("error", err))
return fmt.Errorf("error beginning transaction: %v", err)
}
insertQuery, args, err := s.statementBuilder.
Insert(sqlReleaseTableName).
Columns(
sqlReleaseTableKeyColumn,
sqlReleaseTableTypeColumn,
sqlReleaseTableBodyColumn,
sqlReleaseTableNameColumn,
sqlReleaseTableNamespaceColumn,
sqlReleaseTableVersionColumn,
sqlReleaseTableStatusColumn,
sqlReleaseTableOwnerColumn,
sqlReleaseTableCreatedAtColumn,
).
Values(
key,
sqlReleaseDefaultType,
body,
rls.Name,
namespace,
int(rls.Version),
rls.Info.Status.String(),
sqlReleaseDefaultOwner,
int(time.Now().Unix()),
).ToSql()
if err != nil {
s.Logger().Debug("failed to build insert query", slog.Any("error", err))
return err
}
if _, err := transaction.Exec(insertQuery, args...); err != nil {
defer transaction.Rollback()
selectQuery, args, buildErr := s.statementBuilder.
Select(sqlReleaseTableKeyColumn).
From(sqlReleaseTableName).
Where(sq.Eq{sqlReleaseTableKeyColumn: key}).
Where(sq.Eq{sqlReleaseTableNamespaceColumn: s.namespace}).
ToSql()
if buildErr != nil {
s.Logger().Debug("failed to build select query", "error", buildErr)
return err
}
var record SQLReleaseWrapper
if err := transaction.Get(&record, selectQuery, args...); err == nil {
s.Logger().Debug("release already exists", slog.String("key", key))
return ErrReleaseExists
}
s.Logger().Debug("failed to store release in SQL database", slog.String("key", key), slog.Any("error", err))
return err
}
// Filtering labels before insert cause in SQL storage driver system releases are stored in separate columns of release table
for k, v := range filterSystemLabels(rls.Labels) {
insertLabelsQuery, args, err := s.statementBuilder.
Insert(sqlCustomLabelsTableName).
Columns(
sqlCustomLabelsTableReleaseKeyColumn,
sqlCustomLabelsTableReleaseNamespaceColumn,
sqlCustomLabelsTableKeyColumn,
sqlCustomLabelsTableValueColumn,
).
Values(
key,
namespace,
k,
v,
).ToSql()
if err != nil {
defer transaction.Rollback()
s.Logger().Debug("failed to build insert query", slog.Any("error", err))
return err
}
if _, err := transaction.Exec(insertLabelsQuery, args...); err != nil {
defer transaction.Rollback()
s.Logger().Debug("failed to write Labels", slog.Any("error", err))
return err
}
}
defer transaction.Commit()
return nil
}
// Update updates a release.
func (s *SQL) Update(key string, rel release.Releaser) error {
rls, err := releaserToV1Release(rel)
if err != nil {
return err
}
namespace := rls.Namespace
if namespace == "" {
namespace = defaultNamespace
}
s.namespace = namespace
body, err := encodeRelease(rls)
if err != nil {
s.Logger().Debug("failed to encode release", slog.Any("error", err))
return err
}
query, args, err := s.statementBuilder.
Update(sqlReleaseTableName).
Set(sqlReleaseTableBodyColumn, body).
Set(sqlReleaseTableNameColumn, rls.Name).
Set(sqlReleaseTableVersionColumn, int(rls.Version)).
Set(sqlReleaseTableStatusColumn, rls.Info.Status.String()).
Set(sqlReleaseTableOwnerColumn, sqlReleaseDefaultOwner).
Set(sqlReleaseTableModifiedAtColumn, int(time.Now().Unix())).
Where(sq.Eq{sqlReleaseTableKeyColumn: key}).
Where(sq.Eq{sqlReleaseTableNamespaceColumn: namespace}).
ToSql()
if err != nil {
s.Logger().Debug("failed to build update query", slog.Any("error", err))
return err
}
if _, err := s.db.Exec(query, args...); err != nil {
s.Logger().Debug("failed to update release in SQL database", slog.String("key", key), slog.Any("error", err))
return err
}
return nil
}
// Delete deletes a release or returns ErrReleaseNotFound.
func (s *SQL) Delete(key string) (release.Releaser, error) {
transaction, err := s.db.Beginx()
if err != nil {
s.Logger().Debug("failed to start SQL transaction", slog.Any("error", err))
return nil, fmt.Errorf("error beginning transaction: %v", err)
}
selectQuery, args, err := s.statementBuilder.
Select(sqlReleaseTableBodyColumn).
From(sqlReleaseTableName).
Where(sq.Eq{sqlReleaseTableKeyColumn: key}).
Where(sq.Eq{sqlReleaseTableNamespaceColumn: s.namespace}).
ToSql()
if err != nil {
s.Logger().Debug("failed to build select query", slog.Any("error", err))
return nil, err
}
var record SQLReleaseWrapper
err = transaction.Get(&record, selectQuery, args...)
if err != nil {
s.Logger().Debug("release not found", slog.String("key", key), slog.Any("error", err))
return nil, ErrReleaseNotFound
}
release, err := decodeRelease(record.Body)
if err != nil {
s.Logger().Debug("failed to decode release", slog.String("key", key), slog.Any("error", err))
transaction.Rollback()
return nil, err
}
defer transaction.Commit()
deleteQuery, args, err := s.statementBuilder.
Delete(sqlReleaseTableName).
Where(sq.Eq{sqlReleaseTableKeyColumn: key}).
Where(sq.Eq{sqlReleaseTableNamespaceColumn: s.namespace}).
ToSql()
if err != nil {
s.Logger().Debug("failed to build delete query", slog.Any("error", err))
return nil, err
}
_, err = transaction.Exec(deleteQuery, args...)
if err != nil {
s.Logger().Debug("failed perform delete query", slog.Any("error", err))
return release, err
}
if release.Labels, err = s.getReleaseCustomLabels(key, s.namespace); err != nil {
s.Logger().Debug(
"failed to get release custom labels",
slog.String("namespace", s.namespace),
slog.String("key", key),
slog.Any("error", err))
return nil, err
}
deleteCustomLabelsQuery, args, err := s.statementBuilder.
Delete(sqlCustomLabelsTableName).
Where(sq.Eq{sqlCustomLabelsTableReleaseKeyColumn: key}).
Where(sq.Eq{sqlCustomLabelsTableReleaseNamespaceColumn: s.namespace}).
ToSql()
if err != nil {
s.Logger().Debug("failed to build delete Labels query", slog.Any("error", err))
return nil, err
}
_, err = transaction.Exec(deleteCustomLabelsQuery, args...)
return release, err
}
// Get release custom labels from database
func (s *SQL) getReleaseCustomLabels(key string, _ string) (map[string]string, error) {
query, args, err := s.statementBuilder.
Select(sqlCustomLabelsTableKeyColumn, sqlCustomLabelsTableValueColumn).
From(sqlCustomLabelsTableName).
Where(sq.Eq{sqlCustomLabelsTableReleaseKeyColumn: key,
sqlCustomLabelsTableReleaseNamespaceColumn: s.namespace}).
ToSql()
if err != nil {
return nil, err
}
var labelsList = []SQLReleaseCustomLabelWrapper{}
if err := s.db.Select(&labelsList, query, args...); err != nil {
return nil, err
}
labelsMap := make(map[string]string)
for _, i := range labelsList {
labelsMap[i.Key] = i.Value
}
return filterSystemLabels(labelsMap), nil
}
// Rebuild system labels from release object
func getReleaseSystemLabels(rls *rspb.Release) map[string]string {
return map[string]string{
"name": rls.Name,
"owner": sqlReleaseDefaultOwner,
"status": rls.Info.Status.String(),
"version": strconv.Itoa(rls.Version),
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/sql_test.go | pkg/storage/driver/sql_test.go | /*
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 driver
import (
"database/sql/driver"
"fmt"
"reflect"
"regexp"
"testing"
"time"
sqlmock "github.com/DATA-DOG/go-sqlmock"
migrate "github.com/rubenv/sql-migrate"
"helm.sh/helm/v4/pkg/release"
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
const recentTimestampTolerance = time.Second
func recentUnixTimestamp() sqlmock.Argument {
return recentUnixTimestampArgument{}
}
type recentUnixTimestampArgument struct{}
func (recentUnixTimestampArgument) Match(value driver.Value) bool {
var ts int64
switch v := value.(type) {
case int:
ts = int64(v)
case int64:
ts = v
default:
return false
}
diff := time.Since(time.Unix(ts, 0))
if diff < 0 {
diff = -diff
}
return diff <= recentTimestampTolerance
}
func TestSQLName(t *testing.T) {
sqlDriver, _ := newTestFixtureSQL(t)
if sqlDriver.Name() != SQLDriverName {
t.Errorf("Expected name to be %s, got %s", SQLDriverName, sqlDriver.Name())
}
}
func TestSQLGet(t *testing.T) {
vers := int(1)
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
body, _ := encodeRelease(rel)
sqlDriver, mock := newTestFixtureSQL(t)
query := fmt.Sprintf(
regexp.QuoteMeta("SELECT %s FROM %s WHERE %s = $1 AND %s = $2"),
sqlReleaseTableBodyColumn,
sqlReleaseTableName,
sqlReleaseTableKeyColumn,
sqlReleaseTableNamespaceColumn,
)
mock.
ExpectQuery(query).
WithArgs(key, namespace).
WillReturnRows(
mock.NewRows([]string{
sqlReleaseTableBodyColumn,
}).AddRow(
body,
),
).RowsWillBeClosed()
mockGetReleaseCustomLabels(mock, key, namespace, rel.Labels)
got, err := sqlDriver.Get(key)
if err != nil {
t.Fatalf("Failed to get release: %v", err)
}
if !reflect.DeepEqual(rel, got) {
t.Errorf("Expected release {%v}, got {%v}", rel, got)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("sql expectations weren't met: %v", err)
}
}
func TestSQLList(t *testing.T) {
releases := []*rspb.Release{}
releases = append(releases, releaseStub("key-1", 1, "default", common.StatusUninstalled))
releases = append(releases, releaseStub("key-2", 1, "default", common.StatusUninstalled))
releases = append(releases, releaseStub("key-3", 1, "default", common.StatusDeployed))
releases = append(releases, releaseStub("key-4", 1, "default", common.StatusDeployed))
releases = append(releases, releaseStub("key-5", 1, "default", common.StatusSuperseded))
releases = append(releases, releaseStub("key-6", 1, "default", common.StatusSuperseded))
sqlDriver, mock := newTestFixtureSQL(t)
for range 3 {
query := fmt.Sprintf(
"SELECT %s, %s, %s FROM %s WHERE %s = $1 AND %s = $2",
sqlReleaseTableKeyColumn,
sqlReleaseTableNamespaceColumn,
sqlReleaseTableBodyColumn,
sqlReleaseTableName,
sqlReleaseTableOwnerColumn,
sqlReleaseTableNamespaceColumn,
)
rows := mock.NewRows([]string{
sqlReleaseTableBodyColumn,
})
for _, r := range releases {
body, _ := encodeRelease(r)
rows.AddRow(body)
}
mock.
ExpectQuery(regexp.QuoteMeta(query)).
WithArgs(sqlReleaseDefaultOwner, sqlDriver.namespace).
WillReturnRows(rows).RowsWillBeClosed()
for _, r := range releases {
mockGetReleaseCustomLabels(mock, "", r.Namespace, r.Labels)
}
}
// list all deleted releases
del, err := sqlDriver.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusUninstalled
})
// check
if err != nil {
t.Errorf("Failed to list deleted: %v", err)
}
if len(del) != 2 {
t.Errorf("Expected 2 deleted, got %d:\n%v\n", len(del), del)
}
// list all deployed releases
dpl, err := sqlDriver.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusDeployed
})
// check
if err != nil {
t.Errorf("Failed to list deployed: %v", err)
}
if len(dpl) != 2 {
t.Errorf("Expected 2 deployed, got %d:\n%v\n", len(dpl), dpl)
}
// list all superseded releases
ssd, err := sqlDriver.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusSuperseded
})
// check
if err != nil {
t.Errorf("Failed to list superseded: %v", err)
}
if len(ssd) != 2 {
t.Errorf("Expected 2 superseded, got %d:\n%v\n", len(ssd), ssd)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("sql expectations weren't met: %v", err)
}
// Check if release having both system and custom labels, this is needed to ensure that selector filtering would work.
rls := convertReleaserToV1(t, ssd[0])
_, ok := rls.Labels["name"]
if !ok {
t.Fatalf("Expected 'name' label in results, actual %v", rls.Labels)
}
_, ok = rls.Labels["key1"]
if !ok {
t.Fatalf("Expected 'key1' label in results, actual %v", rls.Labels)
}
}
func TestSqlCreate(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
sqlDriver, mock := newTestFixtureSQL(t)
body, _ := encodeRelease(rel)
query := fmt.Sprintf(
"INSERT INTO %s (%s,%s,%s,%s,%s,%s,%s,%s,%s) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)",
sqlReleaseTableName,
sqlReleaseTableKeyColumn,
sqlReleaseTableTypeColumn,
sqlReleaseTableBodyColumn,
sqlReleaseTableNameColumn,
sqlReleaseTableNamespaceColumn,
sqlReleaseTableVersionColumn,
sqlReleaseTableStatusColumn,
sqlReleaseTableOwnerColumn,
sqlReleaseTableCreatedAtColumn,
)
mock.ExpectBegin()
mock.
ExpectExec(regexp.QuoteMeta(query)).
WithArgs(key, sqlReleaseDefaultType, body, rel.Name, rel.Namespace, int(rel.Version), rel.Info.Status.String(), sqlReleaseDefaultOwner, recentUnixTimestamp()).
WillReturnResult(sqlmock.NewResult(1, 1))
labelsQuery := fmt.Sprintf(
"INSERT INTO %s (%s,%s,%s,%s) VALUES ($1,$2,$3,$4)",
sqlCustomLabelsTableName,
sqlCustomLabelsTableReleaseKeyColumn,
sqlCustomLabelsTableReleaseNamespaceColumn,
sqlCustomLabelsTableKeyColumn,
sqlCustomLabelsTableValueColumn,
)
mock.MatchExpectationsInOrder(false)
for k, v := range filterSystemLabels(rel.Labels) {
mock.
ExpectExec(regexp.QuoteMeta(labelsQuery)).
WithArgs(key, rel.Namespace, k, v).
WillReturnResult(sqlmock.NewResult(1, 1))
}
mock.ExpectCommit()
if err := sqlDriver.Create(key, rel); err != nil {
t.Fatalf("failed to create release with key %s: %v", key, err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("sql expectations weren't met: %v", err)
}
}
func TestSqlCreateAlreadyExists(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
sqlDriver, mock := newTestFixtureSQL(t)
body, _ := encodeRelease(rel)
insertQuery := fmt.Sprintf(
"INSERT INTO %s (%s,%s,%s,%s,%s,%s,%s,%s,%s) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)",
sqlReleaseTableName,
sqlReleaseTableKeyColumn,
sqlReleaseTableTypeColumn,
sqlReleaseTableBodyColumn,
sqlReleaseTableNameColumn,
sqlReleaseTableNamespaceColumn,
sqlReleaseTableVersionColumn,
sqlReleaseTableStatusColumn,
sqlReleaseTableOwnerColumn,
sqlReleaseTableCreatedAtColumn,
)
// Insert fails (primary key already exists)
mock.ExpectBegin()
mock.
ExpectExec(regexp.QuoteMeta(insertQuery)).
WithArgs(key, sqlReleaseDefaultType, body, rel.Name, rel.Namespace, int(rel.Version), rel.Info.Status.String(), sqlReleaseDefaultOwner, recentUnixTimestamp()).
WillReturnError(fmt.Errorf("dialect dependent SQL error"))
selectQuery := fmt.Sprintf(
regexp.QuoteMeta("SELECT %s FROM %s WHERE %s = $1 AND %s = $2"),
sqlReleaseTableKeyColumn,
sqlReleaseTableName,
sqlReleaseTableKeyColumn,
sqlReleaseTableNamespaceColumn,
)
// Let's check that we do make sure the error is due to a release already existing
mock.
ExpectQuery(selectQuery).
WithArgs(key, namespace).
WillReturnRows(
mock.NewRows([]string{
sqlReleaseTableKeyColumn,
}).AddRow(
key,
),
).RowsWillBeClosed()
mock.ExpectRollback()
if err := sqlDriver.Create(key, rel); err == nil {
t.Fatalf("failed to create release with key %s: %v", key, err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("sql expectations weren't met: %v", err)
}
}
func TestSqlUpdate(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
sqlDriver, mock := newTestFixtureSQL(t)
body, _ := encodeRelease(rel)
query := fmt.Sprintf(
"UPDATE %s SET %s = $1, %s = $2, %s = $3, %s = $4, %s = $5, %s = $6 WHERE %s = $7 AND %s = $8",
sqlReleaseTableName,
sqlReleaseTableBodyColumn,
sqlReleaseTableNameColumn,
sqlReleaseTableVersionColumn,
sqlReleaseTableStatusColumn,
sqlReleaseTableOwnerColumn,
sqlReleaseTableModifiedAtColumn,
sqlReleaseTableKeyColumn,
sqlReleaseTableNamespaceColumn,
)
mock.
ExpectExec(regexp.QuoteMeta(query)).
WithArgs(body, rel.Name, int(rel.Version), rel.Info.Status.String(), sqlReleaseDefaultOwner, recentUnixTimestamp(), key, namespace).
WillReturnResult(sqlmock.NewResult(0, 1))
if err := sqlDriver.Update(key, rel); err != nil {
t.Fatalf("failed to update release with key %s: %v", key, err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("sql expectations weren't met: %v", err)
}
}
func TestSqlQuery(t *testing.T) {
// Reflect actual use cases in ../storage.go
labelSetUnknown := map[string]string{
"name": "smug-pigeon",
"owner": sqlReleaseDefaultOwner,
"status": "unknown",
}
labelSetDeployed := map[string]string{
"name": "smug-pigeon",
"owner": sqlReleaseDefaultOwner,
"status": "deployed",
}
labelSetAll := map[string]string{
"name": "smug-pigeon",
"owner": sqlReleaseDefaultOwner,
}
supersededRelease := releaseStub("smug-pigeon", 1, "default", common.StatusSuperseded)
supersededReleaseBody, _ := encodeRelease(supersededRelease)
deployedRelease := releaseStub("smug-pigeon", 2, "default", common.StatusDeployed)
deployedReleaseBody, _ := encodeRelease(deployedRelease)
// Let's actually start our test
sqlDriver, mock := newTestFixtureSQL(t)
query := fmt.Sprintf(
"SELECT %s, %s, %s FROM %s WHERE %s = $1 AND %s = $2 AND %s = $3 AND %s = $4",
sqlReleaseTableKeyColumn,
sqlReleaseTableNamespaceColumn,
sqlReleaseTableBodyColumn,
sqlReleaseTableName,
sqlReleaseTableNameColumn,
sqlReleaseTableOwnerColumn,
sqlReleaseTableStatusColumn,
sqlReleaseTableNamespaceColumn,
)
mock.
ExpectQuery(regexp.QuoteMeta(query)).
WithArgs("smug-pigeon", sqlReleaseDefaultOwner, "unknown", "default").
WillReturnRows(
mock.NewRows([]string{
sqlReleaseTableBodyColumn,
}),
).RowsWillBeClosed()
mock.
ExpectQuery(regexp.QuoteMeta(query)).
WithArgs("smug-pigeon", sqlReleaseDefaultOwner, "deployed", "default").
WillReturnRows(
mock.NewRows([]string{
sqlReleaseTableBodyColumn,
}).AddRow(
deployedReleaseBody,
),
).RowsWillBeClosed()
mockGetReleaseCustomLabels(mock, "", deployedRelease.Namespace, deployedRelease.Labels)
query = fmt.Sprintf(
"SELECT %s, %s, %s FROM %s WHERE %s = $1 AND %s = $2 AND %s = $3",
sqlReleaseTableKeyColumn,
sqlReleaseTableNamespaceColumn,
sqlReleaseTableBodyColumn,
sqlReleaseTableName,
sqlReleaseTableNameColumn,
sqlReleaseTableOwnerColumn,
sqlReleaseTableNamespaceColumn,
)
mock.
ExpectQuery(regexp.QuoteMeta(query)).
WithArgs("smug-pigeon", sqlReleaseDefaultOwner, "default").
WillReturnRows(
mock.NewRows([]string{
sqlReleaseTableBodyColumn,
}).AddRow(
supersededReleaseBody,
).AddRow(
deployedReleaseBody,
),
).RowsWillBeClosed()
mockGetReleaseCustomLabels(mock, "", supersededRelease.Namespace, supersededRelease.Labels)
mockGetReleaseCustomLabels(mock, "", deployedRelease.Namespace, deployedRelease.Labels)
_, err := sqlDriver.Query(labelSetUnknown)
if err == nil {
t.Errorf("Expected error {%v}, got nil", ErrReleaseNotFound)
} else if err != ErrReleaseNotFound {
t.Fatalf("failed to query for unknown smug-pigeon release: %v", err)
}
results, err := sqlDriver.Query(labelSetDeployed)
if err != nil {
t.Fatalf("failed to query for deployed smug-pigeon release: %v", err)
}
for _, res := range results {
if !reflect.DeepEqual(res, deployedRelease) {
t.Errorf("Expected release {%v}, got {%v}", deployedRelease, res)
}
}
results, err = sqlDriver.Query(labelSetAll)
if err != nil {
t.Fatalf("failed to query release history for smug-pigeon: %v", err)
}
if len(results) != 2 {
t.Errorf("expected a resultset of size 2, got %d", len(results))
}
for _, res := range results {
if !reflect.DeepEqual(res, deployedRelease) && !reflect.DeepEqual(res, supersededRelease) {
t.Errorf("Expected release {%v} or {%v}, got {%v}", deployedRelease, supersededRelease, res)
}
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("sql expectations weren't met: %v", err)
}
}
func TestSqlDelete(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
body, _ := encodeRelease(rel)
sqlDriver, mock := newTestFixtureSQL(t)
selectQuery := fmt.Sprintf(
"SELECT %s FROM %s WHERE %s = $1 AND %s = $2",
sqlReleaseTableBodyColumn,
sqlReleaseTableName,
sqlReleaseTableKeyColumn,
sqlReleaseTableNamespaceColumn,
)
mock.ExpectBegin()
mock.
ExpectQuery(regexp.QuoteMeta(selectQuery)).
WithArgs(key, namespace).
WillReturnRows(
mock.NewRows([]string{
sqlReleaseTableBodyColumn,
}).AddRow(
body,
),
).RowsWillBeClosed()
deleteQuery := fmt.Sprintf(
"DELETE FROM %s WHERE %s = $1 AND %s = $2",
sqlReleaseTableName,
sqlReleaseTableKeyColumn,
sqlReleaseTableNamespaceColumn,
)
mock.
ExpectExec(regexp.QuoteMeta(deleteQuery)).
WithArgs(key, namespace).
WillReturnResult(sqlmock.NewResult(0, 1))
mockGetReleaseCustomLabels(mock, key, namespace, rel.Labels)
deleteLabelsQuery := fmt.Sprintf(
"DELETE FROM %s WHERE %s = $1 AND %s = $2",
sqlCustomLabelsTableName,
sqlCustomLabelsTableReleaseKeyColumn,
sqlCustomLabelsTableReleaseNamespaceColumn,
)
mock.
ExpectExec(regexp.QuoteMeta(deleteLabelsQuery)).
WithArgs(key, namespace).
WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()
deletedRelease, err := sqlDriver.Delete(key)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("sql expectations weren't met: %v", err)
}
if err != nil {
t.Fatalf("failed to delete release with key %q: %v", key, err)
}
if !reflect.DeepEqual(rel, deletedRelease) {
t.Errorf("Expected release {%v}, got {%v}", rel, deletedRelease)
}
}
func mockGetReleaseCustomLabels(mock sqlmock.Sqlmock, key string, namespace string, labels map[string]string) {
query := fmt.Sprintf(
regexp.QuoteMeta("SELECT %s, %s FROM %s WHERE %s = $1 AND %s = $2"),
sqlCustomLabelsTableKeyColumn,
sqlCustomLabelsTableValueColumn,
sqlCustomLabelsTableName,
sqlCustomLabelsTableReleaseKeyColumn,
sqlCustomLabelsTableReleaseNamespaceColumn,
)
eq := mock.ExpectQuery(query).
WithArgs(key, namespace)
returnRows := mock.NewRows([]string{
sqlCustomLabelsTableKeyColumn,
sqlCustomLabelsTableValueColumn,
})
for k, v := range labels {
returnRows.AddRow(k, v)
}
eq.WillReturnRows(returnRows).RowsWillBeClosed()
}
func TestSqlCheckAppliedMigrations(t *testing.T) {
cases := []struct {
migrationsToApply []*migrate.Migration
appliedMigrationsIDs []string
expectedResult bool
errorExplanation string
}{
{
migrationsToApply: []*migrate.Migration{{Id: "init1"}, {Id: "init2"}, {Id: "init3"}},
appliedMigrationsIDs: []string{"1", "2", "init1", "3", "init2", "4", "5"},
expectedResult: false,
errorExplanation: "Has found one migration id \"init3\" as applied, that was not applied",
},
{
migrationsToApply: []*migrate.Migration{{Id: "init1"}, {Id: "init2"}, {Id: "init3"}},
appliedMigrationsIDs: []string{"1", "2", "init1", "3", "init2", "4", "init3", "5"},
expectedResult: true,
errorExplanation: "Has not found one or more migration ids, that was applied",
},
{
migrationsToApply: []*migrate.Migration{{Id: "init"}},
appliedMigrationsIDs: []string{"1", "2", "3", "inits", "4", "tinit", "5"},
expectedResult: false,
errorExplanation: "Has found single \"init\", that was not applied",
},
{
migrationsToApply: []*migrate.Migration{{Id: "init"}},
appliedMigrationsIDs: []string{"1", "2", "init", "3", "init2", "4", "init3", "5"},
expectedResult: true,
errorExplanation: "Has not found single migration id \"init\", that was applied",
},
}
for i, c := range cases {
sqlDriver, mock := newTestFixtureSQL(t)
rows := sqlmock.NewRows([]string{"id", "applied_at"})
for _, id := range c.appliedMigrationsIDs {
rows.AddRow(id, time.Time{})
}
mock.
ExpectQuery("").
WillReturnRows(rows)
mock.ExpectCommit()
if sqlDriver.checkAlreadyApplied(c.migrationsToApply) != c.expectedResult {
t.Errorf("Test case: %v, Expected: %v, Have: %v, Explanation: %v", i, c.expectedResult, !c.expectedResult, c.errorExplanation)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/records_test.go | pkg/storage/driver/records_test.go | /*
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 driver // import "helm.sh/helm/v4/pkg/storage/driver"
import (
"reflect"
"testing"
"helm.sh/helm/v4/pkg/release/common"
)
func TestRecordsAdd(t *testing.T) {
rs := records([]*record{
newRecord("rls-a.v1", releaseStub("rls-a", 1, "default", common.StatusSuperseded)),
newRecord("rls-a.v2", releaseStub("rls-a", 2, "default", common.StatusDeployed)),
})
var tests = []struct {
desc string
key string
ok bool
rec *record
}{
{
"add valid key",
"rls-a.v3",
false,
newRecord("rls-a.v3", releaseStub("rls-a", 3, "default", common.StatusSuperseded)),
},
{
"add already existing key",
"rls-a.v1",
true,
newRecord("rls-a.v1", releaseStub("rls-a", 1, "default", common.StatusDeployed)),
},
}
for _, tt := range tests {
if err := rs.Add(tt.rec); err != nil {
if !tt.ok {
t.Fatalf("failed: %q: %s\n", tt.desc, err)
}
}
}
}
func TestRecordsRemove(t *testing.T) {
var tests = []struct {
desc string
key string
ok bool
}{
{"remove valid key", "rls-a.v1", false},
{"remove invalid key", "rls-a.v", true},
{"remove non-existent key", "rls-z.v1", true},
}
rs := records([]*record{
newRecord("rls-a.v1", releaseStub("rls-a", 1, "default", common.StatusSuperseded)),
newRecord("rls-a.v2", releaseStub("rls-a", 2, "default", common.StatusDeployed)),
})
startLen := rs.Len()
for _, tt := range tests {
if r := rs.Remove(tt.key); r == nil {
if !tt.ok {
t.Fatalf("Failed to %q (key = %s). Expected nil, got %v",
tt.desc,
tt.key,
r,
)
}
}
}
// We expect the total number of records will be less now than there were
// when we started.
endLen := rs.Len()
if endLen >= startLen {
t.Errorf("expected ending length %d to be less than starting length %d", endLen, startLen)
}
}
func TestRecordsRemoveAt(t *testing.T) {
rs := records([]*record{
newRecord("rls-a.v1", releaseStub("rls-a", 1, "default", common.StatusSuperseded)),
newRecord("rls-a.v2", releaseStub("rls-a", 2, "default", common.StatusDeployed)),
})
if len(rs) != 2 {
t.Fatal("Expected len=2 for mock")
}
rs.Remove("rls-a.v1")
if len(rs) != 1 {
t.Fatalf("Expected length of rs to be 1, got %d", len(rs))
}
}
func TestRecordsGet(t *testing.T) {
rs := records([]*record{
newRecord("rls-a.v1", releaseStub("rls-a", 1, "default", common.StatusSuperseded)),
newRecord("rls-a.v2", releaseStub("rls-a", 2, "default", common.StatusDeployed)),
})
var tests = []struct {
desc string
key string
rec *record
}{
{
"get valid key",
"rls-a.v1",
newRecord("rls-a.v1", releaseStub("rls-a", 1, "default", common.StatusSuperseded)),
},
{
"get invalid key",
"rls-a.v3",
nil,
},
}
for _, tt := range tests {
got := rs.Get(tt.key)
if !reflect.DeepEqual(tt.rec, got) {
t.Fatalf("Expected %v, got %v", tt.rec, got)
}
}
}
func TestRecordsIndex(t *testing.T) {
rs := records([]*record{
newRecord("rls-a.v1", releaseStub("rls-a", 1, "default", common.StatusSuperseded)),
newRecord("rls-a.v2", releaseStub("rls-a", 2, "default", common.StatusDeployed)),
})
var tests = []struct {
desc string
key string
sort int
}{
{
"get valid key",
"rls-a.v1",
0,
},
{
"get invalid key",
"rls-a.v3",
-1,
},
}
for _, tt := range tests {
got, _ := rs.Index(tt.key)
if got != tt.sort {
t.Fatalf("Expected %d, got %d", tt.sort, got)
}
}
}
func TestRecordsExists(t *testing.T) {
rs := records([]*record{
newRecord("rls-a.v1", releaseStub("rls-a", 1, "default", common.StatusSuperseded)),
newRecord("rls-a.v2", releaseStub("rls-a", 2, "default", common.StatusDeployed)),
})
var tests = []struct {
desc string
key string
ok bool
}{
{
"get valid key",
"rls-a.v1",
true,
},
{
"get invalid key",
"rls-a.v3",
false,
},
}
for _, tt := range tests {
got := rs.Exists(tt.key)
if got != tt.ok {
t.Fatalf("Expected %t, got %t", tt.ok, got)
}
}
}
func TestRecordsReplace(t *testing.T) {
rs := records([]*record{
newRecord("rls-a.v1", releaseStub("rls-a", 1, "default", common.StatusSuperseded)),
newRecord("rls-a.v2", releaseStub("rls-a", 2, "default", common.StatusDeployed)),
})
var tests = []struct {
desc string
key string
rec *record
expected *record
}{
{
"replace with existing key",
"rls-a.v2",
newRecord("rls-a.v3", releaseStub("rls-a", 3, "default", common.StatusSuperseded)),
newRecord("rls-a.v2", releaseStub("rls-a", 2, "default", common.StatusDeployed)),
},
{
"replace with non existing key",
"rls-a.v4",
newRecord("rls-a.v4", releaseStub("rls-a", 4, "default", common.StatusDeployed)),
nil,
},
}
for _, tt := range tests {
got := rs.Replace(tt.key, tt.rec)
if !reflect.DeepEqual(tt.expected, got) {
t.Fatalf("Expected %v, got %v", tt.expected, got)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/secrets_test.go | pkg/storage/driver/secrets_test.go | /*
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 driver
import (
"encoding/base64"
"encoding/json"
"errors"
"reflect"
"testing"
v1 "k8s.io/api/core/v1"
"helm.sh/helm/v4/pkg/release"
"helm.sh/helm/v4/pkg/release/common"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
func TestSecretName(t *testing.T) {
c := newTestFixtureSecrets(t)
if c.Name() != SecretsDriverName {
t.Errorf("Expected name to be %q, got %q", SecretsDriverName, c.Name())
}
}
func TestSecretGet(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
secrets := newTestFixtureSecrets(t, []*rspb.Release{rel}...)
// get release with key
got, err := secrets.Get(key)
if err != nil {
t.Fatalf("Failed to get release: %s", err)
}
// compare fetched release with original
if !reflect.DeepEqual(rel, got) {
t.Errorf("Expected {%v}, got {%v}", rel, got)
}
}
func TestUNcompressedSecretGet(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
// Create a test fixture which contains an uncompressed release
secret, err := newSecretsObject(key, rel, nil)
if err != nil {
t.Fatalf("Failed to create secret: %s", err)
}
b, err := json.Marshal(rel)
if err != nil {
t.Fatalf("Failed to marshal release: %s", err)
}
secret.Data["release"] = []byte(base64.StdEncoding.EncodeToString(b))
var mock MockSecretsInterface
mock.objects = map[string]*v1.Secret{key: secret}
secrets := NewSecrets(&mock)
// get release with key
got, err := secrets.Get(key)
if err != nil {
t.Fatalf("Failed to get release: %s", err)
}
// compare fetched release with original
if !reflect.DeepEqual(rel, got) {
t.Errorf("Expected {%v}, got {%v}", rel, got)
}
}
func TestSecretList(t *testing.T) {
secrets := newTestFixtureSecrets(t, []*rspb.Release{
releaseStub("key-1", 1, "default", common.StatusUninstalled),
releaseStub("key-2", 1, "default", common.StatusUninstalled),
releaseStub("key-3", 1, "default", common.StatusDeployed),
releaseStub("key-4", 1, "default", common.StatusDeployed),
releaseStub("key-5", 1, "default", common.StatusSuperseded),
releaseStub("key-6", 1, "default", common.StatusSuperseded),
}...)
// list all deleted releases
del, err := secrets.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusUninstalled
})
// check
if err != nil {
t.Errorf("Failed to list deleted: %s", err)
}
if len(del) != 2 {
t.Errorf("Expected 2 deleted, got %d:\n%v\n", len(del), del)
}
// list all deployed releases
dpl, err := secrets.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusDeployed
})
// check
if err != nil {
t.Errorf("Failed to list deployed: %s", err)
}
if len(dpl) != 2 {
t.Errorf("Expected 2 deployed, got %d", len(dpl))
}
// list all superseded releases
ssd, err := secrets.List(func(rel release.Releaser) bool {
rls := convertReleaserToV1(t, rel)
return rls.Info.Status == common.StatusSuperseded
})
// check
if err != nil {
t.Errorf("Failed to list superseded: %s", err)
}
if len(ssd) != 2 {
t.Errorf("Expected 2 superseded, got %d", len(ssd))
}
// Check if release having both system and custom labels, this is needed to ensure that selector filtering would work.
rls := convertReleaserToV1(t, ssd[0])
_, ok := rls.Labels["name"]
if !ok {
t.Fatalf("Expected 'name' label in results, actual %v", rls.Labels)
}
_, ok = rls.Labels["key1"]
if !ok {
t.Fatalf("Expected 'key1' label in results, actual %v", rls.Labels)
}
}
func TestSecretQuery(t *testing.T) {
secrets := newTestFixtureSecrets(t, []*rspb.Release{
releaseStub("key-1", 1, "default", common.StatusUninstalled),
releaseStub("key-2", 1, "default", common.StatusUninstalled),
releaseStub("key-3", 1, "default", common.StatusDeployed),
releaseStub("key-4", 1, "default", common.StatusDeployed),
releaseStub("key-5", 1, "default", common.StatusSuperseded),
releaseStub("key-6", 1, "default", common.StatusSuperseded),
}...)
rls, err := secrets.Query(map[string]string{"status": "deployed"})
if err != nil {
t.Fatalf("Failed to query: %s", err)
}
if len(rls) != 2 {
t.Fatalf("Expected 2 results, actual %d", len(rls))
}
_, err = secrets.Query(map[string]string{"name": "notExist"})
if err != ErrReleaseNotFound {
t.Errorf("Expected {%v}, got {%v}", ErrReleaseNotFound, err)
}
}
func TestSecretCreate(t *testing.T) {
secrets := newTestFixtureSecrets(t)
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
// store the release in a secret
if err := secrets.Create(key, rel); err != nil {
t.Fatalf("Failed to create release with key %q: %s", key, err)
}
// get the release back
got, err := secrets.Get(key)
if err != nil {
t.Fatalf("Failed to get release with key %q: %s", key, err)
}
// compare created release with original
if !reflect.DeepEqual(rel, got) {
t.Errorf("Expected {%v}, got {%v}", rel, got)
}
}
func TestSecretUpdate(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
secrets := newTestFixtureSecrets(t, []*rspb.Release{rel}...)
// modify release status code
rel.Info.Status = common.StatusSuperseded
// perform the update
if err := secrets.Update(key, rel); err != nil {
t.Fatalf("Failed to update release: %s", err)
}
// fetch the updated release
goti, err := secrets.Get(key)
if err != nil {
t.Fatalf("Failed to get release with key %q: %s", key, err)
}
got := convertReleaserToV1(t, goti)
// check release has actually been updated by comparing modified fields
if rel.Info.Status != got.Info.Status {
t.Errorf("Expected status %s, got status %s", rel.Info.Status.String(), got.Info.Status.String())
}
}
func TestSecretDelete(t *testing.T) {
vers := 1
name := "smug-pigeon"
namespace := "default"
key := testKey(name, vers)
rel := releaseStub(name, vers, namespace, common.StatusDeployed)
secrets := newTestFixtureSecrets(t, []*rspb.Release{rel}...)
// perform the delete on a non-existing release
_, err := secrets.Delete("nonexistent")
if err != ErrReleaseNotFound {
t.Fatalf("Expected ErrReleaseNotFound, got: {%v}", err)
}
// perform the delete
rls, err := secrets.Delete(key)
if err != nil {
t.Fatalf("Failed to delete release with key %q: %s", key, err)
}
if !reflect.DeepEqual(rel, rls) {
t.Errorf("Expected {%v}, got {%v}", rel, rls)
}
_, err = secrets.Get(key)
if !errors.Is(err, ErrReleaseNotFound) {
t.Errorf("Expected {%v}, got {%v}", ErrReleaseNotFound, err)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/storage/driver/util_test.go | pkg/storage/driver/util_test.go | /*
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 driver
import (
"reflect"
"testing"
)
func TestGetSystemLabel(t *testing.T) {
if output := GetSystemLabels(); !reflect.DeepEqual(systemLabels, output) {
t.Errorf("Expected {%v}, got {%v}", systemLabels, output)
}
}
func TestIsSystemLabel(t *testing.T) {
tests := map[string]bool{
"name": true,
"owner": true,
"test": false,
"NaMe": false,
}
for label, result := range tests {
if output := isSystemLabel(label); output != result {
t.Errorf("Output %t not equal to expected %t", output, result)
}
}
}
func TestFilterSystemLabels(t *testing.T) {
var tests = [][2]map[string]string{
{nil, map[string]string{}},
{map[string]string{}, map[string]string{}},
{map[string]string{
"name": "name",
"owner": "owner",
"status": "status",
"version": "version",
"createdAt": "createdAt",
"modifiedAt": "modifiedAt",
}, map[string]string{}},
{map[string]string{
"StaTus": "status",
"name": "name",
"owner": "owner",
"key": "value",
}, map[string]string{
"StaTus": "status",
"key": "value",
}},
{map[string]string{
"key1": "value1",
"key2": "value2",
}, map[string]string{
"key1": "value1",
"key2": "value2",
}},
}
for _, test := range tests {
if output := filterSystemLabels(test[0]); !reflect.DeepEqual(test[1], output) {
t.Errorf("Expected {%v}, got {%v}", test[1], output)
}
}
}
func TestContainsSystemLabels(t *testing.T) {
var tests = []struct {
input map[string]string
output bool
}{
{nil, false},
{map[string]string{}, false},
{map[string]string{
"name": "name",
"owner": "owner",
"status": "status",
"version": "version",
"createdAt": "createdAt",
"modifiedAt": "modifiedAt",
}, true},
{map[string]string{
"StaTus": "status",
"name": "name",
"owner": "owner",
"key": "value",
}, true},
{map[string]string{
"key1": "value1",
"key2": "value2",
}, false},
}
for _, test := range tests {
if output := ContainsSystemLabels(test.input); !reflect.DeepEqual(test.output, output) {
t.Errorf("Expected {%v}, got {%v}", test.output, output)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/uploader/chart_uploader.go | pkg/uploader/chart_uploader.go | /*
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 uploader
import (
"fmt"
"io"
"net/url"
"helm.sh/helm/v4/pkg/pusher"
"helm.sh/helm/v4/pkg/registry"
)
// ChartUploader handles uploading a chart.
type ChartUploader struct {
// Out is the location to write warning and info messages.
Out io.Writer
// Pusher collection for the operation
Pushers pusher.Providers
// Options provide parameters to be passed along to the Pusher being initialized.
Options []pusher.Option
// RegistryClient is a client for interacting with registries.
RegistryClient *registry.Client
}
// UploadTo uploads a chart. Depending on the settings, it may also upload a provenance file.
func (c *ChartUploader) UploadTo(ref, remote string) error {
u, err := url.Parse(remote)
if err != nil {
return fmt.Errorf("invalid chart URL format: %s", remote)
}
if u.Scheme == "" {
return fmt.Errorf("scheme prefix missing from remote (e.g. \"%s://\")", registry.OCIScheme)
}
p, err := c.Pushers.ByScheme(u.Scheme)
if err != nil {
return err
}
return p.Push(ref, u.String(), c.Options...)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/uploader/doc.go | pkg/uploader/doc.go | /*
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 uploader provides a library for uploading charts.
This package contains tools for uploading charts to registries.
*/
package uploader
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/rollback.go | pkg/cmd/rollback.go | /*
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 (
"fmt"
"io"
"strconv"
"time"
"github.com/spf13/cobra"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cmd/require"
)
const rollbackDesc = `
This command rolls back a release to a previous revision.
The first argument of the rollback command is the name of a release, and the
second is a revision (version) number. If this argument is omitted or set to
0, it will roll back to the previous release.
To see revision numbers, run 'helm history RELEASE'.
`
func newRollbackCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewRollback(cfg)
cmd := &cobra.Command{
Use: "rollback <RELEASE> [REVISION]",
Short: "roll back a release to a previous revision",
Long: rollbackDesc,
Args: require.MinimumNArgs(1),
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return compListReleases(toComplete, args, cfg)
}
if len(args) == 1 {
return compListRevisions(toComplete, cfg, args[0])
}
return noMoreArgsComp()
},
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 1 {
ver, err := strconv.Atoi(args[1])
if err != nil {
return fmt.Errorf("could not convert revision to a number: %v", err)
}
client.Version = ver
}
dryRunStrategy, err := cmdGetDryRunFlagStrategy(cmd, false)
if err != nil {
return err
}
client.DryRunStrategy = dryRunStrategy
if err := client.Run(args[0]); err != nil {
return err
}
fmt.Fprintf(out, "Rollback was a success! Happy Helming!\n")
return nil
},
}
f := cmd.Flags()
f.BoolVar(&client.ForceReplace, "force-replace", false, "force resource updates by replacement")
f.BoolVar(&client.ForceReplace, "force", false, "deprecated")
f.MarkDeprecated("force", "use --force-replace instead")
f.BoolVar(&client.ForceConflicts, "force-conflicts", false, "if set server-side apply will force changes against conflicts")
f.StringVar(&client.ServerSideApply, "server-side", "auto", "must be \"true\", \"false\" or \"auto\". Object updates run in the server instead of the client (\"auto\" defaults the value from the previous chart release's method)")
f.BoolVar(&client.DisableHooks, "no-hooks", false, "prevent hooks from running during rollback")
f.DurationVar(&client.Timeout, "timeout", 300*time.Second, "time to wait for any individual Kubernetes operation (like Jobs for hooks)")
f.BoolVar(&client.WaitForJobs, "wait-for-jobs", false, "if set and --wait enabled, will wait until all Jobs have been completed before marking the release as successful. It will wait for as long as --timeout")
f.BoolVar(&client.CleanupOnFail, "cleanup-on-fail", false, "allow deletion of new resources created in this rollback when rollback fails")
f.IntVar(&client.MaxHistory, "history-max", settings.MaxHistory, "limit the maximum number of revisions saved per release. Use 0 for no limit")
addDryRunFlag(cmd)
AddWaitFlag(cmd, &client.WaitStrategy)
cmd.MarkFlagsMutuallyExclusive("force-replace", "force-conflicts")
cmd.MarkFlagsMutuallyExclusive("force", "force-conflicts")
return cmd
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/flags.go | pkg/cmd/flags.go | /*
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 (
"flag"
"fmt"
"log"
"log/slog"
"path/filepath"
"sort"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"k8s.io/klog/v2"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cli"
"helm.sh/helm/v4/pkg/cli/output"
"helm.sh/helm/v4/pkg/cli/values"
"helm.sh/helm/v4/pkg/helmpath"
"helm.sh/helm/v4/pkg/kube"
"helm.sh/helm/v4/pkg/postrenderer"
"helm.sh/helm/v4/pkg/repo/v1"
)
const (
outputFlag = "output"
postRenderFlag = "post-renderer"
postRenderArgsFlag = "post-renderer-args"
)
func addValueOptionsFlags(f *pflag.FlagSet, v *values.Options) {
f.StringSliceVarP(&v.ValueFiles, "values", "f", []string{}, "specify values in a YAML file or a URL (can specify multiple)")
f.StringArrayVar(&v.Values, "set", []string{}, "set values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)")
f.StringArrayVar(&v.StringValues, "set-string", []string{}, "set STRING values on the command line (can specify multiple or separate values with commas: key1=val1,key2=val2)")
f.StringArrayVar(&v.FileValues, "set-file", []string{}, "set values from respective files specified via the command line (can specify multiple or separate values with commas: key1=path1,key2=path2)")
f.StringArrayVar(&v.JSONValues, "set-json", []string{}, "set JSON values on the command line (can specify multiple or separate values with commas: key1=jsonval1,key2=jsonval2 or using json format: {\"key1\": jsonval1, \"key2\": \"jsonval2\"})")
f.StringArrayVar(&v.LiteralValues, "set-literal", []string{}, "set a literal STRING value on the command line")
}
func AddWaitFlag(cmd *cobra.Command, wait *kube.WaitStrategy) {
cmd.Flags().Var(
newWaitValue(kube.HookOnlyStrategy, wait),
"wait",
"if specified, wait until resources are ready (up to --timeout). Values: 'watcher', 'hookOnly', and 'legacy'.",
)
// Sets the strategy to use the watcher strategy if `--wait` is used without an argument
cmd.Flags().Lookup("wait").NoOptDefVal = string(kube.StatusWatcherStrategy)
}
type waitValue kube.WaitStrategy
func newWaitValue(defaultValue kube.WaitStrategy, ws *kube.WaitStrategy) *waitValue {
*ws = defaultValue
return (*waitValue)(ws)
}
func (ws *waitValue) String() string {
if ws == nil {
return ""
}
return string(*ws)
}
func (ws *waitValue) Set(s string) error {
switch s {
case string(kube.StatusWatcherStrategy), string(kube.LegacyStrategy), string(kube.HookOnlyStrategy):
*ws = waitValue(s)
return nil
case "true":
slog.Warn("--wait=true is deprecated (boolean value) and can be replaced with --wait=watcher")
*ws = waitValue(kube.StatusWatcherStrategy)
return nil
case "false":
slog.Warn("--wait=false is deprecated (boolean value) and can be replaced with --wait=hookOnly")
*ws = waitValue(kube.HookOnlyStrategy)
return nil
default:
return fmt.Errorf("invalid wait input %q. Valid inputs are %s, %s, and %s", s, kube.StatusWatcherStrategy, kube.HookOnlyStrategy, kube.LegacyStrategy)
}
}
func (ws *waitValue) Type() string {
return "WaitStrategy"
}
func addChartPathOptionsFlags(f *pflag.FlagSet, c *action.ChartPathOptions) {
f.StringVar(&c.Version, "version", "", "specify a version constraint for the chart version to use. This constraint can be a specific tag (e.g. 1.1.1) or it may reference a valid range (e.g. ^2.0.0). If this is not specified, the latest version is used")
f.BoolVar(&c.Verify, "verify", false, "verify the package before using it")
f.StringVar(&c.Keyring, "keyring", defaultKeyring(), "location of public keys used for verification")
f.StringVar(&c.RepoURL, "repo", "", "chart repository url where to locate the requested chart")
f.StringVar(&c.Username, "username", "", "chart repository username where to locate the requested chart")
f.StringVar(&c.Password, "password", "", "chart repository password where to locate the requested chart")
f.StringVar(&c.CertFile, "cert-file", "", "identify HTTPS client using this SSL certificate file")
f.StringVar(&c.KeyFile, "key-file", "", "identify HTTPS client using this SSL key file")
f.BoolVar(&c.InsecureSkipTLSVerify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the chart download")
f.BoolVar(&c.PlainHTTP, "plain-http", false, "use insecure HTTP connections for the chart download")
f.StringVar(&c.CaFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle")
f.BoolVar(&c.PassCredentialsAll, "pass-credentials", false, "pass credentials to all domains")
}
// bindOutputFlag will add the output flag to the given command and bind the
// value to the given format pointer
func bindOutputFlag(cmd *cobra.Command, varRef *output.Format) {
cmd.Flags().VarP(newOutputValue(output.Table, varRef), outputFlag, "o",
fmt.Sprintf("prints the output in the specified format. Allowed values: %s", strings.Join(output.Formats(), ", ")))
err := cmd.RegisterFlagCompletionFunc(outputFlag, func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
var formatNames []string
for format, desc := range output.FormatsWithDesc() {
formatNames = append(formatNames, fmt.Sprintf("%s\t%s", format, desc))
}
// Sort the results to get a deterministic order for the tests
sort.Strings(formatNames)
return formatNames, cobra.ShellCompDirectiveNoFileComp
})
if err != nil {
log.Fatal(err)
}
}
type outputValue output.Format
func newOutputValue(defaultValue output.Format, p *output.Format) *outputValue {
*p = defaultValue
return (*outputValue)(p)
}
func (o *outputValue) String() string {
// It is much cleaner looking (and technically less allocations) to just
// convert to a string rather than type asserting to the underlying
// output.Format
return string(*o)
}
func (o *outputValue) Type() string {
return "format"
}
func (o *outputValue) Set(s string) error {
outfmt, err := output.ParseFormat(s)
if err != nil {
return err
}
*o = outputValue(outfmt)
return nil
}
// TODO there is probably a better way to pass cobra settings than as a param
func bindPostRenderFlag(cmd *cobra.Command, varRef *postrenderer.PostRenderer, settings *cli.EnvSettings) {
p := &postRendererOptions{varRef, "", []string{}, settings}
cmd.Flags().Var(&postRendererString{p}, postRenderFlag, "the name of a postrenderer type plugin to be used for post rendering. If it exists, the plugin will be used")
cmd.Flags().Var(&postRendererArgsSlice{p}, postRenderArgsFlag, "an argument to the post-renderer (can specify multiple)")
}
type postRendererOptions struct {
renderer *postrenderer.PostRenderer
pluginName string
args []string
settings *cli.EnvSettings
}
type postRendererString struct {
options *postRendererOptions
}
func (p *postRendererString) String() string {
return p.options.pluginName
}
func (p *postRendererString) Type() string {
return "postRendererString"
}
func (p *postRendererString) Set(val string) error {
if val == "" {
return nil
}
if p.options.pluginName != "" {
return fmt.Errorf("cannot specify --post-renderer flag more than once")
}
p.options.pluginName = val
pr, err := postrenderer.NewPostRendererPlugin(p.options.settings, p.options.pluginName, p.options.args...)
if err != nil {
return err
}
*p.options.renderer = pr
return nil
}
type postRendererArgsSlice struct {
options *postRendererOptions
}
func (p *postRendererArgsSlice) String() string {
return "[" + strings.Join(p.options.args, ",") + "]"
}
func (p *postRendererArgsSlice) Type() string {
return "postRendererArgsSlice"
}
func (p *postRendererArgsSlice) Set(val string) error {
// a post-renderer defined by a user may accept empty arguments
p.options.args = append(p.options.args, val)
if p.options.pluginName == "" {
return nil
}
// overwrite if already create PostRenderer by `post-renderer` flags
pr, err := postrenderer.NewPostRendererPlugin(p.options.settings, p.options.pluginName, p.options.args...)
if err != nil {
return err
}
*p.options.renderer = pr
return nil
}
func (p *postRendererArgsSlice) Append(val string) error {
p.options.args = append(p.options.args, val)
return nil
}
func (p *postRendererArgsSlice) Replace(val []string) error {
p.options.args = val
return nil
}
func (p *postRendererArgsSlice) GetSlice() []string {
return p.options.args
}
func compVersionFlag(chartRef string, _ string) ([]string, cobra.ShellCompDirective) {
chartInfo := strings.Split(chartRef, "/")
if len(chartInfo) != 2 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
repoName := chartInfo[0]
chartName := chartInfo[1]
path := filepath.Join(settings.RepositoryCache, helmpath.CacheIndexFile(repoName))
var versions []string
if indexFile, err := repo.LoadIndexFile(path); err == nil {
for _, details := range indexFile.Entries[chartName] {
appVersion := details.AppVersion
appVersionDesc := ""
if appVersion != "" {
appVersionDesc = fmt.Sprintf("App: %s, ", appVersion)
}
created := details.Created.Format("January 2, 2006")
createdDesc := ""
if created != "" {
createdDesc = fmt.Sprintf("Created: %s ", created)
}
deprecated := ""
if details.Deprecated {
deprecated = "(deprecated)"
}
versions = append(versions, fmt.Sprintf("%s\t%s%s%s", details.Version, appVersionDesc, createdDesc, deprecated))
}
}
return versions, cobra.ShellCompDirectiveNoFileComp
}
// addKlogFlags adds flags from k8s.io/klog
// marks the flags as hidden to avoid polluting the help text
func addKlogFlags(fs *pflag.FlagSet) {
local := flag.NewFlagSet("klog", flag.ExitOnError)
klog.InitFlags(local)
local.VisitAll(func(fl *flag.Flag) {
fl.Name = normalize(fl.Name)
if fs.Lookup(fl.Name) != nil {
return
}
newflag := pflag.PFlagFromGoFlag(fl)
newflag.Hidden = true
fs.AddFlag(newflag)
})
}
// normalize replaces underscores with hyphens
func normalize(s string) string {
return strings.ReplaceAll(s, "_", "-")
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_hooks.go | pkg/cmd/get_hooks.go | /*
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 (
"fmt"
"io"
"log"
"github.com/spf13/cobra"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cmd/require"
"helm.sh/helm/v4/pkg/release"
)
const getHooksHelp = `
This command downloads hooks for a given release.
Hooks are formatted in YAML and separated by the YAML '---\n' separator.
`
func newGetHooksCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewGet(cfg)
cmd := &cobra.Command{
Use: "hooks RELEASE_NAME",
Short: "download all hooks for a named release",
Long: getHooksHelp,
Args: require.ExactArgs(1),
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return noMoreArgsComp()
}
return compListReleases(toComplete, args, cfg)
},
RunE: func(_ *cobra.Command, args []string) error {
res, err := client.Run(args[0])
if err != nil {
return err
}
rac, err := release.NewAccessor(res)
if err != nil {
return err
}
for _, hook := range rac.Hooks() {
hac, err := release.NewHookAccessor(hook)
if err != nil {
return err
}
fmt.Fprintf(out, "---\n# Source: %s\n%s\n", hac.Path(), hac.Manifest())
}
return nil
},
}
cmd.Flags().IntVar(&client.Version, "revision", 0, "get the named release with revision")
err := cmd.RegisterFlagCompletionFunc("revision", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 1 {
return compListRevisions(toComplete, cfg, args[0])
}
return nil, cobra.ShellCompDirectiveNoFileComp
})
if err != nil {
log.Fatal(err)
}
return cmd
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_all.go | pkg/cmd/get_all.go | /*
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 (
"io"
"log"
"github.com/spf13/cobra"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cli/output"
"helm.sh/helm/v4/pkg/cmd/require"
)
var getAllHelp = `
This command prints a human readable collection of information about the
notes, hooks, supplied values, and generated manifest file of the given release.
`
func newGetAllCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
var template string
client := action.NewGet(cfg)
cmd := &cobra.Command{
Use: "all RELEASE_NAME",
Short: "download all information for a named release",
Long: getAllHelp,
Args: require.ExactArgs(1),
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return noMoreArgsComp()
}
return compListReleases(toComplete, args, cfg)
},
RunE: func(_ *cobra.Command, args []string) error {
res, err := client.Run(args[0])
if err != nil {
return err
}
if template != "" {
data := map[string]interface{}{
"Release": res,
}
return tpl(template, data, out)
}
return output.Table.Write(out, &statusPrinter{
release: res,
debug: true,
showMetadata: true,
hideNotes: false,
noColor: settings.ShouldDisableColor(),
})
},
}
f := cmd.Flags()
f.IntVar(&client.Version, "revision", 0, "get the named release with revision")
err := cmd.RegisterFlagCompletionFunc("revision", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 1 {
return compListRevisions(toComplete, cfg, args[0])
}
return nil, cobra.ShellCompDirectiveNoFileComp
})
if err != nil {
log.Fatal(err)
}
f.StringVar(&template, "template", "", "go template for formatting the output, eg: {{.Release.Name}}")
return cmd
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/history_test.go | pkg/cmd/history_test.go | /*
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 (
"encoding/json"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/pkg/release/common"
release "helm.sh/helm/v4/pkg/release/v1"
)
func TestHistoryCmd(t *testing.T) {
mk := func(name string, vers int, status common.Status) *release.Release {
return release.Mock(&release.MockReleaseOptions{
Name: name,
Version: vers,
Status: status,
})
}
tests := []cmdTestCase{{
name: "get history for release",
cmd: "history angry-bird",
rels: []*release.Release{
mk("angry-bird", 4, common.StatusDeployed),
mk("angry-bird", 3, common.StatusSuperseded),
mk("angry-bird", 2, common.StatusSuperseded),
mk("angry-bird", 1, common.StatusSuperseded),
},
golden: "output/history.txt",
}, {
name: "get history with max limit set",
cmd: "history angry-bird --max 2",
rels: []*release.Release{
mk("angry-bird", 4, common.StatusDeployed),
mk("angry-bird", 3, common.StatusSuperseded),
},
golden: "output/history-limit.txt",
}, {
name: "get history with yaml output format",
cmd: "history angry-bird --output yaml",
rels: []*release.Release{
mk("angry-bird", 4, common.StatusDeployed),
mk("angry-bird", 3, common.StatusSuperseded),
},
golden: "output/history.yaml",
}, {
name: "get history with json output format",
cmd: "history angry-bird --output json",
rels: []*release.Release{
mk("angry-bird", 4, common.StatusDeployed),
mk("angry-bird", 3, common.StatusSuperseded),
},
golden: "output/history.json",
}}
runTestCmd(t, tests)
}
func TestHistoryOutputCompletion(t *testing.T) {
outputFlagCompletionTest(t, "history")
}
func revisionFlagCompletionTest(t *testing.T, cmdName string) {
t.Helper()
mk := func(name string, vers int, status common.Status) *release.Release {
return release.Mock(&release.MockReleaseOptions{
Name: name,
Version: vers,
Status: status,
})
}
releases := []*release.Release{
mk("musketeers", 11, common.StatusDeployed),
mk("musketeers", 10, common.StatusSuperseded),
mk("musketeers", 9, common.StatusSuperseded),
mk("musketeers", 8, common.StatusSuperseded),
}
tests := []cmdTestCase{{
name: "completion for revision flag",
cmd: fmt.Sprintf("__complete %s musketeers --revision ''", cmdName),
rels: releases,
golden: "output/revision-comp.txt",
}, {
name: "completion for revision flag, no filter",
cmd: fmt.Sprintf("__complete %s musketeers --revision 1", cmdName),
rels: releases,
golden: "output/revision-comp.txt",
}, {
name: "completion for revision flag with too few args",
cmd: fmt.Sprintf("__complete %s --revision ''", cmdName),
rels: releases,
golden: "output/revision-wrong-args-comp.txt",
}, {
name: "completion for revision flag with too many args",
cmd: fmt.Sprintf("__complete %s three musketeers --revision ''", cmdName),
rels: releases,
golden: "output/revision-wrong-args-comp.txt",
}}
runTestCmd(t, tests)
}
func TestHistoryCompletion(t *testing.T) {
checkReleaseCompletion(t, "history", false)
}
func TestHistoryFileCompletion(t *testing.T) {
checkFileCompletion(t, "history", false)
checkFileCompletion(t, "history myrelease", false)
}
func TestReleaseInfoMarshalJSON(t *testing.T) {
updated := time.Date(2025, 10, 8, 12, 0, 0, 0, time.UTC)
tests := []struct {
name string
info releaseInfo
expected string
}{
{
name: "all fields populated",
info: releaseInfo{
Revision: 1,
Updated: updated,
Status: "deployed",
Chart: "mychart-1.0.0",
AppVersion: "1.0.0",
Description: "Initial install",
},
expected: `{"revision":1,"updated":"2025-10-08T12:00:00Z","status":"deployed","chart":"mychart-1.0.0","app_version":"1.0.0","description":"Initial install"}`,
},
{
name: "without updated time",
info: releaseInfo{
Revision: 2,
Status: "superseded",
Chart: "mychart-1.0.1",
AppVersion: "1.0.1",
Description: "Upgraded",
},
expected: `{"revision":2,"status":"superseded","chart":"mychart-1.0.1","app_version":"1.0.1","description":"Upgraded"}`,
},
{
name: "with zero revision",
info: releaseInfo{
Revision: 0,
Updated: updated,
Status: "failed",
Chart: "mychart-1.0.0",
AppVersion: "1.0.0",
Description: "Install failed",
},
expected: `{"revision":0,"updated":"2025-10-08T12:00:00Z","status":"failed","chart":"mychart-1.0.0","app_version":"1.0.0","description":"Install failed"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
data, err := json.Marshal(&tt.info)
require.NoError(t, err)
assert.JSONEq(t, tt.expected, string(data))
})
}
}
func TestReleaseInfoUnmarshalJSON(t *testing.T) {
updated := time.Date(2025, 10, 8, 12, 0, 0, 0, time.UTC)
tests := []struct {
name string
input string
expected releaseInfo
wantErr bool
}{
{
name: "all fields populated",
input: `{"revision":1,"updated":"2025-10-08T12:00:00Z","status":"deployed","chart":"mychart-1.0.0","app_version":"1.0.0","description":"Initial install"}`,
expected: releaseInfo{
Revision: 1,
Updated: updated,
Status: "deployed",
Chart: "mychart-1.0.0",
AppVersion: "1.0.0",
Description: "Initial install",
},
},
{
name: "empty string updated field",
input: `{"revision":2,"updated":"","status":"superseded","chart":"mychart-1.0.1","app_version":"1.0.1","description":"Upgraded"}`,
expected: releaseInfo{
Revision: 2,
Status: "superseded",
Chart: "mychart-1.0.1",
AppVersion: "1.0.1",
Description: "Upgraded",
},
},
{
name: "missing updated field",
input: `{"revision":3,"status":"deployed","chart":"mychart-1.0.2","app_version":"1.0.2","description":"Upgraded"}`,
expected: releaseInfo{
Revision: 3,
Status: "deployed",
Chart: "mychart-1.0.2",
AppVersion: "1.0.2",
Description: "Upgraded",
},
},
{
name: "null updated field",
input: `{"revision":4,"updated":null,"status":"failed","chart":"mychart-1.0.3","app_version":"1.0.3","description":"Failed"}`,
expected: releaseInfo{
Revision: 4,
Status: "failed",
Chart: "mychart-1.0.3",
AppVersion: "1.0.3",
Description: "Failed",
},
},
{
name: "invalid time format",
input: `{"revision":5,"updated":"invalid-time","status":"deployed","chart":"mychart-1.0.4","app_version":"1.0.4","description":"Test"}`,
wantErr: true,
},
{
name: "zero revision",
input: `{"revision":0,"updated":"2025-10-08T12:00:00Z","status":"pending-install","chart":"mychart-1.0.0","app_version":"1.0.0","description":"Installing"}`,
expected: releaseInfo{
Revision: 0,
Updated: updated,
Status: "pending-install",
Chart: "mychart-1.0.0",
AppVersion: "1.0.0",
Description: "Installing",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var info releaseInfo
err := json.Unmarshal([]byte(tt.input), &info)
if tt.wantErr {
assert.Error(t, err)
return
}
require.NoError(t, err)
assert.Equal(t, tt.expected.Revision, info.Revision)
assert.Equal(t, tt.expected.Updated.Unix(), info.Updated.Unix())
assert.Equal(t, tt.expected.Status, info.Status)
assert.Equal(t, tt.expected.Chart, info.Chart)
assert.Equal(t, tt.expected.AppVersion, info.AppVersion)
assert.Equal(t, tt.expected.Description, info.Description)
})
}
}
func TestReleaseInfoRoundTrip(t *testing.T) {
updated := time.Date(2025, 10, 8, 12, 0, 0, 0, time.UTC)
original := releaseInfo{
Revision: 1,
Updated: updated,
Status: "deployed",
Chart: "mychart-1.0.0",
AppVersion: "1.0.0",
Description: "Initial install",
}
data, err := json.Marshal(&original)
require.NoError(t, err)
var decoded releaseInfo
err = json.Unmarshal(data, &decoded)
require.NoError(t, err)
assert.Equal(t, original.Revision, decoded.Revision)
assert.Equal(t, original.Updated.Unix(), decoded.Updated.Unix())
assert.Equal(t, original.Status, decoded.Status)
assert.Equal(t, original.Chart, decoded.Chart)
assert.Equal(t, original.AppVersion, decoded.AppVersion)
assert.Equal(t, original.Description, decoded.Description)
}
func TestReleaseInfoEmptyStringRoundTrip(t *testing.T) {
// This test specifically verifies that empty string time fields
// are handled correctly during parsing
input := `{"revision":1,"updated":"","status":"deployed","chart":"mychart-1.0.0","app_version":"1.0.0","description":"Test"}`
var info releaseInfo
err := json.Unmarshal([]byte(input), &info)
require.NoError(t, err)
// Verify time field is zero value
assert.True(t, info.Updated.IsZero())
assert.Equal(t, 1, info.Revision)
assert.Equal(t, "deployed", info.Status)
// Marshal back and verify empty time field is omitted
data, err := json.Marshal(&info)
require.NoError(t, err)
var result map[string]interface{}
err = json.Unmarshal(data, &result)
require.NoError(t, err)
// Zero time value should be omitted
assert.NotContains(t, result, "updated")
assert.Equal(t, float64(1), result["revision"])
assert.Equal(t, "deployed", result["status"])
assert.Equal(t, "mychart-1.0.0", result["chart"])
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/push_test.go | pkg/cmd/push_test.go | /*
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 (
"testing"
)
func TestPushFileCompletion(t *testing.T) {
checkFileCompletion(t, "push", true)
checkFileCompletion(t, "push package.tgz", false)
checkFileCompletion(t, "push package.tgz oci://localhost:5000", false)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/dependency_build_test.go | pkg/cmd/dependency_build_test.go | /*
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 (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/provenance"
"helm.sh/helm/v4/pkg/repo/v1"
"helm.sh/helm/v4/pkg/repo/v1/repotest"
)
func TestDependencyBuildCmd(t *testing.T) {
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/testcharts/*.tgz"),
)
defer srv.Stop()
rootDir := srv.Root()
srv.LinkIndices()
ociSrv, err := repotest.NewOCIServer(t, srv.Root())
if err != nil {
t.Fatal(err)
}
ociChartName := "oci-depending-chart"
c := createTestingMetadataForOCI(ociChartName, ociSrv.RegistryURL)
if _, err := chartutil.Save(c, ociSrv.Dir); err != nil {
t.Fatal(err)
}
ociSrv.Run(t, repotest.WithDependingChart(c))
dir := func(p ...string) string {
return filepath.Join(append([]string{srv.Root()}, p...)...)
}
chartname := "depbuild"
createTestingChart(t, rootDir, chartname, srv.URL())
repoFile := filepath.Join(rootDir, "repositories.yaml")
cmd := fmt.Sprintf("dependency build '%s' --repository-config %s --repository-cache %s --plain-http", filepath.Join(rootDir, chartname), repoFile, rootDir)
_, out, err := executeActionCommand(cmd)
// In the first pass, we basically want the same results as an update.
if err != nil {
t.Logf("Output: %s", out)
t.Fatal(err)
}
if !strings.Contains(out, `update from the "test" chart repository`) {
t.Errorf("Repo did not get updated\n%s", out)
}
// Make sure the actual file got downloaded.
expect := filepath.Join(rootDir, chartname, "charts/reqtest-0.1.0.tgz")
if _, err := os.Stat(expect); err != nil {
t.Fatal(err)
}
// In the second pass, we want to remove the chart's request dependency,
// then see if it restores from the lock.
lockfile := filepath.Join(rootDir, chartname, "Chart.lock")
if _, err := os.Stat(lockfile); err != nil {
t.Fatal(err)
}
if err := os.RemoveAll(expect); err != nil {
t.Fatal(err)
}
_, out, err = executeActionCommand(cmd)
if err != nil {
t.Logf("Output: %s", out)
t.Fatal(err)
}
// Now repeat the test that the dependency exists.
if _, err := os.Stat(expect); err != nil {
t.Fatal(err)
}
// Make sure that build is also fetching the correct version.
hash, err := provenance.DigestFile(expect)
if err != nil {
t.Fatal(err)
}
i, err := repo.LoadIndexFile(filepath.Join(rootDir, "index.yaml"))
if err != nil {
t.Fatal(err)
}
reqver := i.Entries["reqtest"][0]
if h := reqver.Digest; h != hash {
t.Errorf("Failed hash match: expected %s, got %s", hash, h)
}
if v := reqver.Version; v != "0.1.0" {
t.Errorf("mismatched versions. Expected %q, got %q", "0.1.0", v)
}
skipRefreshCmd := fmt.Sprintf("dependency build '%s' --skip-refresh --repository-config %s --repository-cache %s --plain-http", filepath.Join(rootDir, chartname), repoFile, rootDir)
_, out, err = executeActionCommand(skipRefreshCmd)
// In this pass, we check --skip-refresh option becomes effective.
if err != nil {
t.Logf("Output: %s", out)
t.Fatal(err)
}
if strings.Contains(out, `update from the "test" chart repository`) {
t.Errorf("Repo did get updated\n%s", out)
}
// OCI dependencies
if err := chartutil.SaveDir(c, dir()); err != nil {
t.Fatal(err)
}
cmd = fmt.Sprintf("dependency build '%s' --repository-config %s --repository-cache %s --registry-config %s/config.json --plain-http",
dir(ociChartName),
dir("repositories.yaml"),
dir(),
dir())
_, out, err = executeActionCommand(cmd)
if err != nil {
t.Logf("Output: %s", out)
t.Fatal(err)
}
expect = dir(ociChartName, "charts/oci-dependent-chart-0.1.0.tgz")
if _, err := os.Stat(expect); err != nil {
t.Fatal(err)
}
}
func TestDependencyBuildCmdWithHelmV2Hash(t *testing.T) {
chartName := "testdata/testcharts/issue-7233"
cmd := fmt.Sprintf("dependency build '%s'", chartName)
_, out, err := executeActionCommand(cmd)
// Want to make sure the build can verify Helm v2 hash
if err != nil {
t.Logf("Output: %s", out)
t.Fatal(err)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_index.go | pkg/cmd/repo_index.go | /*
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 (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"github.com/spf13/cobra"
"helm.sh/helm/v4/pkg/cmd/require"
"helm.sh/helm/v4/pkg/repo/v1"
)
const repoIndexDesc = `
Read the current directory, generate an index file based on the charts found
and write the result to 'index.yaml' in the current directory.
This tool is used for creating an 'index.yaml' file for a chart repository. To
set an absolute URL to the charts, use '--url' flag.
To merge the generated index with an existing index file, use the '--merge'
flag. In this case, the charts found in the current directory will be merged
into the index passed in with --merge, with local charts taking priority over
existing charts.
`
type repoIndexOptions struct {
dir string
url string
merge string
json bool
}
func newRepoIndexCmd(out io.Writer) *cobra.Command {
o := &repoIndexOptions{}
cmd := &cobra.Command{
Use: "index [DIR]",
Short: "generate an index file given a directory containing packaged charts",
Long: repoIndexDesc,
Args: require.ExactArgs(1),
ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
// Allow file completion when completing the argument for the directory
return nil, cobra.ShellCompDirectiveDefault
}
// No more completions, so disable file completion
return noMoreArgsComp()
},
RunE: func(_ *cobra.Command, args []string) error {
o.dir = args[0]
return o.run(out)
},
}
f := cmd.Flags()
f.StringVar(&o.url, "url", "", "url of chart repository")
f.StringVar(&o.merge, "merge", "", "merge the generated index into the given index")
f.BoolVar(&o.json, "json", false, "output in JSON format")
return cmd
}
func (i *repoIndexOptions) run(_ io.Writer) error {
path, err := filepath.Abs(i.dir)
if err != nil {
return err
}
return index(path, i.url, i.merge, i.json)
}
func index(dir, url, mergeTo string, json bool) error {
out := filepath.Join(dir, "index.yaml")
i, err := repo.IndexDirectory(dir, url)
if err != nil {
return err
}
if mergeTo != "" {
// if index.yaml is missing then create an empty one to merge into
var i2 *repo.IndexFile
if _, err := os.Stat(mergeTo); errors.Is(err, fs.ErrNotExist) {
i2 = repo.NewIndexFile()
writeIndexFile(i2, mergeTo, json)
} else {
i2, err = repo.LoadIndexFile(mergeTo)
if err != nil {
return fmt.Errorf("merge failed: %w", err)
}
}
i.Merge(i2)
}
i.SortEntries()
return writeIndexFile(i, out, json)
}
func writeIndexFile(i *repo.IndexFile, out string, json bool) error {
if json {
return i.WriteJSONFile(out, 0o644)
}
return i.WriteFile(out, 0o644)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/show.go | pkg/cmd/show.go | /*
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 (
"fmt"
"io"
"log"
"log/slog"
"github.com/spf13/cobra"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cmd/require"
)
const showDesc = `
This command consists of multiple subcommands to display information about a chart
`
const showAllDesc = `
This command inspects a chart (directory, file, or URL) and displays all its content
(values.yaml, Chart.yaml, README)
`
const showValuesDesc = `
This command inspects a chart (directory, file, or URL) and displays the contents
of the values.yaml file
`
const showChartDesc = `
This command inspects a chart (directory, file, or URL) and displays the contents
of the Chart.yaml file
`
const readmeChartDesc = `
This command inspects a chart (directory, file, or URL) and displays the contents
of the README file
`
const showCRDsDesc = `
This command inspects a chart (directory, file, or URL) and displays the contents
of the CustomResourceDefinition files
`
func newShowCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewShow(action.ShowAll, cfg)
showCommand := &cobra.Command{
Use: "show",
Short: "show information of a chart",
Aliases: []string{"inspect"},
Long: showDesc,
Args: require.NoArgs,
}
// Function providing dynamic auto-completion
validArgsFunc := func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return noMoreArgsComp()
}
return compListCharts(toComplete, true)
}
all := &cobra.Command{
Use: "all [CHART]",
Short: "show all information of the chart",
Long: showAllDesc,
Args: require.ExactArgs(1),
ValidArgsFunction: validArgsFunc,
RunE: func(_ *cobra.Command, args []string) error {
client.OutputFormat = action.ShowAll
err := addRegistryClient(client)
if err != nil {
return err
}
output, err := runShow(args, client)
if err != nil {
return err
}
fmt.Fprint(out, output)
return nil
},
}
valuesSubCmd := &cobra.Command{
Use: "values [CHART]",
Short: "show the chart's values",
Long: showValuesDesc,
Args: require.ExactArgs(1),
ValidArgsFunction: validArgsFunc,
RunE: func(_ *cobra.Command, args []string) error {
client.OutputFormat = action.ShowValues
err := addRegistryClient(client)
if err != nil {
return err
}
output, err := runShow(args, client)
if err != nil {
return err
}
fmt.Fprint(out, output)
return nil
},
}
chartSubCmd := &cobra.Command{
Use: "chart [CHART]",
Short: "show the chart's definition",
Long: showChartDesc,
Args: require.ExactArgs(1),
ValidArgsFunction: validArgsFunc,
RunE: func(_ *cobra.Command, args []string) error {
client.OutputFormat = action.ShowChart
err := addRegistryClient(client)
if err != nil {
return err
}
output, err := runShow(args, client)
if err != nil {
return err
}
fmt.Fprint(out, output)
return nil
},
}
readmeSubCmd := &cobra.Command{
Use: "readme [CHART]",
Short: "show the chart's README",
Long: readmeChartDesc,
Args: require.ExactArgs(1),
ValidArgsFunction: validArgsFunc,
RunE: func(_ *cobra.Command, args []string) error {
client.OutputFormat = action.ShowReadme
err := addRegistryClient(client)
if err != nil {
return err
}
output, err := runShow(args, client)
if err != nil {
return err
}
fmt.Fprint(out, output)
return nil
},
}
crdsSubCmd := &cobra.Command{
Use: "crds [CHART]",
Short: "show the chart's CRDs",
Long: showCRDsDesc,
Args: require.ExactArgs(1),
ValidArgsFunction: validArgsFunc,
RunE: func(_ *cobra.Command, args []string) error {
client.OutputFormat = action.ShowCRDs
err := addRegistryClient(client)
if err != nil {
return err
}
output, err := runShow(args, client)
if err != nil {
return err
}
fmt.Fprint(out, output)
return nil
},
}
cmds := []*cobra.Command{all, readmeSubCmd, valuesSubCmd, chartSubCmd, crdsSubCmd}
for _, subCmd := range cmds {
addShowFlags(subCmd, client)
showCommand.AddCommand(subCmd)
}
return showCommand
}
func addShowFlags(subCmd *cobra.Command, client *action.Show) {
f := subCmd.Flags()
f.BoolVar(&client.Devel, "devel", false, "use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is ignored")
if subCmd.Name() == "values" {
f.StringVar(&client.JSONPathTemplate, "jsonpath", "", "supply a JSONPath expression to filter the output")
}
addChartPathOptionsFlags(f, &client.ChartPathOptions)
err := subCmd.RegisterFlagCompletionFunc("version", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 1 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compVersionFlag(args[0], toComplete)
})
if err != nil {
log.Fatal(err)
}
}
func runShow(args []string, client *action.Show) (string, error) {
slog.Debug("original chart version", "version", client.Version)
if client.Version == "" && client.Devel {
slog.Debug("setting version to >0.0.0-0")
client.Version = ">0.0.0-0"
}
cp, err := client.LocateChart(args[0], settings)
if err != nil {
return "", err
}
return client.Run(cp)
}
func addRegistryClient(client *action.Show) error {
registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile,
client.InsecureSkipTLSVerify, client.PlainHTTP, client.Username, client.Password)
if err != nil {
return fmt.Errorf("missing registry client: %w", err)
}
client.SetRegistryClient(registryClient)
return nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_metadata.go | pkg/cmd/get_metadata.go | /*
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 (
"fmt"
"io"
"log"
"github.com/spf13/cobra"
k8sLabels "k8s.io/apimachinery/pkg/labels"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cli/output"
"helm.sh/helm/v4/pkg/cmd/require"
release "helm.sh/helm/v4/pkg/release/v1"
)
type metadataWriter struct {
metadata *action.Metadata
}
func newGetMetadataCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
var outfmt output.Format
client := action.NewGetMetadata(cfg)
cmd := &cobra.Command{
Use: "metadata RELEASE_NAME",
Short: "This command fetches metadata for a given release",
Args: require.ExactArgs(1),
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return noMoreArgsComp()
}
return compListReleases(toComplete, args, cfg)
},
RunE: func(_ *cobra.Command, args []string) error {
releaseMetadata, err := client.Run(args[0])
if err != nil {
return err
}
return outfmt.Write(out, &metadataWriter{releaseMetadata})
},
}
f := cmd.Flags()
f.IntVar(&client.Version, "revision", 0, "specify release revision")
err := cmd.RegisterFlagCompletionFunc("revision", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 1 {
return compListRevisions(toComplete, cfg, args[0])
}
return nil, cobra.ShellCompDirectiveNoFileComp
})
if err != nil {
log.Fatal(err)
}
bindOutputFlag(cmd, &outfmt)
return cmd
}
func (w metadataWriter) WriteTable(out io.Writer) error {
formatApplyMethod := func(applyMethod string) string {
switch applyMethod {
case "":
return "client-side apply (defaulted)"
case string(release.ApplyMethodClientSideApply):
return "client-side apply"
case string(release.ApplyMethodServerSideApply):
return "server-side apply"
default:
return fmt.Sprintf("unknown (%q)", applyMethod)
}
}
_, _ = fmt.Fprintf(out, "NAME: %v\n", w.metadata.Name)
_, _ = fmt.Fprintf(out, "CHART: %v\n", w.metadata.Chart)
_, _ = fmt.Fprintf(out, "VERSION: %v\n", w.metadata.Version)
_, _ = fmt.Fprintf(out, "APP_VERSION: %v\n", w.metadata.AppVersion)
_, _ = fmt.Fprintf(out, "ANNOTATIONS: %v\n", k8sLabels.Set(w.metadata.Annotations).String())
_, _ = fmt.Fprintf(out, "LABELS: %v\n", k8sLabels.Set(w.metadata.Labels).String())
_, _ = fmt.Fprintf(out, "DEPENDENCIES: %v\n", w.metadata.FormattedDepNames())
_, _ = fmt.Fprintf(out, "NAMESPACE: %v\n", w.metadata.Namespace)
_, _ = fmt.Fprintf(out, "REVISION: %v\n", w.metadata.Revision)
_, _ = fmt.Fprintf(out, "STATUS: %v\n", w.metadata.Status)
_, _ = fmt.Fprintf(out, "DEPLOYED_AT: %v\n", w.metadata.DeployedAt)
_, _ = fmt.Fprintf(out, "APPLY_METHOD: %v\n", formatApplyMethod(w.metadata.ApplyMethod))
return nil
}
func (w metadataWriter) WriteJSON(out io.Writer) error {
return output.EncodeJSON(out, w.metadata)
}
func (w metadataWriter) WriteYAML(out io.Writer) error {
return output.EncodeYAML(out, w.metadata)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/verify.go | pkg/cmd/verify.go | /*
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 (
"fmt"
"io"
"github.com/spf13/cobra"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cmd/require"
)
const verifyDesc = `
Verify that the given chart has a valid provenance file.
Provenance files provide cryptographic verification that a chart has not been
tampered with, and was packaged by a trusted provider.
This command can be used to verify a local chart. Several other commands provide
'--verify' flags that run the same validation. To generate a signed package, use
the 'helm package --sign' command.
`
func newVerifyCmd(out io.Writer) *cobra.Command {
client := action.NewVerify()
cmd := &cobra.Command{
Use: "verify PATH",
Short: "verify that a chart at the given path has been signed and is valid",
Long: verifyDesc,
Args: require.ExactArgs(1),
ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
// Allow file completion when completing the argument for the path
return nil, cobra.ShellCompDirectiveDefault
}
// No more completions, so disable file completion
return noMoreArgsComp()
},
RunE: func(_ *cobra.Command, args []string) error {
result, err := client.Run(args[0])
if err != nil {
return err
}
fmt.Fprint(out, result)
return nil
},
}
cmd.Flags().StringVar(&client.Keyring, "keyring", defaultKeyring(), "keyring containing public keys")
return cmd
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/root.go | pkg/cmd/root.go | /*
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 "helm.sh/helm/v4/pkg/cmd"
import (
"context"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"os"
"strings"
"github.com/fatih/color"
"github.com/spf13/cobra"
"sigs.k8s.io/yaml"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
"helm.sh/helm/v4/internal/logging"
"helm.sh/helm/v4/internal/tlsutil"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cli"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
"helm.sh/helm/v4/pkg/registry"
ri "helm.sh/helm/v4/pkg/release"
release "helm.sh/helm/v4/pkg/release/v1"
"helm.sh/helm/v4/pkg/repo/v1"
"helm.sh/helm/v4/pkg/storage/driver"
)
var globalUsage = `The Kubernetes package manager
Common actions for Helm:
- helm search: search for charts
- helm pull: download a chart to your local directory to view
- helm install: upload the chart to Kubernetes
- helm list: list releases of charts
Environment variables:
| Name | Description |
|------------------------------------|------------------------------------------------------------------------------------------------------------|
| $HELM_CACHE_HOME | set an alternative location for storing cached files. |
| $HELM_CONFIG_HOME | set an alternative location for storing Helm configuration. |
| $HELM_DATA_HOME | set an alternative location for storing Helm data. |
| $HELM_DEBUG | indicate whether or not Helm is running in Debug mode |
| $HELM_DRIVER | set the backend storage driver. Values are: configmap, secret, memory, sql. |
| $HELM_DRIVER_SQL_CONNECTION_STRING | set the connection string the SQL storage driver should use. |
| $HELM_MAX_HISTORY | set the maximum number of helm release history. |
| $HELM_NAMESPACE | set the namespace used for the helm operations. |
| $HELM_NO_PLUGINS | disable plugins. Set HELM_NO_PLUGINS=1 to disable plugins. |
| $HELM_PLUGINS | set the path to the plugins directory |
| $HELM_REGISTRY_CONFIG | set the path to the registry config file. |
| $HELM_REPOSITORY_CACHE | set the path to the repository cache directory |
| $HELM_REPOSITORY_CONFIG | set the path to the repositories file. |
| $KUBECONFIG | set an alternative Kubernetes configuration file (default "~/.kube/config") |
| $HELM_KUBEAPISERVER | set the Kubernetes API Server Endpoint for authentication |
| $HELM_KUBECAFILE | set the Kubernetes certificate authority file. |
| $HELM_KUBEASGROUPS | set the Groups to use for impersonation using a comma-separated list. |
| $HELM_KUBEASUSER | set the Username to impersonate for the operation. |
| $HELM_KUBECONTEXT | set the name of the kubeconfig context. |
| $HELM_KUBETOKEN | set the Bearer KubeToken used for authentication. |
| $HELM_KUBEINSECURE_SKIP_TLS_VERIFY | indicate if the Kubernetes API server's certificate validation should be skipped (insecure) |
| $HELM_KUBETLS_SERVER_NAME | set the server name used to validate the Kubernetes API server certificate |
| $HELM_BURST_LIMIT | set the default burst limit in the case the server contains many CRDs (default 100, -1 to disable) |
| $HELM_QPS | set the Queries Per Second in cases where a high number of calls exceed the option for higher burst values |
| $HELM_COLOR | set color output mode. Allowed values: never, always, auto (default: never) |
| $NO_COLOR | set to any non-empty value to disable all colored output (overrides $HELM_COLOR) |
Helm stores cache, configuration, and data based on the following configuration order:
- If a HELM_*_HOME environment variable is set, it will be used
- Otherwise, on systems supporting the XDG base directory specification, the XDG variables will be used
- When no other location is set a default location will be used based on the operating system
By default, the default directories depend on the Operating System. The defaults are listed below:
| Operating System | Cache Path | Configuration Path | Data Path |
|------------------|---------------------------|--------------------------------|-------------------------|
| Linux | $HOME/.cache/helm | $HOME/.config/helm | $HOME/.local/share/helm |
| macOS | $HOME/Library/Caches/helm | $HOME/Library/Preferences/helm | $HOME/Library/helm |
| Windows | %TEMP%\helm | %APPDATA%\helm | %APPDATA%\helm |
`
var settings = cli.New()
func NewRootCmd(out io.Writer, args []string, logSetup func(bool)) (*cobra.Command, error) {
actionConfig := action.NewConfiguration()
cmd, err := newRootCmdWithConfig(actionConfig, out, args, logSetup)
if err != nil {
return nil, err
}
cobra.OnInitialize(func() {
helmDriver := os.Getenv("HELM_DRIVER")
if err := actionConfig.Init(settings.RESTClientGetter(), settings.Namespace(), helmDriver); err != nil {
log.Fatal(err)
}
if helmDriver == "memory" {
loadReleasesInMemory(actionConfig)
}
actionConfig.SetHookOutputFunc(hookOutputWriter)
})
return cmd, nil
}
// SetupLogging sets up Helm logging used by the Helm client.
// This function is passed to the NewRootCmd function to enable logging. Any other
// application that uses the NewRootCmd function to setup all the Helm commands may
// use this function to setup logging or their own. Using a custom logging setup function
// enables applications using Helm commands to integrate with their existing logging
// system.
// The debug argument is the value if Helm is set for debugging (i.e. --debug flag)
func SetupLogging(debug bool) {
logger := logging.NewLogger(func() bool { return debug })
slog.SetDefault(logger)
}
// configureColorOutput configures the color output based on the ColorMode setting
func configureColorOutput(settings *cli.EnvSettings) {
switch settings.ColorMode {
case "never":
color.NoColor = true
case "always":
color.NoColor = false
case "auto":
// Let fatih/color handle automatic detection
// It will check if output is a terminal and NO_COLOR env var
// We don't need to do anything here
}
}
func newRootCmdWithConfig(actionConfig *action.Configuration, out io.Writer, args []string, logSetup func(bool)) (*cobra.Command, error) {
cmd := &cobra.Command{
Use: "helm",
Short: "The Helm package manager for Kubernetes.",
Long: globalUsage,
SilenceUsage: true,
PersistentPreRun: func(_ *cobra.Command, _ []string) {
if err := startProfiling(); err != nil {
log.Printf("Warning: Failed to start profiling: %v", err)
}
},
PersistentPostRun: func(_ *cobra.Command, _ []string) {
if err := stopProfiling(); err != nil {
log.Printf("Warning: Failed to stop profiling: %v", err)
}
},
}
flags := cmd.PersistentFlags()
settings.AddFlags(flags)
addKlogFlags(flags)
// We can safely ignore any errors that flags.Parse encounters since
// those errors will be caught later during the call to cmd.Execution.
// This call is required to gather configuration information prior to
// execution.
flags.ParseErrorsAllowlist.UnknownFlags = true
flags.Parse(args)
logSetup(settings.Debug)
// newRootCmdWithConfig is only called from NewRootCmd. NewRootCmd sets up
// NewConfiguration without a custom logger. So, the slog default is used. logSetup
// can change the default logger to the one in the logger package. This happens for
// the Helm client. This means the actionConfig logger is different from the slog
// default logger. If they are different we sync the actionConfig logger to the slog
// current default one.
if actionConfig.Logger() != slog.Default() {
actionConfig.SetLogger(slog.Default().Handler())
}
// Validate color mode setting
switch settings.ColorMode {
case "never", "auto", "always":
// Valid color mode
default:
return nil, fmt.Errorf("invalid color mode %q: must be one of: never, auto, always", settings.ColorMode)
}
// Configure color output based on ColorMode setting
configureColorOutput(settings)
// Setup shell completion for the color flag
_ = cmd.RegisterFlagCompletionFunc("color", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{"never", "auto", "always"}, cobra.ShellCompDirectiveNoFileComp
})
// Setup shell completion for the colour flag
_ = cmd.RegisterFlagCompletionFunc("colour", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{"never", "auto", "always"}, cobra.ShellCompDirectiveNoFileComp
})
// Setup shell completion for the namespace flag
err := cmd.RegisterFlagCompletionFunc("namespace", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
if client, err := actionConfig.KubernetesClientSet(); err == nil {
// Choose a long enough timeout that the user notices something is not working
// but short enough that the user is not made to wait very long
to := int64(3)
cobra.CompDebugln(fmt.Sprintf("About to call kube client for namespaces with timeout of: %d", to), settings.Debug)
nsNames := []string{}
if namespaces, err := client.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{TimeoutSeconds: &to}); err == nil {
for _, ns := range namespaces.Items {
nsNames = append(nsNames, ns.Name)
}
return nsNames, cobra.ShellCompDirectiveNoFileComp
}
}
return nil, cobra.ShellCompDirectiveDefault
})
if err != nil {
log.Fatal(err)
}
// Setup shell completion for the kube-context flag
err = cmd.RegisterFlagCompletionFunc("kube-context", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
cobra.CompDebugln("About to get the different kube-contexts", settings.Debug)
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
if len(settings.KubeConfig) > 0 {
loadingRules = &clientcmd.ClientConfigLoadingRules{ExplicitPath: settings.KubeConfig}
}
if config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
loadingRules,
&clientcmd.ConfigOverrides{}).RawConfig(); err == nil {
comps := []string{}
for name, context := range config.Contexts {
comps = append(comps, fmt.Sprintf("%s\t%s", name, context.Cluster))
}
return comps, cobra.ShellCompDirectiveNoFileComp
}
return nil, cobra.ShellCompDirectiveNoFileComp
})
if err != nil {
log.Fatal(err)
}
registryClient, err := newDefaultRegistryClient(false, "", "")
if err != nil {
return nil, err
}
actionConfig.RegistryClient = registryClient
// Add subcommands
cmd.AddCommand(
// chart commands
newCreateCmd(out),
newDependencyCmd(actionConfig, out),
newPullCmd(actionConfig, out),
newShowCmd(actionConfig, out),
newLintCmd(out),
newPackageCmd(out),
newRepoCmd(out),
newSearchCmd(out),
newVerifyCmd(out),
// release commands
newGetCmd(actionConfig, out),
newHistoryCmd(actionConfig, out),
newInstallCmd(actionConfig, out),
newListCmd(actionConfig, out),
newReleaseTestCmd(actionConfig, out),
newRollbackCmd(actionConfig, out),
newStatusCmd(actionConfig, out),
newTemplateCmd(actionConfig, out),
newUninstallCmd(actionConfig, out),
newUpgradeCmd(actionConfig, out),
newCompletionCmd(out),
newEnvCmd(out),
newPluginCmd(out),
newVersionCmd(out),
// Hidden documentation generator command: 'helm docs'
newDocsCmd(out),
)
cmd.AddCommand(
newRegistryCmd(actionConfig, out),
newPushCmd(actionConfig, out),
)
// Find and add CLI plugins
loadCLIPlugins(cmd, out)
// Check for expired repositories
checkForExpiredRepos(settings.RepositoryConfig)
return cmd, nil
}
// This function loads releases into the memory storage if the
// environment variable is properly set.
func loadReleasesInMemory(actionConfig *action.Configuration) {
filePaths := strings.Split(os.Getenv("HELM_MEMORY_DRIVER_DATA"), ":")
if len(filePaths) == 0 {
return
}
store := actionConfig.Releases
mem, ok := store.Driver.(*driver.Memory)
if !ok {
// For an unexpected reason we are not dealing with the memory storage driver.
return
}
actionConfig.KubeClient = &kubefake.PrintingKubeClient{Out: io.Discard}
for _, path := range filePaths {
b, err := os.ReadFile(path)
if err != nil {
log.Fatal("Unable to read memory driver data", err)
}
releases := []*release.Release{}
if err := yaml.Unmarshal(b, &releases); err != nil {
log.Fatal("Unable to unmarshal memory driver data: ", err)
}
for _, rel := range releases {
if err := store.Create(rel); err != nil {
log.Fatal(err)
}
}
}
// Must reset namespace to the proper one
mem.SetNamespace(settings.Namespace())
}
// hookOutputWriter provides the writer for writing hook logs.
func hookOutputWriter(_, _, _ string) io.Writer {
return log.Writer()
}
func checkForExpiredRepos(repofile string) {
expiredRepos := []struct {
name string
old string
new string
}{
{
name: "stable",
old: "kubernetes-charts.storage.googleapis.com",
new: "https://charts.helm.sh/stable",
},
{
name: "incubator",
old: "kubernetes-charts-incubator.storage.googleapis.com",
new: "https://charts.helm.sh/incubator",
},
}
// parse repo file.
// Ignore the error because it is okay for a repo file to be unparsable at this
// stage. Later checks will trap the error and respond accordingly.
repoFile, err := repo.LoadFile(repofile)
if err != nil {
return
}
for _, exp := range expiredRepos {
r := repoFile.Get(exp.name)
if r == nil {
return
}
if url := r.URL; strings.Contains(url, exp.old) {
fmt.Fprintf(
os.Stderr,
"WARNING: %q is deprecated for %q and will be deleted Nov. 13, 2020.\nWARNING: You should switch to %q via:\nWARNING: helm repo add %q %q --force-update\n",
exp.old,
exp.name,
exp.new,
exp.name,
exp.new,
)
}
}
}
func newRegistryClient(
certFile, keyFile, caFile string, insecureSkipTLSVerify, plainHTTP bool, username, password string,
) (*registry.Client, error) {
if certFile != "" && keyFile != "" || caFile != "" || insecureSkipTLSVerify {
registryClient, err := newRegistryClientWithTLS(certFile, keyFile, caFile, insecureSkipTLSVerify, username, password)
if err != nil {
return nil, err
}
return registryClient, nil
}
registryClient, err := newDefaultRegistryClient(plainHTTP, username, password)
if err != nil {
return nil, err
}
return registryClient, nil
}
func newDefaultRegistryClient(plainHTTP bool, username, password string) (*registry.Client, error) {
opts := []registry.ClientOption{
registry.ClientOptDebug(settings.Debug),
registry.ClientOptEnableCache(true),
registry.ClientOptWriter(os.Stderr),
registry.ClientOptCredentialsFile(settings.RegistryConfig),
registry.ClientOptBasicAuth(username, password),
}
if plainHTTP {
opts = append(opts, registry.ClientOptPlainHTTP())
}
// Create a new registry client
registryClient, err := registry.NewClient(opts...)
if err != nil {
return nil, err
}
return registryClient, nil
}
func newRegistryClientWithTLS(
certFile, keyFile, caFile string, insecureSkipTLSVerify bool, username, password string,
) (*registry.Client, error) {
tlsConf, err := tlsutil.NewTLSConfig(
tlsutil.WithInsecureSkipVerify(insecureSkipTLSVerify),
tlsutil.WithCertKeyPairFiles(certFile, keyFile),
tlsutil.WithCAFile(caFile),
)
if err != nil {
return nil, fmt.Errorf("can't create TLS config for client: %w", err)
}
// Create a new registry client
registryClient, err := registry.NewClient(
registry.ClientOptDebug(settings.Debug),
registry.ClientOptEnableCache(true),
registry.ClientOptWriter(os.Stderr),
registry.ClientOptCredentialsFile(settings.RegistryConfig),
registry.ClientOptHTTPClient(&http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConf,
Proxy: http.ProxyFromEnvironment,
},
}),
registry.ClientOptBasicAuth(username, password),
)
if err != nil {
return nil, err
}
return registryClient, nil
}
type CommandError struct {
error
ExitCode int
}
// releaserToV1Release is a helper function to convert a v1 release passed by interface
// into the type object.
func releaserToV1Release(rel ri.Releaser) (*release.Release, error) {
switch r := rel.(type) {
case release.Release:
return &r, nil
case *release.Release:
return r, nil
case nil:
return nil, nil
default:
return nil, fmt.Errorf("unsupported release type: %T", rel)
}
}
func releaseListToV1List(ls []ri.Releaser) ([]*release.Release, error) {
rls := make([]*release.Release, 0, len(ls))
for _, val := range ls {
rel, err := releaserToV1Release(val)
if err != nil {
return nil, err
}
rls = append(rls, rel)
}
return rls, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin_update.go | pkg/cmd/plugin_update.go | /*
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 (
"errors"
"fmt"
"io"
"log/slog"
"path/filepath"
"github.com/spf13/cobra"
"helm.sh/helm/v4/internal/plugin"
"helm.sh/helm/v4/internal/plugin/installer"
)
type pluginUpdateOptions struct {
names []string
}
func newPluginUpdateCmd(out io.Writer) *cobra.Command {
o := &pluginUpdateOptions{}
cmd := &cobra.Command{
Use: "update <plugin>...",
Aliases: []string{"up"},
Short: "update one or more Helm plugins",
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return compListPlugins(toComplete, args), cobra.ShellCompDirectiveNoFileComp
},
PreRunE: func(_ *cobra.Command, args []string) error {
return o.complete(args)
},
RunE: func(_ *cobra.Command, _ []string) error {
return o.run(out)
},
}
return cmd
}
func (o *pluginUpdateOptions) complete(args []string) error {
if len(args) == 0 {
return errors.New("please provide plugin name to update")
}
o.names = args
return nil
}
func (o *pluginUpdateOptions) run(out io.Writer) error {
slog.Debug("loading installed plugins", "path", settings.PluginsDirectory)
plugins, err := plugin.LoadAll(settings.PluginsDirectory)
if err != nil {
return err
}
var errorPlugins []error
for _, name := range o.names {
if found := findPlugin(plugins, name); found != nil {
if err := updatePlugin(found); err != nil {
errorPlugins = append(errorPlugins, fmt.Errorf("failed to update plugin %s, got error (%v)", name, err))
} else {
fmt.Fprintf(out, "Updated plugin: %s\n", name)
}
} else {
errorPlugins = append(errorPlugins, fmt.Errorf("plugin: %s not found", name))
}
}
if len(errorPlugins) > 0 {
return errors.Join(errorPlugins...)
}
return nil
}
func updatePlugin(p plugin.Plugin) error {
exactLocation, err := filepath.EvalSymlinks(p.Dir())
if err != nil {
return err
}
absExactLocation, err := filepath.Abs(exactLocation)
if err != nil {
return err
}
i, err := installer.FindSource(absExactLocation)
if err != nil {
return err
}
if err := installer.Update(i); err != nil {
return err
}
slog.Debug("loading plugin", "path", i.Path())
updatedPlugin, err := plugin.LoadDir(i.Path())
if err != nil {
return err
}
return runHook(updatedPlugin, plugin.Update)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/lint_test.go | pkg/cmd/lint_test.go | /*
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 (
"fmt"
"testing"
)
func TestLintCmdWithSubchartsFlag(t *testing.T) {
testChart := "testdata/testcharts/chart-with-bad-subcharts"
tests := []cmdTestCase{{
name: "lint good chart with bad subcharts",
cmd: fmt.Sprintf("lint %s", testChart),
golden: "output/lint-chart-with-bad-subcharts.txt",
wantError: true,
}, {
name: "lint good chart with bad subcharts using --with-subcharts flag",
cmd: fmt.Sprintf("lint --with-subcharts %s", testChart),
golden: "output/lint-chart-with-bad-subcharts-with-subcharts.txt",
wantError: true,
}}
runTestCmd(t, tests)
}
func TestLintCmdWithQuietFlag(t *testing.T) {
testChart1 := "testdata/testcharts/alpine"
testChart2 := "testdata/testcharts/chart-bad-requirements"
tests := []cmdTestCase{{
name: "lint good chart using --quiet flag",
cmd: fmt.Sprintf("lint --quiet %s", testChart1),
golden: "output/lint-quiet.txt",
}, {
name: "lint two charts, one with error using --quiet flag",
cmd: fmt.Sprintf("lint --quiet %s %s", testChart1, testChart2),
golden: "output/lint-quiet-with-error.txt",
wantError: true,
}, {
name: "lint chart with warning using --quiet flag",
cmd: "lint --quiet testdata/testcharts/chart-with-only-crds",
golden: "output/lint-quiet-with-warning.txt",
}, {
name: "lint non-existent chart using --quiet flag",
cmd: "lint --quiet thischartdoesntexist/",
golden: "",
wantError: true,
}}
runTestCmd(t, tests)
}
func TestLintCmdWithKubeVersionFlag(t *testing.T) {
testChart := "testdata/testcharts/chart-with-deprecated-api"
tests := []cmdTestCase{{
name: "lint chart with deprecated api version using kube version flag",
cmd: fmt.Sprintf("lint --kube-version 1.22.0 %s", testChart),
golden: "output/lint-chart-with-deprecated-api.txt",
wantError: false,
}, {
name: "lint chart with deprecated api version using kube version and strict flag",
cmd: fmt.Sprintf("lint --kube-version 1.22.0 --strict %s", testChart),
golden: "output/lint-chart-with-deprecated-api-strict.txt",
wantError: true,
}, {
// the test builds will use the kubeVersionMinorTesting const in capabilities.go
// which is "20"
name: "lint chart with deprecated api version without kube version",
cmd: fmt.Sprintf("lint %s", testChart),
golden: "output/lint-chart-with-deprecated-api-old-k8s.txt",
wantError: false,
}, {
name: "lint chart with deprecated api version with older kube version",
cmd: fmt.Sprintf("lint --kube-version 1.21.0 --strict %s", testChart),
golden: "output/lint-chart-with-deprecated-api-old-k8s.txt",
wantError: false,
}}
runTestCmd(t, tests)
}
func TestLintCmdRequiresArgs(t *testing.T) {
tests := []cmdTestCase{{
name: "lint without arguments should fail",
cmd: "lint",
wantError: true,
}}
runTestCmd(t, tests)
}
func TestLintFileCompletion(t *testing.T) {
checkFileCompletion(t, "lint", true)
checkFileCompletion(t, "lint mypath", true) // Multiple paths can be given
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/create.go | pkg/cmd/create.go | /*
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 (
"fmt"
"io"
"path/filepath"
"github.com/spf13/cobra"
chart "helm.sh/helm/v4/pkg/chart/v2"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/cmd/require"
"helm.sh/helm/v4/pkg/helmpath"
)
const createDesc = `
This command creates a chart directory along with the common files and
directories used in a chart.
For example, 'helm create foo' will create a directory structure that looks
something like this:
foo/
├── .helmignore # Contains patterns to ignore when packaging Helm charts.
├── Chart.yaml # Information about your chart
├── values.yaml # The default values for your templates
├── charts/ # Charts that this chart depends on
└── templates/ # The template files
└── tests/ # The test files
'helm create' takes a path for an argument. If directories in the given path
do not exist, Helm will attempt to create them as it goes. If the given
destination exists and there are files in that directory, conflicting files
will be overwritten, but other files will be left alone.
`
type createOptions struct {
starter string // --starter
name string
starterDir string
}
func newCreateCmd(out io.Writer) *cobra.Command {
o := &createOptions{}
cmd := &cobra.Command{
Use: "create NAME",
Short: "create a new chart with the given name",
Long: createDesc,
Args: require.ExactArgs(1),
ValidArgsFunction: func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
// Allow file completion when completing the argument for the name
// which could be a path
return nil, cobra.ShellCompDirectiveDefault
}
// No more completions, so disable file completion
return noMoreArgsComp()
},
RunE: func(_ *cobra.Command, args []string) error {
o.name = args[0]
o.starterDir = helmpath.DataPath("starters")
return o.run(out)
},
}
cmd.Flags().StringVarP(&o.starter, "starter", "p", "", "the name or absolute path to Helm starter scaffold")
return cmd
}
func (o *createOptions) run(out io.Writer) error {
fmt.Fprintf(out, "Creating %s\n", o.name)
chartname := filepath.Base(o.name)
cfile := &chart.Metadata{
Name: chartname,
Description: "A Helm chart for Kubernetes",
Type: "application",
Version: "0.1.0",
AppVersion: "0.1.0",
APIVersion: chart.APIVersionV2,
}
if o.starter != "" {
// Create from the starter
lstarter := filepath.Join(o.starterDir, o.starter)
// If path is absolute, we don't want to prefix it with helm starters folder
if filepath.IsAbs(o.starter) {
lstarter = o.starter
}
return chartutil.CreateFrom(cfile, filepath.Dir(o.name), lstarter)
}
chartutil.Stderr = out
_, err := chartutil.Create(chartname, filepath.Dir(o.name))
return err
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/plugin_verify.go | pkg/cmd/plugin_verify.go | /*
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 (
"fmt"
"io"
"os"
"path/filepath"
"github.com/spf13/cobra"
"helm.sh/helm/v4/internal/plugin"
"helm.sh/helm/v4/pkg/cmd/require"
)
const pluginVerifyDesc = `
This command verifies that a Helm plugin has a valid provenance file,
and that the provenance file is signed by a trusted PGP key.
It supports both:
- Plugin tarballs (.tgz or .tar.gz files)
- Installed plugin directories
For installed plugins, use the path shown by 'helm env HELM_PLUGINS' followed
by the plugin name. For example:
helm plugin verify ~/.local/share/helm/plugins/example-cli
To generate a signed plugin, use the 'helm plugin package --sign' command.
`
type pluginVerifyOptions struct {
keyring string
pluginPath string
}
func newPluginVerifyCmd(out io.Writer) *cobra.Command {
o := &pluginVerifyOptions{}
cmd := &cobra.Command{
Use: "verify [PATH]",
Short: "verify that a plugin at the given path has been signed and is valid",
Long: pluginVerifyDesc,
Args: require.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
o.pluginPath = args[0]
return o.run(out)
},
}
cmd.Flags().StringVar(&o.keyring, "keyring", defaultKeyring(), "keyring containing public keys")
return cmd
}
func (o *pluginVerifyOptions) run(out io.Writer) error {
// Verify the plugin path exists
fi, err := os.Stat(o.pluginPath)
if err != nil {
return err
}
// Only support tarball verification
if fi.IsDir() {
return fmt.Errorf("directory verification not supported - only plugin tarballs can be verified")
}
// Verify it's a tarball
if !plugin.IsTarball(o.pluginPath) {
return fmt.Errorf("plugin file must be a gzipped tarball (.tar.gz or .tgz)")
}
// Look for provenance file
provFile := o.pluginPath + ".prov"
if _, err := os.Stat(provFile); err != nil {
return fmt.Errorf("could not find provenance file %s: %w", provFile, err)
}
// Read the files
archiveData, err := os.ReadFile(o.pluginPath)
if err != nil {
return fmt.Errorf("failed to read plugin file: %w", err)
}
provData, err := os.ReadFile(provFile)
if err != nil {
return fmt.Errorf("failed to read provenance file: %w", err)
}
// Verify the plugin using data
verification, err := plugin.VerifyPlugin(archiveData, provData, filepath.Base(o.pluginPath), o.keyring)
if err != nil {
return err
}
// Output verification details
for name := range verification.SignedBy.Identities {
fmt.Fprintf(out, "Signed by: %v\n", name)
}
fmt.Fprintf(out, "Using Key With Fingerprint: %X\n", verification.SignedBy.PrimaryKey.Fingerprint)
// Only show hash for tarballs
if verification.FileHash != "" {
fmt.Fprintf(out, "Plugin Hash Verified: %s\n", verification.FileHash)
} else {
fmt.Fprintf(out, "Plugin Metadata Verified: %s\n", verification.FileName)
}
return nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/dependency_update_test.go | pkg/cmd/dependency_update_test.go | /*
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 (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
"helm.sh/helm/v4/internal/test/ensure"
chart "helm.sh/helm/v4/pkg/chart/v2"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/helmpath"
"helm.sh/helm/v4/pkg/provenance"
"helm.sh/helm/v4/pkg/repo/v1"
"helm.sh/helm/v4/pkg/repo/v1/repotest"
)
func TestDependencyUpdateCmd(t *testing.T) {
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/testcharts/*.tgz"),
)
defer srv.Stop()
t.Logf("Listening on directory %s", srv.Root())
ociSrv, err := repotest.NewOCIServer(t, srv.Root())
if err != nil {
t.Fatal(err)
}
contentCache := t.TempDir()
ociChartName := "oci-depending-chart"
c := createTestingMetadataForOCI(ociChartName, ociSrv.RegistryURL)
if _, err := chartutil.Save(c, ociSrv.Dir); err != nil {
t.Fatal(err)
}
ociSrv.Run(t, repotest.WithDependingChart(c))
if err := srv.LinkIndices(); err != nil {
t.Fatal(err)
}
dir := func(p ...string) string {
return filepath.Join(append([]string{srv.Root()}, p...)...)
}
chartname := "depup"
ch := createTestingMetadata(chartname, srv.URL())
md := ch.Metadata
if err := chartutil.SaveDir(ch, dir()); err != nil {
t.Fatal(err)
}
_, out, err := executeActionCommand(
fmt.Sprintf("dependency update '%s' --repository-config %s --repository-cache %s --content-cache %s --plain-http", dir(chartname), dir("repositories.yaml"), dir(), contentCache),
)
if err != nil {
t.Logf("Output: %s", out)
t.Fatal(err)
}
// This is written directly to stdout, so we have to capture as is.
if !strings.Contains(out, `update from the "test" chart repository`) {
t.Errorf("Repo did not get updated\n%s", out)
}
// Make sure the actual file got downloaded.
expect := dir(chartname, "charts/reqtest-0.1.0.tgz")
if _, err := os.Stat(expect); err != nil {
t.Fatal(err)
}
hash, err := provenance.DigestFile(expect)
if err != nil {
t.Fatal(err)
}
i, err := repo.LoadIndexFile(dir(helmpath.CacheIndexFile("test")))
if err != nil {
t.Fatal(err)
}
reqver := i.Entries["reqtest"][0]
if h := reqver.Digest; h != hash {
t.Errorf("Failed hash match: expected %s, got %s", hash, h)
}
// Now change the dependencies and update. This verifies that on update,
// old dependencies are cleansed and new dependencies are added.
md.Dependencies = []*chart.Dependency{
{Name: "reqtest", Version: "0.1.0", Repository: srv.URL()},
{Name: "compressedchart", Version: "0.3.0", Repository: srv.URL()},
}
if err := chartutil.SaveChartfile(dir(chartname, "Chart.yaml"), md); err != nil {
t.Fatal(err)
}
_, out, err = executeActionCommand(fmt.Sprintf("dependency update '%s' --repository-config %s --repository-cache %s --content-cache %s --plain-http", dir(chartname), dir("repositories.yaml"), dir(), contentCache))
if err != nil {
t.Logf("Output: %s", out)
t.Fatal(err)
}
// In this second run, we should see compressedchart-0.3.0.tgz, and not
// the 0.1.0 version.
expect = dir(chartname, "charts/compressedchart-0.3.0.tgz")
if _, err := os.Stat(expect); err != nil {
t.Fatalf("Expected %q: %s", expect, err)
}
unexpected := dir(chartname, "charts/compressedchart-0.1.0.tgz")
if _, err := os.Stat(unexpected); err == nil {
t.Fatalf("Unexpected %q", unexpected)
}
// test for OCI charts
if err := chartutil.SaveDir(c, dir()); err != nil {
t.Fatal(err)
}
cmd := fmt.Sprintf("dependency update '%s' --repository-config %s --repository-cache %s --registry-config %s/config.json --content-cache %s --plain-http",
dir(ociChartName),
dir("repositories.yaml"),
dir(),
dir(),
contentCache)
_, out, err = executeActionCommand(cmd)
if err != nil {
t.Logf("Output: %s", out)
t.Fatal(err)
}
expect = dir(ociChartName, "charts/oci-dependent-chart-0.1.0.tgz")
if _, err := os.Stat(expect); err != nil {
t.Fatal(err)
}
}
func TestDependencyUpdateCmd_DoNotDeleteOldChartsOnError(t *testing.T) {
defer resetEnv()()
ensure.HelmHome(t)
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/testcharts/*.tgz"),
)
defer srv.Stop()
t.Logf("Listening on directory %s", srv.Root())
if err := srv.LinkIndices(); err != nil {
t.Fatal(err)
}
chartname := "depupdelete"
dir := func(p ...string) string {
return filepath.Join(append([]string{srv.Root()}, p...)...)
}
createTestingChart(t, dir(), chartname, srv.URL())
_, output, err := executeActionCommand(fmt.Sprintf("dependency update %s --repository-config %s --repository-cache %s --plain-http", dir(chartname), dir("repositories.yaml"), dir()))
if err != nil {
t.Logf("Output: %s", output)
t.Fatal(err)
}
// Chart repo is down
srv.Stop()
contentCache := t.TempDir()
_, output, err = executeActionCommand(fmt.Sprintf("dependency update %s --repository-config %s --repository-cache %s --content-cache %s --plain-http", dir(chartname), dir("repositories.yaml"), dir(), contentCache))
if err == nil {
t.Logf("Output: %s", output)
t.Fatal("Expected error, got nil")
}
// Make sure charts dir still has dependencies
files, err := os.ReadDir(filepath.Join(dir(chartname), "charts"))
if err != nil {
t.Fatal(err)
}
dependencies := []string{"compressedchart-0.1.0.tgz", "reqtest-0.1.0.tgz"}
if len(dependencies) != len(files) {
t.Fatalf("Expected %d chart dependencies, got %d", len(dependencies), len(files))
}
for index, file := range files {
if dependencies[index] != file.Name() {
t.Fatalf("Chart dependency %s not matching %s", dependencies[index], file.Name())
}
}
// Make sure tmpcharts-x is deleted
tmpPath := filepath.Join(dir(chartname), fmt.Sprintf("tmpcharts-%d", os.Getpid()))
if _, err := os.Stat(tmpPath); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("tmpcharts dir still exists")
}
}
func TestDependencyUpdateCmd_WithRepoThatWasNotAdded(t *testing.T) {
srv := setupMockRepoServer(t)
srvForUnmanagedRepo := setupMockRepoServer(t)
defer srv.Stop()
defer srvForUnmanagedRepo.Stop()
dir := func(p ...string) string {
return filepath.Join(append([]string{srv.Root()}, p...)...)
}
chartname := "depup"
ch := createTestingMetadata(chartname, srv.URL())
chartDependency := &chart.Dependency{
Name: "signtest",
Version: "0.1.0",
Repository: srvForUnmanagedRepo.URL(),
}
ch.Metadata.Dependencies = append(ch.Metadata.Dependencies, chartDependency)
if err := chartutil.SaveDir(ch, dir()); err != nil {
t.Fatal(err)
}
contentCache := t.TempDir()
_, out, err := executeActionCommand(
fmt.Sprintf("dependency update '%s' --repository-config %s --repository-cache %s --content-cache %s", dir(chartname),
dir("repositories.yaml"), dir(), contentCache),
)
if err != nil {
t.Logf("Output: %s", out)
t.Fatal(err)
}
// This is written directly to stdout, so we have to capture as is
if !strings.Contains(out, `Getting updates for unmanaged Helm repositories...`) {
t.Errorf("No ‘unmanaged’ Helm repo used in test chartdependency or it doesn’t cause the creation "+
"of an ‘ad hoc’ repo index cache file\n%s", out)
}
}
func setupMockRepoServer(t *testing.T) *repotest.Server {
t.Helper()
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/testcharts/*.tgz"),
)
t.Logf("Listening on directory %s", srv.Root())
if err := srv.LinkIndices(); err != nil {
t.Fatal(err)
}
return srv
}
// createTestingMetadata creates a basic chart that depends on reqtest-0.1.0
//
// The baseURL can be used to point to a particular repository server.
func createTestingMetadata(name, baseURL string) *chart.Chart {
return &chart.Chart{
Metadata: &chart.Metadata{
APIVersion: chart.APIVersionV2,
Name: name,
Version: "1.2.3",
Dependencies: []*chart.Dependency{
{Name: "reqtest", Version: "0.1.0", Repository: baseURL},
{Name: "compressedchart", Version: "0.1.0", Repository: baseURL},
},
},
}
}
func createTestingMetadataForOCI(name, registryURL string) *chart.Chart {
return &chart.Chart{
Metadata: &chart.Metadata{
APIVersion: chart.APIVersionV2,
Name: name,
Version: "1.2.3",
Dependencies: []*chart.Dependency{
{Name: "oci-dependent-chart", Version: "0.1.0", Repository: fmt.Sprintf("oci://%s/u/ocitestuser", registryURL)},
},
},
}
}
// createTestingChart creates a basic chart that depends on reqtest-0.1.0
//
// The baseURL can be used to point to a particular repository server.
func createTestingChart(t *testing.T, dest, name, baseURL string) {
t.Helper()
cfile := createTestingMetadata(name, baseURL)
if err := chartutil.SaveDir(cfile, dest); err != nil {
t.Fatal(err)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/registry.go | pkg/cmd/registry.go | /*
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 (
"io"
"github.com/spf13/cobra"
"helm.sh/helm/v4/pkg/action"
)
const registryHelp = `
This command consists of multiple subcommands to interact with registries.
`
func newRegistryCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "registry",
Short: "login to or logout from a registry",
Long: registryHelp,
}
cmd.AddCommand(
newRegistryLoginCmd(cfg, out),
newRegistryLogoutCmd(cfg, out),
)
return cmd
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_metadata_test.go | pkg/cmd/get_metadata_test.go | /*
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 (
"testing"
release "helm.sh/helm/v4/pkg/release/v1"
)
func TestGetMetadataCmd(t *testing.T) {
tests := []cmdTestCase{{
name: "get metadata with a release",
cmd: "get metadata thomas-guide",
golden: "output/get-metadata.txt",
rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "thomas-guide", Labels: map[string]string{"key1": "value1"}})},
}, {
name: "get metadata requires release name arg",
cmd: "get metadata",
golden: "output/get-metadata-args.txt",
rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "thomas-guide", Labels: map[string]string{"key1": "value1"}})},
wantError: true,
}, {
name: "get metadata to json",
cmd: "get metadata thomas-guide --output json",
golden: "output/get-metadata.json",
rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "thomas-guide", Labels: map[string]string{"key1": "value1"}})},
}, {
name: "get metadata to yaml",
cmd: "get metadata thomas-guide --output yaml",
golden: "output/get-metadata.yaml",
rels: []*release.Release{release.Mock(&release.MockReleaseOptions{Name: "thomas-guide", Labels: map[string]string{"key1": "value1"}})},
}}
runTestCmd(t, tests)
}
func TestGetMetadataCompletion(t *testing.T) {
checkReleaseCompletion(t, "get metadata", false)
}
func TestGetMetadataRevisionCompletion(t *testing.T) {
revisionFlagCompletionTest(t, "get metadata")
}
func TestGetMetadataOutputCompletion(t *testing.T) {
outputFlagCompletionTest(t, "get metadata")
}
func TestGetMetadataFileCompletion(t *testing.T) {
checkFileCompletion(t, "get metadata", false)
checkFileCompletion(t, "get metadata myrelease", false)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/install.go | pkg/cmd/install.go | /*
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 (
"context"
"fmt"
"io"
"log"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/chart"
"helm.sh/helm/v4/pkg/chart/loader"
"helm.sh/helm/v4/pkg/cli/output"
"helm.sh/helm/v4/pkg/cli/values"
"helm.sh/helm/v4/pkg/cmd/require"
"helm.sh/helm/v4/pkg/downloader"
"helm.sh/helm/v4/pkg/getter"
release "helm.sh/helm/v4/pkg/release/v1"
)
const installDesc = `
This command installs a chart archive.
The install argument must be a chart reference, a path to a packaged chart,
a path to an unpacked chart directory or a URL.
To override values in a chart, use either the '--values' flag and pass in a file
or use the '--set' flag and pass configuration from the command line, to force
a string value use '--set-string'. You can use '--set-file' to set individual
values from a file when the value itself is too long for the command line
or is dynamically generated. You can also use '--set-json' to set json values
(scalars/objects/arrays) from the command line. Additionally, you can use '--set-json' and passing json object as a string.
$ helm install -f myvalues.yaml myredis ./redis
or
$ helm install --set name=prod myredis ./redis
or
$ helm install --set-string long_int=1234567890 myredis ./redis
or
$ helm install --set-file my_script=dothings.sh myredis ./redis
or
$ helm install --set-json 'master.sidecars=[{"name":"sidecar","image":"myImage","imagePullPolicy":"Always","ports":[{"name":"portname","containerPort":1234}]}]' myredis ./redis
or
$ helm install --set-json '{"master":{"sidecars":[{"name":"sidecar","image":"myImage","imagePullPolicy":"Always","ports":[{"name":"portname","containerPort":1234}]}]}}' myredis ./redis
You can specify the '--values'/'-f' flag multiple times. The priority will be given to the
last (right-most) file specified. For example, if both myvalues.yaml and override.yaml
contained a key called 'Test', the value set in override.yaml would take precedence:
$ helm install -f myvalues.yaml -f override.yaml myredis ./redis
You can specify the '--set' flag multiple times. The priority will be given to the
last (right-most) set specified. For example, if both 'bar' and 'newbar' values are
set for a key called 'foo', the 'newbar' value would take precedence:
$ helm install --set foo=bar --set foo=newbar myredis ./redis
Similarly, in the following example 'foo' is set to '["four"]':
$ helm install --set-json='foo=["one", "two", "three"]' --set-json='foo=["four"]' myredis ./redis
And in the following example, 'foo' is set to '{"key1":"value1","key2":"bar"}':
$ helm install --set-json='foo={"key1":"value1","key2":"value2"}' --set-json='foo.key2="bar"' myredis ./redis
To check the generated manifests of a release without installing the chart,
the --debug and --dry-run flags can be combined.
The --dry-run flag will output all generated chart manifests, including Secrets
which can contain sensitive values. To hide Kubernetes Secrets use the
--hide-secret flag. Please carefully consider how and when these flags are used.
If --verify is set, the chart MUST have a provenance file, and the provenance
file MUST pass all verification steps.
There are six different ways you can express the chart you want to install:
1. By chart reference: helm install mymaria example/mariadb
2. By path to a packaged chart: helm install mynginx ./nginx-1.2.3.tgz
3. By path to an unpacked chart directory: helm install mynginx ./nginx
4. By absolute URL: helm install mynginx https://example.com/charts/nginx-1.2.3.tgz
5. By chart reference and repo url: helm install --repo https://example.com/charts/ mynginx nginx
6. By OCI registries: helm install mynginx --version 1.2.3 oci://example.com/charts/nginx
CHART REFERENCES
A chart reference is a convenient way of referencing a chart in a chart repository.
When you use a chart reference with a repo prefix ('example/mariadb'), Helm will look in the local
configuration for a chart repository named 'example', and will then look for a
chart in that repository whose name is 'mariadb'. It will install the latest stable version of that chart
until you specify '--devel' flag to also include development version (alpha, beta, and release candidate releases), or
supply a version number with the '--version' flag.
To see the list of chart repositories, use 'helm repo list'. To search for
charts in a repository, use 'helm search'.
`
func newInstallCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewInstall(cfg)
valueOpts := &values.Options{}
var outfmt output.Format
cmd := &cobra.Command{
Use: "install [NAME] [CHART]",
Short: "install a chart",
Long: installDesc,
Args: require.MinimumNArgs(1),
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return compInstall(args, toComplete, client)
},
RunE: func(cmd *cobra.Command, args []string) error {
registryClient, err := newRegistryClient(client.CertFile, client.KeyFile, client.CaFile,
client.InsecureSkipTLSVerify, client.PlainHTTP, client.Username, client.Password)
if err != nil {
return fmt.Errorf("missing registry client: %w", err)
}
client.SetRegistryClient(registryClient)
dryRunStrategy, err := cmdGetDryRunFlagStrategy(cmd, false)
if err != nil {
return err
}
client.DryRunStrategy = dryRunStrategy
rel, err := runInstall(args, client, valueOpts, out)
if err != nil {
return fmt.Errorf("INSTALLATION FAILED: %w", err)
}
return outfmt.Write(out, &statusPrinter{
release: rel,
debug: settings.Debug,
showMetadata: false,
hideNotes: client.HideNotes,
noColor: settings.ShouldDisableColor(),
})
},
}
f := cmd.Flags()
addInstallFlags(cmd, f, client, valueOpts)
// hide-secret is not available in all places the install flags are used so
// it is added separately
f.BoolVar(&client.HideSecret, "hide-secret", false, "hide Kubernetes Secrets when also using the --dry-run flag")
addDryRunFlag(cmd)
bindOutputFlag(cmd, &outfmt)
bindPostRenderFlag(cmd, &client.PostRenderer, settings)
return cmd
}
func addInstallFlags(cmd *cobra.Command, f *pflag.FlagSet, client *action.Install, valueOpts *values.Options) {
f.BoolVar(&client.CreateNamespace, "create-namespace", false, "create the release namespace if not present")
f.BoolVar(&client.ForceReplace, "force-replace", false, "force resource updates by replacement")
f.BoolVar(&client.ForceReplace, "force", false, "deprecated")
f.MarkDeprecated("force", "use --force-replace instead")
f.BoolVar(&client.ForceConflicts, "force-conflicts", false, "if set server-side apply will force changes against conflicts")
f.BoolVar(&client.ServerSideApply, "server-side", true, "object updates run in the server instead of the client")
f.BoolVar(&client.DisableHooks, "no-hooks", false, "prevent hooks from running during install")
f.BoolVar(&client.Replace, "replace", false, "reuse the given name, only if that name is a deleted release which remains in the history. This is unsafe in production")
f.DurationVar(&client.Timeout, "timeout", 300*time.Second, "time to wait for any individual Kubernetes operation (like Jobs for hooks)")
f.BoolVar(&client.WaitForJobs, "wait-for-jobs", false, "if set and --wait enabled, will wait until all Jobs have been completed before marking the release as successful. It will wait for as long as --timeout")
f.BoolVarP(&client.GenerateName, "generate-name", "g", false, "generate the name (and omit the NAME parameter)")
f.StringVar(&client.NameTemplate, "name-template", "", "specify template used to name the release")
f.StringVar(&client.Description, "description", "", "add a custom description")
f.BoolVar(&client.Devel, "devel", false, "use development versions, too. Equivalent to version '>0.0.0-0'. If --version is set, this is ignored")
f.BoolVar(&client.DependencyUpdate, "dependency-update", false, "update dependencies if they are missing before installing the chart")
f.BoolVar(&client.DisableOpenAPIValidation, "disable-openapi-validation", false, "if set, the installation process will not validate rendered templates against the Kubernetes OpenAPI Schema")
f.BoolVar(&client.RollbackOnFailure, "rollback-on-failure", false, "if set, Helm will rollback (uninstall) the installation upon failure. The --wait flag will be default to \"watcher\" if --rollback-on-failure is set")
f.MarkDeprecated("atomic", "use --rollback-on-failure instead")
f.BoolVar(&client.SkipCRDs, "skip-crds", false, "if set, no CRDs will be installed. By default, CRDs are installed if not already present")
f.BoolVar(&client.SubNotes, "render-subchart-notes", false, "if set, render subchart notes along with the parent")
f.BoolVar(&client.SkipSchemaValidation, "skip-schema-validation", false, "if set, disables JSON schema validation")
f.StringToStringVarP(&client.Labels, "labels", "l", nil, "Labels that would be added to release metadata. Should be divided by comma.")
f.BoolVar(&client.EnableDNS, "enable-dns", false, "enable DNS lookups when rendering templates")
f.BoolVar(&client.HideNotes, "hide-notes", false, "if set, do not show notes in install output. Does not affect presence in chart metadata")
f.BoolVar(&client.TakeOwnership, "take-ownership", false, "if set, install will ignore the check for helm annotations and take ownership of the existing resources")
addValueOptionsFlags(f, valueOpts)
addChartPathOptionsFlags(f, &client.ChartPathOptions)
AddWaitFlag(cmd, &client.WaitStrategy)
cmd.MarkFlagsMutuallyExclusive("force-replace", "force-conflicts")
cmd.MarkFlagsMutuallyExclusive("force", "force-conflicts")
err := cmd.RegisterFlagCompletionFunc("version", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
requiredArgs := 2
if client.GenerateName {
requiredArgs = 1
}
if len(args) != requiredArgs {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return compVersionFlag(args[requiredArgs-1], toComplete)
})
if err != nil {
log.Fatal(err)
}
}
func runInstall(args []string, client *action.Install, valueOpts *values.Options, out io.Writer) (*release.Release, error) {
slog.Debug("Original chart version", "version", client.Version)
if client.Version == "" && client.Devel {
slog.Debug("setting version to >0.0.0-0")
client.Version = ">0.0.0-0"
}
name, chartRef, err := client.NameAndChart(args)
if err != nil {
return nil, err
}
client.ReleaseName = name
cp, err := client.LocateChart(chartRef, settings)
if err != nil {
return nil, err
}
slog.Debug("Chart path", "path", cp)
p := getter.All(settings)
vals, err := valueOpts.MergeValues(p)
if err != nil {
return nil, err
}
// Check chart dependencies to make sure all are present in /charts
chartRequested, err := loader.Load(cp)
if err != nil {
return nil, err
}
ac, err := chart.NewAccessor(chartRequested)
if err != nil {
return nil, err
}
if err := checkIfInstallable(ac); err != nil {
return nil, err
}
if ac.Deprecated() {
slog.Warn("this chart is deprecated")
}
if req := ac.MetaDependencies(); len(req) > 0 {
// If CheckDependencies returns an error, we have unfulfilled dependencies.
// As of Helm 2.4.0, this is treated as a stopping condition:
// https://github.com/helm/helm/issues/2209
if err := action.CheckDependencies(chartRequested, req); err != nil {
if client.DependencyUpdate {
man := &downloader.Manager{
Out: out,
ChartPath: cp,
Keyring: client.Keyring,
SkipUpdate: false,
Getters: p,
RepositoryConfig: settings.RepositoryConfig,
RepositoryCache: settings.RepositoryCache,
ContentCache: settings.ContentCache,
Debug: settings.Debug,
RegistryClient: client.GetRegistryClient(),
}
if err := man.Update(); err != nil {
return nil, err
}
// Reload the chart with the updated Chart.lock file.
if chartRequested, err = loader.Load(cp); err != nil {
return nil, fmt.Errorf("failed reloading chart after repo update: %w", err)
}
} else {
return nil, fmt.Errorf("an error occurred while checking for chart dependencies. You may need to run `helm dependency build` to fetch missing dependencies: %w", err)
}
}
}
client.Namespace = settings.Namespace()
// Create context and prepare the handle of SIGTERM
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
// Set up channel on which to send signal notifications.
// We must use a buffered channel or risk missing the signal
// if we're not ready to receive when the signal is sent.
cSignal := make(chan os.Signal, 2)
signal.Notify(cSignal, os.Interrupt, syscall.SIGTERM)
go func() {
<-cSignal
fmt.Fprintf(out, "Release %s has been cancelled.\n", args[0])
cancel()
}()
ri, err := client.RunWithContext(ctx, chartRequested, vals)
rel, rerr := releaserToV1Release(ri)
if rerr != nil {
return nil, rerr
}
return rel, err
}
// checkIfInstallable validates if a chart can be installed
//
// Application chart type is only installable
func checkIfInstallable(ch chart.Accessor) error {
meta := ch.MetadataAsMap()
switch meta["Type"] {
case "", "application":
return nil
}
return fmt.Errorf("%s charts are not installable", meta["Type"])
}
// Provide dynamic auto-completion for the install and template commands
func compInstall(args []string, toComplete string, client *action.Install) ([]string, cobra.ShellCompDirective) {
requiredArgs := 1
if client.GenerateName {
requiredArgs = 0
}
if len(args) == requiredArgs {
return compListCharts(toComplete, true)
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/status.go | pkg/cmd/status.go | /*
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 (
"bytes"
"fmt"
"io"
"log"
"strings"
"time"
"github.com/spf13/cobra"
"k8s.io/kubectl/pkg/cmd/get"
coloroutput "helm.sh/helm/v4/internal/cli/output"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/chart/common/util"
"helm.sh/helm/v4/pkg/cli/output"
"helm.sh/helm/v4/pkg/cmd/require"
"helm.sh/helm/v4/pkg/release"
releasev1 "helm.sh/helm/v4/pkg/release/v1"
)
// NOTE: Keep the list of statuses up-to-date with pkg/release/status.go.
var statusHelp = `
This command shows the status of a named release.
The status consists of:
- last deployment time
- k8s namespace in which the release lives
- state of the release (can be: unknown, deployed, uninstalled, superseded, failed, uninstalling, pending-install, pending-upgrade or pending-rollback)
- revision of the release
- description of the release (can be completion message or error message)
- list of resources that this release consists of
- details on last test suite run, if applicable
- additional notes provided by the chart
`
func newStatusCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewStatus(cfg)
var outfmt output.Format
cmd := &cobra.Command{
Use: "status RELEASE_NAME",
Short: "display the status of the named release",
Long: statusHelp,
Args: require.ExactArgs(1),
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return noMoreArgsComp()
}
return compListReleases(toComplete, args, cfg)
},
RunE: func(_ *cobra.Command, args []string) error {
// When the output format is a table the resources should be fetched
// and displayed as a table. When YAML or JSON the resources will be
// returned. This mirrors the handling in kubectl.
if outfmt == output.Table {
client.ShowResourcesTable = true
}
reli, err := client.Run(args[0])
if err != nil {
return err
}
rel, err := releaserToV1Release(reli)
if err != nil {
return err
}
// strip chart metadata from the output
rel.Chart = nil
return outfmt.Write(out, &statusPrinter{
release: rel,
debug: false,
showMetadata: false,
hideNotes: false,
noColor: settings.ShouldDisableColor(),
})
},
}
f := cmd.Flags()
f.IntVar(&client.Version, "revision", 0, "if set, display the status of the named release with revision")
err := cmd.RegisterFlagCompletionFunc("revision", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 1 {
return compListRevisions(toComplete, cfg, args[0])
}
return nil, cobra.ShellCompDirectiveNoFileComp
})
if err != nil {
log.Fatal(err)
}
bindOutputFlag(cmd, &outfmt)
return cmd
}
type statusPrinter struct {
release release.Releaser
debug bool
showMetadata bool
hideNotes bool
noColor bool
}
func (s statusPrinter) getV1Release() *releasev1.Release {
switch rel := s.release.(type) {
case releasev1.Release:
return &rel
case *releasev1.Release:
return rel
}
return &releasev1.Release{}
}
func (s statusPrinter) WriteJSON(out io.Writer) error {
return output.EncodeJSON(out, s.getV1Release())
}
func (s statusPrinter) WriteYAML(out io.Writer) error {
return output.EncodeYAML(out, s.getV1Release())
}
func (s statusPrinter) WriteTable(out io.Writer) error {
if s.release == nil {
return nil
}
rel := s.getV1Release()
_, _ = fmt.Fprintf(out, "NAME: %s\n", rel.Name)
if !rel.Info.LastDeployed.IsZero() {
_, _ = fmt.Fprintf(out, "LAST DEPLOYED: %s\n", rel.Info.LastDeployed.Format(time.ANSIC))
}
_, _ = fmt.Fprintf(out, "NAMESPACE: %s\n", coloroutput.ColorizeNamespace(rel.Namespace, s.noColor))
_, _ = fmt.Fprintf(out, "STATUS: %s\n", coloroutput.ColorizeStatus(rel.Info.Status, s.noColor))
_, _ = fmt.Fprintf(out, "REVISION: %d\n", rel.Version)
if s.showMetadata {
_, _ = fmt.Fprintf(out, "CHART: %s\n", rel.Chart.Metadata.Name)
_, _ = fmt.Fprintf(out, "VERSION: %s\n", rel.Chart.Metadata.Version)
_, _ = fmt.Fprintf(out, "APP_VERSION: %s\n", rel.Chart.Metadata.AppVersion)
}
_, _ = fmt.Fprintf(out, "DESCRIPTION: %s\n", rel.Info.Description)
if len(rel.Info.Resources) > 0 {
buf := new(bytes.Buffer)
printFlags := get.NewHumanPrintFlags()
typePrinter, _ := printFlags.ToPrinter("")
printer := &get.TablePrinter{Delegate: typePrinter}
var keys []string
for key := range rel.Info.Resources {
keys = append(keys, key)
}
for _, t := range keys {
_, _ = fmt.Fprintf(buf, "==> %s\n", t)
vk := rel.Info.Resources[t]
for _, resource := range vk {
if err := printer.PrintObj(resource, buf); err != nil {
_, _ = fmt.Fprintf(buf, "failed to print object type %s: %v\n", t, err)
}
}
buf.WriteString("\n")
}
_, _ = fmt.Fprintf(out, "RESOURCES:\n%s\n", buf.String())
}
executions := executionsByHookEvent(rel)
if tests, ok := executions[releasev1.HookTest]; !ok || len(tests) == 0 {
_, _ = fmt.Fprintln(out, "TEST SUITE: None")
} else {
for _, h := range tests {
// Don't print anything if hook has not been initiated
if h.LastRun.StartedAt.IsZero() {
continue
}
_, _ = fmt.Fprintf(out, "TEST SUITE: %s\n%s\n%s\n%s\n",
h.Name,
fmt.Sprintf("Last Started: %s", h.LastRun.StartedAt.Format(time.ANSIC)),
fmt.Sprintf("Last Completed: %s", h.LastRun.CompletedAt.Format(time.ANSIC)),
fmt.Sprintf("Phase: %s", h.LastRun.Phase),
)
}
}
if s.debug {
_, _ = fmt.Fprintln(out, "USER-SUPPLIED VALUES:")
err := output.EncodeYAML(out, rel.Config)
if err != nil {
return err
}
// Print an extra newline
_, _ = fmt.Fprintln(out)
cfg, err := util.CoalesceValues(rel.Chart, rel.Config)
if err != nil {
return err
}
_, _ = fmt.Fprintln(out, "COMPUTED VALUES:")
err = output.EncodeYAML(out, cfg.AsMap())
if err != nil {
return err
}
// Print an extra newline
_, _ = fmt.Fprintln(out)
}
if strings.EqualFold(rel.Info.Description, "Dry run complete") || s.debug {
_, _ = fmt.Fprintln(out, "HOOKS:")
for _, h := range rel.Hooks {
_, _ = fmt.Fprintf(out, "---\n# Source: %s\n%s\n", h.Path, h.Manifest)
}
_, _ = fmt.Fprintf(out, "MANIFEST:\n%s\n", rel.Manifest)
}
// Hide notes from output - option in install and upgrades
if !s.hideNotes && len(rel.Info.Notes) > 0 {
_, _ = fmt.Fprintf(out, "NOTES:\n%s\n", strings.TrimSpace(rel.Info.Notes))
}
return nil
}
func executionsByHookEvent(rel *releasev1.Release) map[releasev1.HookEvent][]*releasev1.Hook {
result := make(map[releasev1.HookEvent][]*releasev1.Hook)
for _, h := range rel.Hooks {
for _, e := range h.Events {
executions, ok := result[e]
if !ok {
executions = []*releasev1.Hook{}
}
result[e] = append(executions, h)
}
}
return result
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/dependency.go | pkg/cmd/dependency.go | /*
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 (
"io"
"path/filepath"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cmd/require"
)
const dependencyDesc = `
Manage the dependencies of a chart.
Helm charts store their dependencies in 'charts/'. For chart developers, it is
often easier to manage dependencies in 'Chart.yaml' which declares all
dependencies.
The dependency commands operate on that file, making it easy to synchronize
between the desired dependencies and the actual dependencies stored in the
'charts/' directory.
For example, this Chart.yaml declares two dependencies:
# Chart.yaml
dependencies:
- name: nginx
version: "1.2.3"
repository: "https://example.com/charts"
- name: memcached
version: "3.2.1"
repository: "https://another.example.com/charts"
The 'name' should be the name of a chart, where that name must match the name
in that chart's 'Chart.yaml' file.
The 'version' field should contain a semantic version or version range.
The 'repository' URL should point to a Chart Repository. Helm expects that by
appending '/index.yaml' to the URL, it should be able to retrieve the chart
repository's index. Note: 'repository' can be an alias. The alias must start
with 'alias:' or '@'.
Starting from 2.2.0, repository can be defined as the path to the directory of
the dependency charts stored locally. The path should start with a prefix of
"file://". For example,
# Chart.yaml
dependencies:
- name: nginx
version: "1.2.3"
repository: "file://../dependency_chart/nginx"
If the dependency chart is retrieved locally, it is not required to have the
repository added to helm by "helm add repo". Version matching is also supported
for this case.
`
const dependencyListDesc = `
List all of the dependencies declared in a chart.
This can take chart archives and chart directories as input. It will not alter
the contents of a chart.
This will produce an error if the chart cannot be loaded.
`
func newDependencyCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "dependency update|build|list",
Aliases: []string{"dep", "dependencies"},
Short: "manage a chart's dependencies",
Long: dependencyDesc,
Args: require.NoArgs,
}
cmd.AddCommand(newDependencyListCmd(out))
cmd.AddCommand(newDependencyUpdateCmd(cfg, out))
cmd.AddCommand(newDependencyBuildCmd(out))
return cmd
}
func newDependencyListCmd(out io.Writer) *cobra.Command {
client := action.NewDependency()
cmd := &cobra.Command{
Use: "list CHART",
Aliases: []string{"ls"},
Short: "list the dependencies for the given chart",
Long: dependencyListDesc,
Args: require.MaximumNArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
chartpath := "."
if len(args) > 0 {
chartpath = filepath.Clean(args[0])
}
return client.List(chartpath, out)
},
}
f := cmd.Flags()
f.UintVar(&client.ColumnWidth, "max-col-width", 80, "maximum column width for output table")
return cmd
}
func addDependencySubcommandFlags(f *pflag.FlagSet, client *action.Dependency) {
f.BoolVar(&client.Verify, "verify", false, "verify the packages against signatures")
f.StringVar(&client.Keyring, "keyring", defaultKeyring(), "keyring containing public keys")
f.BoolVar(&client.SkipRefresh, "skip-refresh", false, "do not refresh the local repository cache")
f.StringVar(&client.Username, "username", "", "chart repository username where to locate the requested chart")
f.StringVar(&client.Password, "password", "", "chart repository password where to locate the requested chart")
f.StringVar(&client.CertFile, "cert-file", "", "identify HTTPS client using this SSL certificate file")
f.StringVar(&client.KeyFile, "key-file", "", "identify HTTPS client using this SSL key file")
f.BoolVar(&client.InsecureSkipTLSVerify, "insecure-skip-tls-verify", false, "skip tls certificate checks for the chart download")
f.BoolVar(&client.PlainHTTP, "plain-http", false, "use insecure HTTP connections for the chart download")
f.StringVar(&client.CaFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle")
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/repo_add_test.go | pkg/cmd/repo_add_test.go | /*
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 (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"sigs.k8s.io/yaml"
"helm.sh/helm/v4/pkg/helmpath"
"helm.sh/helm/v4/pkg/helmpath/xdg"
"helm.sh/helm/v4/pkg/repo/v1"
"helm.sh/helm/v4/pkg/repo/v1/repotest"
)
func TestRepoAddCmd(t *testing.T) {
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/testserver/*.*"),
)
defer srv.Stop()
// A second test server is setup to verify URL changing
srv2 := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/testserver/*.*"),
)
defer srv2.Stop()
tmpdir := filepath.Join(t.TempDir(), "path-component.yaml/data")
if err := os.MkdirAll(tmpdir, 0o777); err != nil {
t.Fatal(err)
}
repoFile := filepath.Join(tmpdir, "repositories.yaml")
tests := []cmdTestCase{
{
name: "add a repository",
cmd: fmt.Sprintf("repo add test-name %s --repository-config %s --repository-cache %s", srv.URL(), repoFile, tmpdir),
golden: "output/repo-add.txt",
},
{
name: "add repository second time",
cmd: fmt.Sprintf("repo add test-name %s --repository-config %s --repository-cache %s", srv.URL(), repoFile, tmpdir),
golden: "output/repo-add2.txt",
},
{
name: "add repository different url",
cmd: fmt.Sprintf("repo add test-name %s --repository-config %s --repository-cache %s", srv2.URL(), repoFile, tmpdir),
wantError: true,
},
{
name: "add repository second time",
cmd: fmt.Sprintf("repo add test-name %s --repository-config %s --repository-cache %s --force-update", srv2.URL(), repoFile, tmpdir),
golden: "output/repo-add.txt",
},
}
runTestCmd(t, tests)
}
func TestRepoAdd(t *testing.T) {
ts := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/testserver/*.*"),
)
defer ts.Stop()
rootDir := t.TempDir()
repoFile := filepath.Join(rootDir, "repositories.yaml")
const testRepoName = "test-name"
o := &repoAddOptions{
name: testRepoName,
url: ts.URL(),
forceUpdate: false,
repoFile: repoFile,
}
t.Setenv(xdg.CacheHomeEnvVar, rootDir)
if err := o.run(io.Discard); err != nil {
t.Error(err)
}
f, err := repo.LoadFile(repoFile)
if err != nil {
t.Fatal(err)
}
if !f.Has(testRepoName) {
t.Errorf("%s was not successfully inserted into %s", testRepoName, repoFile)
}
idx := filepath.Join(helmpath.CachePath("repository"), helmpath.CacheIndexFile(testRepoName))
if _, err := os.Stat(idx); errors.Is(err, fs.ErrNotExist) {
t.Errorf("Error cache index file was not created for repository %s", testRepoName)
}
idx = filepath.Join(helmpath.CachePath("repository"), helmpath.CacheChartsFile(testRepoName))
if _, err := os.Stat(idx); errors.Is(err, fs.ErrNotExist) {
t.Errorf("Error cache charts file was not created for repository %s", testRepoName)
}
o.forceUpdate = true
if err := o.run(io.Discard); err != nil {
t.Errorf("Repository was not updated: %s", err)
}
if err := o.run(io.Discard); err != nil {
t.Errorf("Duplicate repository name was added")
}
}
func TestRepoAddCheckLegalName(t *testing.T) {
ts := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/testserver/*.*"),
)
defer ts.Stop()
defer resetEnv()()
const testRepoName = "test-hub/test-name"
rootDir := t.TempDir()
repoFile := filepath.Join(t.TempDir(), "repositories.yaml")
o := &repoAddOptions{
name: testRepoName,
url: ts.URL(),
forceUpdate: false,
repoFile: repoFile,
}
t.Setenv(xdg.CacheHomeEnvVar, rootDir)
wantErrorMsg := fmt.Sprintf("repository name (%s) contains '/', please specify a different name without '/'", testRepoName)
if err := o.run(io.Discard); err != nil {
if wantErrorMsg != err.Error() {
t.Fatalf("Actual error %s, not equal to expected error %s", err, wantErrorMsg)
}
} else {
t.Fatalf("expect reported an error.")
}
}
func TestRepoAddConcurrentGoRoutines(t *testing.T) {
const testName = "test-name"
repoFile := filepath.Join(t.TempDir(), "repositories.yaml")
repoAddConcurrent(t, testName, repoFile)
}
func TestRepoAddConcurrentDirNotExist(t *testing.T) {
const testName = "test-name-2"
repoFile := filepath.Join(t.TempDir(), "foo", "repositories.yaml")
repoAddConcurrent(t, testName, repoFile)
}
func TestRepoAddConcurrentNoFileExtension(t *testing.T) {
const testName = "test-name-3"
repoFile := filepath.Join(t.TempDir(), "repositories")
repoAddConcurrent(t, testName, repoFile)
}
func TestRepoAddConcurrentHiddenFile(t *testing.T) {
const testName = "test-name-4"
repoFile := filepath.Join(t.TempDir(), ".repositories")
repoAddConcurrent(t, testName, repoFile)
}
func repoAddConcurrent(t *testing.T, testName, repoFile string) {
t.Helper()
ts := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/testserver/*.*"),
)
defer ts.Stop()
var wg sync.WaitGroup
wg.Add(3)
for i := range 3 {
go func(name string) {
defer wg.Done()
o := &repoAddOptions{
name: name,
url: ts.URL(),
forceUpdate: false,
repoFile: repoFile,
}
if err := o.run(io.Discard); err != nil {
t.Error(err)
}
}(fmt.Sprintf("%s-%d", testName, i))
}
wg.Wait()
b, err := os.ReadFile(repoFile)
if err != nil {
t.Error(err)
}
var f repo.File
if err := yaml.Unmarshal(b, &f); err != nil {
t.Error(err)
}
var name string
for i := range 3 {
name = fmt.Sprintf("%s-%d", testName, i)
if !f.Has(name) {
t.Errorf("%s was not successfully inserted into %s: %s", name, repoFile, f.Repositories[0])
}
}
}
func TestRepoAddFileCompletion(t *testing.T) {
checkFileCompletion(t, "repo add", false)
checkFileCompletion(t, "repo add reponame", false)
checkFileCompletion(t, "repo add reponame https://example.com", false)
}
func TestRepoAddWithPasswordFromStdin(t *testing.T) {
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/testserver/*.*"),
repotest.WithMiddleware(repotest.BasicAuthMiddleware(t)),
)
defer srv.Stop()
defer resetEnv()()
in, err := os.Open("testdata/password")
if err != nil {
t.Errorf("unexpected error, got '%v'", err)
}
tmpdir := t.TempDir()
repoFile := filepath.Join(tmpdir, "repositories.yaml")
store := storageFixture()
const testName = "test-name"
const username = "username"
cmd := fmt.Sprintf("repo add %s %s --repository-config %s --repository-cache %s --username %s --password-stdin", testName, srv.URL(), repoFile, tmpdir, username)
var result string
_, result, err = executeActionCommandStdinC(store, in, cmd)
if err != nil {
t.Errorf("unexpected error, got '%v'", err)
}
if !strings.Contains(result, fmt.Sprintf("\"%s\" has been added to your repositories", testName)) {
t.Errorf("Repo was not successfully added. Output: %s", result)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/get_manifest.go | pkg/cmd/get_manifest.go | /*
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 (
"fmt"
"io"
"log"
"github.com/spf13/cobra"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cmd/require"
"helm.sh/helm/v4/pkg/release"
)
var getManifestHelp = `
This command fetches the generated manifest for a given release.
A manifest is a YAML-encoded representation of the Kubernetes resources that
were generated from this release's chart(s). If a chart is dependent on other
charts, those resources will also be included in the manifest.
`
func newGetManifestCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
client := action.NewGet(cfg)
cmd := &cobra.Command{
Use: "manifest RELEASE_NAME",
Short: "download the manifest for a named release",
Long: getManifestHelp,
Args: require.ExactArgs(1),
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return noMoreArgsComp()
}
return compListReleases(toComplete, args, cfg)
},
RunE: func(_ *cobra.Command, args []string) error {
res, err := client.Run(args[0])
if err != nil {
return err
}
rac, err := release.NewAccessor(res)
if err != nil {
return err
}
fmt.Fprintln(out, rac.Manifest())
return nil
},
}
cmd.Flags().IntVar(&client.Version, "revision", 0, "get the named release with revision")
err := cmd.RegisterFlagCompletionFunc("revision", func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 1 {
return compListRevisions(toComplete, cfg, args[0])
}
return nil, cobra.ShellCompDirectiveNoFileComp
})
if err != nil {
log.Fatal(err)
}
return cmd
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/registry_login.go | pkg/cmd/registry_login.go | /*
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 (
"bufio"
"errors"
"fmt"
"io"
"log/slog"
"os"
"strings"
"github.com/moby/term"
"github.com/spf13/cobra"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/cmd/require"
)
const registryLoginDesc = `
Authenticate to a remote registry.
For example for Github Container Registry:
echo "$GITHUB_TOKEN" | helm registry login ghcr.io -u $GITHUB_USER --password-stdin
`
type registryLoginOptions struct {
username string
password string
passwordFromStdinOpt bool
certFile string
keyFile string
caFile string
insecure bool
plainHTTP bool
}
func newRegistryLoginCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {
o := ®istryLoginOptions{}
cmd := &cobra.Command{
Use: "login [host]",
Short: "login to a registry",
Long: registryLoginDesc,
Args: require.MinimumNArgs(1),
ValidArgsFunction: cobra.NoFileCompletions,
RunE: func(_ *cobra.Command, args []string) error {
hostname := args[0]
username, password, err := getUsernamePassword(o.username, o.password, o.passwordFromStdinOpt)
if err != nil {
return err
}
return action.NewRegistryLogin(cfg).Run(out, hostname, username, password,
action.WithCertFile(o.certFile),
action.WithKeyFile(o.keyFile),
action.WithCAFile(o.caFile),
action.WithInsecure(o.insecure),
action.WithPlainHTTPLogin(o.plainHTTP))
},
}
f := cmd.Flags()
f.StringVarP(&o.username, "username", "u", "", "registry username")
f.StringVarP(&o.password, "password", "p", "", "registry password or identity token")
f.BoolVarP(&o.passwordFromStdinOpt, "password-stdin", "", false, "read password or identity token from stdin")
f.BoolVarP(&o.insecure, "insecure", "", false, "allow connections to TLS registry without certs")
f.StringVar(&o.certFile, "cert-file", "", "identify registry client using this SSL certificate file")
f.StringVar(&o.keyFile, "key-file", "", "identify registry client using this SSL key file")
f.StringVar(&o.caFile, "ca-file", "", "verify certificates of HTTPS-enabled servers using this CA bundle")
f.BoolVar(&o.plainHTTP, "plain-http", false, "use insecure HTTP connections for the chart upload")
return cmd
}
// Adapted from https://github.com/oras-project/oras
func getUsernamePassword(usernameOpt string, passwordOpt string, passwordFromStdinOpt bool) (string, string, error) {
var err error
username := usernameOpt
password := passwordOpt
if passwordFromStdinOpt {
passwordFromStdin, err := io.ReadAll(os.Stdin)
if err != nil {
return "", "", err
}
password = strings.TrimSuffix(string(passwordFromStdin), "\n")
password = strings.TrimSuffix(password, "\r")
} else if password == "" {
if username == "" {
username, err = readLine("Username: ", false)
if err != nil {
return "", "", err
}
username = strings.TrimSpace(username)
}
if username == "" {
password, err = readLine("Token: ", true)
if err != nil {
return "", "", err
} else if password == "" {
return "", "", errors.New("token required")
}
} else {
password, err = readLine("Password: ", true)
if err != nil {
return "", "", err
} else if password == "" {
return "", "", errors.New("password required")
}
}
} else {
slog.Warn("using --password via the CLI is insecure. Use --password-stdin")
}
return username, password, nil
}
// Copied/adapted from https://github.com/oras-project/oras
func readLine(prompt string, silent bool) (string, error) {
fmt.Print(prompt)
if silent {
fd := os.Stdin.Fd()
state, err := term.SaveState(fd)
if err != nil {
return "", err
}
term.DisableEcho(fd, state)
defer term.RestoreTerminal(fd, state)
}
reader := bufio.NewReader(os.Stdin)
line, _, err := reader.ReadLine()
if err != nil {
return "", err
}
if silent {
fmt.Println()
}
return string(line), nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cmd/release_testing_test.go | pkg/cmd/release_testing_test.go | /*
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 (
"bytes"
"io"
"strings"
"testing"
"helm.sh/helm/v4/pkg/action"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
rcommon "helm.sh/helm/v4/pkg/release/common"
release "helm.sh/helm/v4/pkg/release/v1"
)
func TestReleaseTestingCompletion(t *testing.T) {
checkReleaseCompletion(t, "test", false)
}
func TestReleaseTestingFileCompletion(t *testing.T) {
checkFileCompletion(t, "test", false)
checkFileCompletion(t, "test myrelease", false)
}
func TestReleaseTestNotesHandling(t *testing.T) {
// Test that ensures notes behavior is correct for test command
// This is a simpler test that focuses on the core functionality
rel := &release.Release{
Name: "test-release",
Namespace: "default",
Info: &release.Info{
Status: rcommon.StatusDeployed,
Notes: "Some important notes that should be hidden by default",
},
Chart: &chart.Chart{Metadata: &chart.Metadata{Name: "test", Version: "1.0.0"}},
}
// Set up storage
store := storageFixture()
store.Create(rel)
// Set up action configuration properly
actionConfig := &action.Configuration{
Releases: store,
KubeClient: &kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}},
Capabilities: common.DefaultCapabilities,
}
// Test the newReleaseTestCmd function directly
var buf1 bytes.Buffer
// Test 1: Default behavior (should hide notes)
cmd1 := newReleaseTestCmd(actionConfig, &buf1)
cmd1.SetArgs([]string{"test-release"})
err1 := cmd1.Execute()
if err1 != nil {
t.Fatalf("Unexpected error for default test: %v", err1)
}
output1 := buf1.String()
if strings.Contains(output1, "NOTES:") {
t.Errorf("Expected notes to be hidden by default, but found NOTES section in output: %s", output1)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.