From ebf051fe3f0b9d83aa673dd2687781a690efc8f4 Mon Sep 17 00:00:00 2001 From: Lertsenem Date: Sat, 15 Aug 2015 18:42:07 +0200 Subject: [PATCH] Adding META management for 'add' command --- persoconf/main.py | 50 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/persoconf/main.py b/persoconf/main.py index 0645ba0..6227082 100755 --- a/persoconf/main.py +++ b/persoconf/main.py @@ -2,6 +2,7 @@ import argparse import logging +import json import os, os.path import shutil @@ -30,6 +31,14 @@ def yes_no_question(question="Yes or no?", default=False): return default +def contractuser(path): + home = os.path.expanduser("~") + + if path.startswith(home): + return path.replace(home, "~", 1) # Replace only one instance: the first one + else: + return path + # ARGPARSE ######################################## # Argument parsing using argparse @@ -108,8 +117,8 @@ if not os.path.isdir(args.rootdir): print("New persoconf directory created at '%s'" % arg.rootdir) - -# SWITCH COMMAND +# ADD COMMAND +######################################## if args.command == "add": # Check (and create) the app directory @@ -143,9 +152,30 @@ if args.command == "add": confpath = appdir + "/" + confname - # Check that the file is really new - absconf = os.path.abspath(os.path.expanduser(args.conf)) + # Load app META file + metafile = appdir + "/" + args.metafile + try: + appmeta = json.load( open(metafile) ) + except FileNotFoundError: + log.info("Metafile %s does not exist for app %s" % (args.metafile, args.app)) + appmeta = { "name" : args.app, "depends": {}, "files": {} } + + # Check that the file is really new + absconf = contractuser( os.path.abspath(os.path.expanduser(args.conf)) ) + + try: + destslist = {} + + for (fname,finfo) in appmeta["files"].items(): + destslist[finfo["dest"]] = fname + except KeyError: + log.error("Malformed metafile %s in app %s" % (args.metafile, args.app) ) + exit(1) + + if absconf in destslist: + log.error("File %s already exists as %s in app %s" % (absconf, destslist[absconf], args.app)) + exit(1) # Copy the conf dir try: @@ -178,18 +208,24 @@ if args.command == "add": log.info("Copying conf file") shutil.copyfile(args.conf, confpath) - print("New conf file '%s' associated with app '%s'" % (confname, args.app)) + log.info("New conf file '%s' associated with app '%s'" % (confname, args.app)) except PermissionError: log.error("Unable to write on '%s', please check permissions" % confpath) exit() + # Add the file to META + # Update META data + log.debug("adding meta data for %s in %s" % (confname, args.app)) + appmeta["files"][confname] = { "dest": absconf } - - # TODO add the file to META + # Write to the metafile + log.debug("Wrinting to metafile") + json.dump(appmeta, open(metafile, 'w')) +######################################## print(args)