|
import glob |
|
import os |
|
import xml.etree.ElementTree as ET |
|
from xml.dom import minidom |
|
|
|
|
|
ENCODING = 'utf-8' |
|
|
|
|
|
def parse_and_get_ns(file): |
|
events = "start", "start-ns" |
|
root = None |
|
ns = {} |
|
for event, elem in ET.iterparse(file, events): |
|
if event == "start-ns": |
|
if elem[0] in ns and ns[elem[0]] != elem[1]: |
|
# NOTE: It is perfectly valid to have the same prefix refer |
|
# to different URI namespaces in different parts of the |
|
# document. This exception serves as a reminder that this |
|
# solution is not robust. Use at your own peril. |
|
raise KeyError("Duplicate prefix with different URI found.") |
|
ns[elem[0]] = "{%s}" % elem[1] |
|
elif event == "start": |
|
if root is None: |
|
root = elem |
|
return ET.ElementTree(root), ns |
|
|
|
|
|
def get_library_names(file): |
|
tree, ns = parse_and_get_ns(file) |
|
prefix = ns[''] if '' in ns else '' |
|
|
|
group_tag_name = '%sItemGroup' % prefix |
|
reference_tag_name = '%sReference' % prefix |
|
|
|
root = tree.getroot() |
|
|
|
ref_tags = [] |
|
for ig in root.findall(group_tag_name): |
|
ref_tags += [rf for rf in ig.findall(reference_tag_name)] |
|
|
|
names = [] |
|
for ref in ref_tags: |
|
include = ref.attrib.get('Include') |
|
if include is None: |
|
continue |
|
|
|
library_name = get_library_name(include) |
|
names.append(library_name) |
|
return names |
|
|
|
|
|
def get_library_name(include_str): |
|
name_len = (include_str.index(',') |
|
if ',' in include_str |
|
else len(include_str)) |
|
return include_str[:name_len] |
|
|
|
|
|
def convert(filepath): |
|
dir_path = os.path.dirname(os.path.realpath(filepath)) |
|
library_names = [ |
|
name |
|
for name in get_library_names(filepath) |
|
if name.startswith('SharpDX') |
|
] |
|
packs_element = ET.Element('packages') |
|
for name in library_names: |
|
if name == 'SharpDX.Sample': |
|
continue |
|
|
|
pack_element = ET.Element('package') |
|
pack_element.attrib['id'] = name |
|
pack_element.attrib['version'] = '3.1.1' |
|
pack_element.attrib['targetFramework'] = 'net451' |
|
|
|
packs_element.append(pack_element) |
|
|
|
save_path = os.path.join(dir_path, 'packages.config') |
|
|
|
with open(save_path, 'w', encoding=ENCODING) as w: |
|
w.write(prettify(packs_element).decode()) |
|
|
|
|
|
def prettify(elem): |
|
"""Return a pretty-printed XML string for the Element. |
|
""" |
|
rough_string = ET.tostring(elem, ENCODING) |
|
reparsed = minidom.parseString(rough_string) |
|
return reparsed.toprettyxml(indent=' ', encoding=ENCODING) |
|
|
|
|
|
if __name__ == '__main__': |
|
for csproj in glob.glob('**/*.csproj', recursive=True): |
|
print(csproj) |
|
convert(csproj) |