Skip to content

Instantly share code, notes, and snippets.

@mirhec
Created June 20, 2019 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mirhec/8a2362f22c66e5897bf9228747481e41 to your computer and use it in GitHub Desktop.
Save mirhec/8a2362f22c66e5897bf9228747481e41 to your computer and use it in GitHub Desktop.
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