Created
June 20, 2019 09:53
-
-
Save mirhec/8a2362f22c66e5897bf9228747481e41 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import click | |
import os | |
import glob | |
from configparser import ConfigParser | |
import re | |
@click.group() | |
def cli(): | |
pass | |
@click.command() | |
@click.option('--input-folder') | |
@click.option('--source-ini-file') | |
@click.option('--section-to-copy') | |
@click.option('--out-folder', default='out') | |
def copy_section(input_folder, source_ini_file, section_to_copy, out_folder): | |
if not os.path.exists(input_folder): | |
raise Exception('Cannot find input_folder %s' % input_folder) | |
if not os.path.exists(source_ini_file): | |
raise Exception('Cannot find source_ini_file %s' % source_ini_file) | |
if not os.path.exists(out_folder): | |
os.makedirs(out_folder) | |
template = ConfigParser() | |
# make ConfigParser work case sensitive, see http://stackoverflow.com/questions/19359556/configparser-reads-capital-keys-and-make-them-lower-case | |
template.optionxform = str | |
template.read(source_ini_file) | |
if not template.has_section(section_to_copy): | |
raise Exception('Source INI file %s has no section %s!' % (source_ini_file, section_to_copy)) | |
for file in os.listdir(input_folder): | |
fullpath = os.path.join(input_folder, file) | |
if not os.path.isfile(fullpath) or file[-4:] != '.ini': | |
continue | |
ini = ConfigParser() | |
ini.optionxform = str | |
ini.read(fullpath) | |
if ini.has_section(section_to_copy): | |
print('overwrite section in %s' % file) | |
else: | |
print('create section in %s' % file) | |
ini[section_to_copy] = template[section_to_copy] | |
with open(os.path.join(out_folder, file), 'w') as out: | |
ini.write(out) | |
if __name__ == '__main__': | |
cli.add_command(copy_section) | |
cli() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment