Skip to content

Instantly share code, notes, and snippets.

@anuar2k
Created June 21, 2023 21:39
Show Gist options
  • Save anuar2k/3eb36effee2c2bea926063e0f30e388c to your computer and use it in GitHub Desktop.
Save anuar2k/3eb36effee2c2bea926063e0f30e388c to your computer and use it in GitHub Desktop.
import os
import glob
import xml.etree.ElementTree as ET
def create_group_file_structure(file_list):
group_structure = {}
for file_path in file_list:
# Normalize the file path and split it into directories and the filename
file_path = os.path.normpath(file_path)
directories, filename = os.path.split(file_path)
# Split the directories into individual group names
groups = directories.split(os.path.sep)
# Create the nested group structure
current_group = group_structure
for group in groups:
current_group = current_group.setdefault(group, {})
# Add the file to the final group
current_group[filename] = file_path
return group_structure
def update_ewp_file(ewp_file, group_structure):
# Parse the existing .ewp file
tree = ET.parse(ewp_file)
root = tree.getroot()
# Find the <group> element in the XML tree
group_element = root.find(".//group")
if group_element is None:
group_element = ET.SubElement(root, "group")
# Recursively add groups and files to the XML tree
add_groups_to_ewp(group_structure, group_element)
# Save the updated .ewp file
tree.write(ewp_file, encoding="UTF-8", xml_declaration=True)
def add_groups_to_ewp(group_structure, parent_element):
for group_name, files_or_subgroups in group_structure.items():
# Create a <group> element
group_element = ET.SubElement(parent_element, "group")
group_element.set("name", group_name)
for name, path_or_subgroup in files_or_subgroups.items():
if isinstance(path_or_subgroup, dict):
# If the value is a dictionary, it represents a subgroup
add_groups_to_ewp({name: path_or_subgroup}, group_element)
else:
# Otherwise, it represents a file
file_element = ET.SubElement(group_element, "file")
file_element.set("name", name)
# Example usage
glob_pattern = "path/to/files/*.c"
file_list = glob.glob(glob_pattern)
group_structure = create_group_file_structure(file_list)
ewp_file_path = "path/to/project.ewp"
update_ewp_file(ewp_file_path, group_structure)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment