Closed deexithparand closed 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:
DockerClient
struct that holds the Docker client. (Similar to what I have done)RemoveUnusedImages
, CleanupStoppedContainerImages
, and PrintUnusedImages
on this struct.I can push an example refactor if you'd like! 😄
type DockerClient struct {
cli *client.Client
}
func (d *DockerClient) RemoveUnusedImages() {...}
func (d *DockerClient) CleanupStoppedContainerImages() {...}
func (d *DockerClient) PrintUnusedImages() {...}
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.
@deexithparand Looks good mostly. Have you tested all the scenarios?
@mmuazam98 after refactoring, I've tested all the usecases which were previously tested for the old code. Works fine for me.
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