persoconf/commands/delete.py

129 lines
4.9 KiB
Python
Raw Normal View History

2015-12-07 12:11:35 -05:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import shutil
import utils
from metafile import Metafile, MalformedMetafileError
# --------------------------------------
def init(parser):
parser.add_argument( "app" ,
type=str ,
help="The app to delete, or the app to delete a " \
"conf file from" )
parser.add_argument( "files" ,
nargs="*" ,
type=str ,
help="The conf files or directories to delete from " \
"the app" )
parser.add_argument( "--force-yes", "-y" ,
action="store_true" ,
help="Don't ask silly questions" )
# --------------------------------------
def run(args, persoconf, logger):
# Does this app really exists ?
try:
appmeta = Metafile( json_path = os.path.join( persoconf.path ,
args.app ,
persoconf.metafile ) )
except FileNotFoundError:
logger.error( "App %s does not seem to exist" % args.app )
exit(1)
except MalformedMetafileError:
logger.error( "Failed to load metafile from app %s" % args.app )
exit(1)
# Does the user want to remove files or the entire app ?
if args.files == []:
# Delete the entire app
if ( args.force_yes
or utils.yes_no_question("Really delete app '%s'?" % appmeta.name)
):
shutil.rmtree( os.path.join(persoconf.path, appmeta.name) )
logger.warning("App %s was deleted" % appmeta.name)
else:
logger.warning("Nothing was deleted")
exit(0)
else:
# Delete all required files (or directories)
if ( not args.force_yes
and not utils.yes_no_question(
"Delete all files from following list: %s from app %s?"
% (str(args.files),appmeta.name)
2015-12-07 12:19:19 -05:00
)
2015-12-07 12:11:35 -05:00
):
logger.warning("Nothing was deleted")
exit(0)
# The filenames can be confnames or real files names. For each we'll
# assume first that it's a confname, then that it's a file name if that
# fails.
dstdic = appmeta.get_files_dst2src() # Get that here for optimization
for f in args.files:
# 1) It's probably a confname
if f in appmeta.files:
if utils.delete_file_or_dir(
logger = logger ,
path = os.path.join(persoconf.path,
appmeta.name ,
f )
):
# File deleted, let's delete the entry in Metafile
appmeta.del_file(f)
appmeta.save()
else:
logger.warning( "Something wrong occured while deleting " \
"file %s"
% f )
continue
# 2) If not, it must be a real filename
else:
absf = utils.contractuser(
os.path.abspath(os.path.expanduser(f))
)
if absf in dstdic:
if delete_file_or_dir( logger = logger,
path = os.path.join(
persoconf.path,
appmeta.name ,
dstdir[absf]
)
):
# File deleted, let's delete the entry in Metafile
appmeta.del_file(dstdir[absf])
appmeta.save()
else:
logger.warning( "Something wrong occured while " \
"deleting file %s"
% f )
continue
# 3) Otherwise, no idea what it is
else:
logger.warning( "Cannot find file %s in app %s data; " \
"ignoring it"
% (f, appmeta.name) )
continue