mmuazam98 / dockclean

DockClean is a simple Go-based tool that cleans up unused Docker images from your system.
MIT License
4 stars 4 forks source link

feat : Remove Images Associated with Stopped Containers (Issue : #4) #10

Closed deexithparand closed 1 month ago

deexithparand commented 1 month ago

Code Updates

Implementation Details

The function first lists all Docker images and initializes them as "unreferenced". It then lists all containers and updates the state of each image based on its associated containers:

Images marked for potential removal are then removed using the Docker API. After successful image removal, associated stopped containers are also removed.

Purpose of This Functionality

This ensures that even though the images are deleted, the associated stopped containers are not left behind. If the stopped containers remain without their associated images, it could cause errors during future runs of the --remove-stopped command, such as "the associated image of the stopped container is not present." This functionality prevents those errors by cleaning up both the images and their stopped containers together.

Tested Example image

mmuazam98 commented 1 month ago

@deexithparand

Thanks for your contribution! The current implementation works, but we can refactor it to improve maintainability and modularity. Instead of passing the Docker client around as a parameter, we can encapsulate the client in a struct and add methods to that struct. This will clean up the main logic and make it easier to extend the functionality in the future.

Here’s what I suggest:

I can push an example refactor if you'd like! 😄

mmuazam98 commented 1 month ago
type DockerClient struct {
    cli *client.Client
}

func (d *DockerClient) RemoveUnusedImages() {...}

func (d *DockerClient) CleanupStoppedContainerImages() {...}

func (d *DockerClient) PrintUnusedImages() {...}
deexithparand commented 1 month ago

Hi @mmuazam98, I've updated the code as requested and also modified the folder structure little bit to add more best practices. Please check and merge the PR if its satisfactory.

mmuazam98 commented 1 month ago

@deexithparand Looks good mostly. Have you tested all the scenarios?

deexithparand commented 1 month ago

@mmuazam98 after refactoring, I've tested all the usecases which were previously tested for the old code. Works fine for me.