From 046178e55f72ed9db7cf5898d3be91b0112ab94f Mon Sep 17 00:00:00 2001 From: Matthew Heon Date: Tue, 27 Aug 2019 15:25:54 -0400 Subject: Add function for looking up volumes by partial name This isn't included in Docker, but seems handy enough. Use the new API for 'volume rm' and 'volume inspect'. Fixes #3891 Signed-off-by: Matthew Heon --- libpod/in_memory_state.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'libpod/in_memory_state.go') diff --git a/libpod/in_memory_state.go b/libpod/in_memory_state.go index 280ae5f5c..a008fcb39 100644 --- a/libpod/in_memory_state.go +++ b/libpod/in_memory_state.go @@ -459,6 +459,41 @@ func (s *InMemoryState) Volume(name string) (*Volume, error) { return vol, nil } +// LookupVolume finds a volume from an unambiguous partial ID. +func (s *InMemoryState) LookupVolume(name string) (*Volume, error) { + if name == "" { + return nil, define.ErrEmptyID + } + + vol, ok := s.volumes[name] + if ok { + return vol, nil + } + + // Alright, we've failed to find by full name. Now comes the expensive + // part. + // Loop through all volumes and look for matches. + var ( + foundMatch bool + candidate *Volume + ) + for volName, vol := range s.volumes { + if strings.HasPrefix(volName, name) { + if foundMatch { + return nil, errors.Wrapf(define.ErrVolumeExists, "more than one result for volume name %q", name) + } + candidate = vol + foundMatch = true + } + } + + if !foundMatch { + return nil, errors.Wrapf(define.ErrNoSuchVolume, "no volume with name %q found", name) + } + + return candidate, nil +} + // HasVolume checks if a volume with the given name is present in the state func (s *InMemoryState) HasVolume(name string) (bool, error) { if name == "" { -- cgit v1.2.3-54-g00ecf