Skip to content

Commit

Permalink
Add gc command
Browse files Browse the repository at this point in the history
  • Loading branch information
mgax committed Dec 31, 2023
1 parent 9fca263 commit 8a4c202
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
6 changes: 6 additions & 0 deletions opslib/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import click

from .operations import apply, print_report
from .state import run_gc

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -105,6 +106,11 @@ def ls():
def shell():
return interact(str(component), dict(self=component))

@cli.command()
@click.option("-n", "--dry-run", is_flag=True)
def gc(dry_run):
run_gc(component, dry_run=dry_run)

@cli.forward_command("component")
@click.pass_context
@click.argument("path")
Expand Down
26 changes: 26 additions & 0 deletions opslib/state.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import logging
import shutil

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -84,3 +85,28 @@ def __iter__(self):
class JsonState:
def __get__(self, obj, objtype=None):
return ComponentJsonState(obj)


def run_gc(component, dry_run=False):
child_names = {child._meta.name for child in component}
statedir_prefix = component._meta.statedir.prefix

def unexpected(item):
if item.name.startswith("_"):
return False

if not item.is_dir():
return False

return item.name not in child_names

for item in statedir_prefix.iterdir():
if unexpected(item):
print(item)
if dry_run:
continue

shutil.rmtree(item)

for child in component:
run_gc(child, dry_run=dry_run)

0 comments on commit 8a4c202

Please sign in to comment.