Skip to content

Instantly share code, notes, and snippets.

@tkardi
Created April 20, 2017 06:05
Show Gist options
  • Save tkardi/97ef9bc6b0cde411bfb85feccdb9b7ed to your computer and use it in GitHub Desktop.
Save tkardi/97ef9bc6b0cde411bfb85feccdb9b7ed to your computer and use it in GitHub Desktop.
Fix GeoServer workspace config xml files by replacing certain values (e.g workspace id).
import os
from lxml import etree
def iter_path(path, ext):
"""Returns an iterator over files on path with a certain fileextension."""
for dirname, paths, files in os.walk(path):
for _file in files:
_fname, _ext = os.path.splitext(_file)
if _ext.lower() == '.%s' % ext.lower():
yield os.path.join(dirname, _file)
def replace_value_by_xpath(path, xpathexp, value):
"""Replaces a value at xpath with a new value.
Only 1 response per xpath expression per file allowed.
"""
assert os.path.exists(path), "Path %s does not exist!"
for _file in iter_path(path, 'xml'):
with open(_file) as f:
# just in case we'll stack the old contents away
original = f.read()
tree = etree.fromstring(original)
x = tree.xpath(xpathexp)
if len(x) == 1:
elem = x[0]
try:
assert elem.text != value
elem.text = value
new = etree.tostring(tree)
with open(_file, 'w') as f:
f.write(new)
except AssertionError as ae:
print 'File %s already has xpath "%s" value %s' % (
_file, xpathexp, value
)
except Exception as e:
_bckup = '%s.backup' % _file
with open(_bckup, 'w') as f:
f.write(original)
print 'Something happened, wrote backup to %s' % (
_bckup,
)
raise
elif len(x) > 0:
# this could be, but we're not interested in this case
# e.g multiple styles/style elements - it's more complicated
# than that.
raise AttributeError(
'File %s has multiple xpath "%s" responses' % (
_file, xpathexpr
)
)
else:
# did not find xpathexpression in this file
pass
if __name__ == '__main__':
# replace_value_by_xpath takes three args:
# gs workspace path,
# xpath expression of what to search for,
# and the new value to assign
# NB! make sure you have backup copy of the workspace before running.
# you know, just in case.
replace_value_by_xpath(
'GEOSERVER_DATA_DIR/workspaces/WORKSPACE_NAME',
'//workspace/id',
'ThisIsTheNew-Workspace:id-1234')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment