Skip to content

Commit

Permalink
Provide API to remove containers by name (#152)
Browse files Browse the repository at this point in the history
Signed-off-by: Andrea Panattoni <panattoni.andrea@gmail.com>
  • Loading branch information
zeeke authored and aeneasr committed Jan 14, 2019
1 parent df4d49d commit f76851e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
28 changes: 28 additions & 0 deletions dockertest.go
Expand Up @@ -326,6 +326,34 @@ func (d *Pool) Run(repository, tag string, env []string) (*Resource, error) {
return d.RunWithOptions(&RunOptions{Repository: repository, Tag: tag, Env: env})
}

// RemoveContainerByName find a container with the given name and removes it if present
func (d *Pool) RemoveContainerByName(containerName string) error {
containers, err := d.Client.ListContainers(dc.ListContainersOptions{
All: true,
Filters: map[string][]string{
"name": []string{containerName},
},
})
if err != nil {
return errors.Wrapf(err, "Error while listing containers with name %s", containerName)
}

if len(containers) == 0 {
return nil
}

err = d.Client.RemoveContainer(dc.RemoveContainerOptions{
ID: containers[0].ID,
Force: true,
RemoveVolumes: true,
})
if err != nil {
return errors.Wrapf(err, "Error while removing container with name %s", containerName)
}

return nil
}

// Purge removes a container and linked volumes from docker.
func (d *Pool) Purge(r *Resource) error {
if err := d.Client.RemoveContainer(dc.RemoveContainerOptions{ID: r.Container.ID, Force: true, RemoveVolumes: true}); err != nil {
Expand Down
22 changes: 22 additions & 0 deletions dockertest_test.go
Expand Up @@ -182,3 +182,25 @@ func TestContainerWithShMzSize(t *testing.T) {

require.Nil(t, pool.Purge(resource))
}

func TestRemoveContainerByName(t *testing.T) {
_, err := pool.RunWithOptions(
&RunOptions{
Name: "db",
Repository: "postgres",
Tag: "9.5",
})
require.Nil(t, err)

err = pool.RemoveContainerByName("db")
require.Nil(t, err)

resource, err := pool.RunWithOptions(
&RunOptions{
Name: "db",
Repository: "postgres",
Tag: "9.5",
})
require.Nil(t, err)
require.Nil(t, pool.Purge(resource))
}

0 comments on commit f76851e

Please sign in to comment.