container: deprecate IsValidStateString

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn
2025-05-12 18:50:32 +02:00
parent e477df3b31
commit 44b653ef99
5 changed files with 58 additions and 35 deletions

View File

@@ -1,5 +1,10 @@
package container
import (
"fmt"
"strings"
)
// ContainerState is a string representation of the container's current state.
//
// It currently is an alias for string, but may become a distinct type in the future.
@@ -15,6 +20,21 @@ const (
StateDead ContainerState = "dead" // StateDead indicates that the container failed to be deleted. Containers in this state are attempted to be cleaned up when the daemon restarts.
)
var validStates = []ContainerState{
StateCreated, StateRunning, StatePaused, StateRestarting, StateRemoving, StateExited, StateDead,
}
// ValidateContainerState checks if the provided string is a valid
// container [ContainerState].
func ValidateContainerState(s ContainerState) error {
switch s {
case StateCreated, StateRunning, StatePaused, StateRestarting, StateRemoving, StateExited, StateDead:
return nil
default:
return errInvalidParameter{error: fmt.Errorf("invalid value for state (%s): must be one of %s", s, strings.Join(validStates, ", "))}
}
}
// StateStatus is used to return container wait results.
// Implements exec.ExitCode interface.
// This type is needed as State include a sync.Mutex field which make

View File

@@ -0,0 +1,33 @@
package container
import (
"testing"
"gotest.tools/v3/assert"
)
func TestValidateContainerState(t *testing.T) {
tests := []struct {
state ContainerState
expectedErr string
}{
{state: StatePaused},
{state: StateRestarting},
{state: StateRunning},
{state: StateDead},
{state: StateCreated},
{state: StateExited},
{state: StateRemoving},
{state: "invalid-state-string", expectedErr: `invalid value for state (invalid-state-string): must be one of created, running, paused, restarting, removing, exited, dead`},
}
for _, tc := range tests {
t.Run(tc.state, func(t *testing.T) {
err := ValidateContainerState(tc.state)
if tc.expectedErr == "" {
assert.NilError(t, err)
} else {
assert.Error(t, err, tc.expectedErr)
}
})
}
}