Created
August 22, 2018 04:36
-
-
Save yang-ling/288013cf87231ffc08e6c812e8b9e056 to your computer and use it in GitHub Desktop.
Check and clean disabled snaps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
""" | |
Check any disabled snap. | |
Remove disabled snap. | |
""" | |
import argparse | |
import subprocess | |
def convert_snap_info(line): | |
"""Convert string line to snap info dict | |
Args: | |
line: one line of snap list --all output | |
Returns: | |
snap info dict, keys: name, rev, notes | |
""" | |
items = [item.strip() for item in line.split(' ') if item.strip()] | |
return {'name': items[0], 'rev': items[2], 'notes': items[5]} | |
def check_disabled_snap(): | |
""" Check if any disabled snap """ | |
disabled_snap_infors = get_disabled_snaps() | |
if disabled_snap_infors: | |
raise ValueError( | |
"Found disabled snap! Please remove {}".format(disabled_snap_infors)) | |
def get_disabled_snaps(): | |
""" Get disabled snap """ | |
result = subprocess.run(['snap', 'list', '--all'], | |
stdout=subprocess.PIPE, stderr=subprocess.PIPE, | |
check=True, encoding='utf-8') | |
lines = [item for item in result.stdout.split('\n') if item] | |
lines.pop(0) | |
snap_infors = [item for item in map( | |
convert_snap_info, lines) if item['notes'].find('disabled') >= 0] | |
return snap_infors | |
def remove_disabled_snap(): | |
""" Remove disabled snap """ | |
disabled_snap_infors = get_disabled_snaps() | |
if not disabled_snap_infors: | |
return | |
for item in disabled_snap_infors: | |
subprocess.run(['sudo', '/usr/bin/snap', 'remove', | |
"--revision={}".format(item['rev']), item['name']], | |
check=True, encoding='utf-8') | |
def main(): | |
""" Main Function """ | |
parser = argparse.ArgumentParser(description="Clean Snaps") | |
parser.add_argument("-r", "--remove", dest="is_remove", | |
action="store_true", help="Remove disabled snap") | |
args = parser.parse_args() | |
if args.is_remove: | |
remove_disabled_snap() | |
else: | |
check_disabled_snap() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment