configutil.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. Defines utilities useful for performing standard "configuration" style tasks.
  3. """
  4. import re
  5. import os
  6. def configure_file(input_path, output_path, substitutions):
  7. """configure_file(input_path, output_path, substitutions) -> bool
  8. Given an input and output path, "configure" the file at the given input path
  9. by replacing variables in the file with those given in the substitutions
  10. list. Returns true if the output file was written.
  11. The substitutions list should be given as a list of tuples (regex string,
  12. replacement), where the regex and replacement will be used as in 're.sub' to
  13. execute the variable replacement.
  14. The output path's parent directory need not exist (it will be created).
  15. If the output path does exist and the configured data is not different than
  16. it's current contents, the output file will not be modified. This is
  17. designed to limit the impact of configured files on build dependencies.
  18. """
  19. # Read in the input data.
  20. f = open(input_path, "rb")
  21. try:
  22. data = f.read()
  23. finally:
  24. f.close()
  25. # Perform the substitutions.
  26. for regex_string,replacement in substitutions:
  27. regex = re.compile(regex_string)
  28. data = regex.sub(replacement, data)
  29. # Ensure the output parent directory exists.
  30. output_parent_path = os.path.dirname(os.path.abspath(output_path))
  31. if not os.path.exists(output_parent_path):
  32. os.makedirs(output_parent_path)
  33. # If the output path exists, load it and compare to the configured contents.
  34. if os.path.exists(output_path):
  35. current_data = None
  36. try:
  37. f = open(output_path, "rb")
  38. try:
  39. current_data = f.read()
  40. except:
  41. current_data = None
  42. f.close()
  43. except:
  44. current_data = None
  45. if current_data is not None and current_data == data:
  46. return False
  47. # Write the output contents.
  48. f = open(output_path, "wb")
  49. try:
  50. f.write(data)
  51. finally:
  52. f.close()
  53. return True