我有多个JSON文件与我的Python PyPI package打包在一起。这些JSON文件从源分发复制到用户主目录下的.ec2mc /目录作为配置文件。顶级配置JSON文件(aws_setup.json)旨在由用户修改。
我怎样才能设置它以便覆盖旧的配置版本,除非用户对配置进行了自己的修改?
我目前的设置是将版本(int)和Protect(bool)密钥添加到aws_setup.json,版本密钥用于更新分发时更新配置,而Protect密钥用于阻止配置的用户从被覆盖。逻辑如下:
# The config's aws_setup.json must have the "Protect" and "Version" keys
if not all(key in config_aws_setup for key in ("Protect", "Version")):
cp_aws_setup_to_config(aws_setup_src_dir)
# If the "Protect" key has been set to True, prevent overwriting aws_setup
elif config_aws_setup["Protect"]:
pass
# Version can be set to 0 during development for constant refreshing
elif source_aws_setup["Version"] == 0:
cp_aws_setup_to_config(aws_setup_src_dir)
# Update if aws_setup_src has larger version number
elif source_aws_setup["Version"] > config_aws_setup["Version"]:
cp_aws_setup_to_config(aws_setup_src_dir)
cp_aws_setup_to_config函数用分发版本覆盖配置:
def cp_aws_setup_to_config(aws_setup_src_dir):
if os.path.isdir(config.AWS_SETUP_DIR):
shutil.rmtree(config.AWS_SETUP_DIR)
shutil.copytree(aws_setup_src_dir, config.AWS_SETUP_DIR)
虽然它有效但我觉得这个设置有点复杂,并且想要一种更简单的方法来达到同样的效果。
答案 0 :(得分:0)
分发的模板配置和用户的配置可以与文件比较进行比较,因为它们同时存在于同一系统中。 filecmp的cmpfiles非常适用于此,因为它可以比较类似目录结构中的文件。
def recursive_cmpfiles(src_dir, dest_dir):
"""wrapper for filecmp.cmpfiles, which recursively finds src_dir's files"""
prefix_len = len(src_dir.parts)
cmp_files = []
for path, _, files in os.walk(src_dir):
for f in files:
cmp_files.append(Path(*(Path(path) / f).parts[prefix_len:]))
return filecmp.cmpfiles(src_dir, dest_dir, cmp_files, shallow=False)
# If 'Modified' key is True, prevent overwriting config's aws_setup
if config_aws_setup['Modified'] is False:
diffs = os2.recursive_cmpfiles(aws_setup_dir_src, aws_setup_dir_dest)
# If source and dest aws_setup differ, overwrite dest aws_setup
# If dest aws_setup missing files, overwrite dest aws_setup
if diffs[1] or diffs[2]:
cp_aws_setup_to_config(aws_setup_dir_src)
这消除了对Version键的需要,尽管' Protect' (现在'已修改')密钥仍在使用。