remove_strings.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/env python
  2. # Copyright (c) 2013 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Remove strings by name from a GRD file."""
  6. import optparse
  7. import re
  8. import sys
  9. def RemoveStrings(grd_path, string_names):
  10. """Removes strings with the given names from a GRD file. Overwrites the file.
  11. Args:
  12. grd_path: path to the GRD file.
  13. string_names: a list of string names to be removed.
  14. """
  15. with open(grd_path, 'r') as f:
  16. grd = f.read()
  17. names_pattern = '|'.join(map(re.escape, string_names))
  18. pattern = r'<message [^>]*name="(%s)".*?</message>\s*' % names_pattern
  19. grd = re.sub(pattern, '', grd, flags=re.DOTALL)
  20. with open(grd_path, 'w') as f:
  21. f.write(grd)
  22. def ParseArgs(args):
  23. usage = 'usage: %prog GRD_PATH...'
  24. parser = optparse.OptionParser(
  25. usage=usage, description='Remove strings from GRD files. Reads string '
  26. 'names from stdin, and removes strings with those names from the listed '
  27. 'GRD files.')
  28. options, args = parser.parse_args(args=args)
  29. if not args:
  30. parser.error('must provide GRD_PATH argument(s)')
  31. return args
  32. def main(args=None):
  33. grd_paths = ParseArgs(args)
  34. strings_to_remove = filter(None, map(str.strip, sys.stdin.readlines()))
  35. for grd_path in grd_paths:
  36. RemoveStrings(grd_path, strings_to_remove)
  37. if __name__ == '__main__':
  38. main()