persoconf/commands/update.py

140 lines
5.2 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import utils
from metafile import Metafile, MalformedMetafileError
# -----------------------------------------------------------------------------
def init(parser):
parser.add_argument( "app",
type=str,
nargs="?",
help="The app to update" )
parser.add_argument( "files",
type=str,
nargs="*",
default=[],
help="The files to update ; default to all " \
"added files" )
# -----------------------------------------------------------------------------
def run(args, persoconf, logger):
# app == None => update all apps
apps_to_update = {}
if args.app is None:
apps_to_update = persoconf.list_apps(logger=logger)
else:
try:
appmeta = Metafile(
json_path = os.path.join( persoconf.path,
args.app,
persoconf.metafile )
)
apps_to_update[appmeta.name] = appmeta
except FileNotFoundError:
logger.error( "Metafile %s does not exist for app %s"
% (persoconf.metafile, args.app) )
exit(1)
except MalformedMetafileError:
logger.error( "Malformed metafile %s in app %s"
% (persoconf.metafile, args.app) )
exit(1)
for app in apps_to_update:
if args.files != []:
dstdic = apps_to_update[app].get_files_dst2src() # Get that here
# for optimization
# 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.
for f in args.files:
# 1) It's probably a confname
if f in apps_to_update[app].files:
if utils.copy_file_or_directory(
logger,
path_dst = os.path.join( persoconf.path,
app,
f ),
path_src = apps_to_update[app].files[f]["dest"]
):
logger.info
(
"Updated %s from %s"
% ( f, apps_to_update[app].files[f]["dest"])
)
else:
logger.warning
(
"Failed to update %s from %s ; ignoring"
% ( f, apps_to_update[app].files[f]["dest"])
)
continue
# 2) If not, it must be a real filename
else:
absf = contractuser(os.path.abspath(os.path.expanduser(f)))
if absf in dstdic:
if utils.copy_file_or_directory(
logger,
path_dst = os.path.join( persoconf.path,
app,
dstdic[absf] ),
path_src = absf
):
logger.info( "Updated %s from %s"
% (dstdic[absf], absf) )
else:
logger.warning( "Failed to update %s from %s ; " \
"ignoring"
% (dstdic[absf], absf) )
continue
# 3) Otherwise, no idea what it is
else:
logger.warning( "Cannot find file %s in app data; " \
"ignoring it"
% f )
continue
# If they were no 'file' args, it means we need to update all files in
# the app
else:
for f in apps_to_update[app].files:
if utils.copy_file_or_directory(
logger,
path_dst = os.path.join( persoconf.path,
app,
f ),
path_src = apps_to_update[app].files[f]["dest"]
):
logger.info( "Updated %s from %s"
% (f, apps_to_update[app].files[f]["dest"]) )
else:
logger.warning( "Failed to update %s from %s ; ignoring"
% ( f,
apps_to_update[app].files[f]["dest"] )
)