mc-apply.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python
  2. #
  3. # Create a Configuration from marlin_config.json
  4. #
  5. import json, sys, shutil
  6. opt_output = '--opt' in sys.argv
  7. output_suffix = '.sh' if opt_output else '' if '--bare-output' in sys.argv else '.gen'
  8. try:
  9. with open('marlin_config.json', 'r') as infile:
  10. conf = json.load(infile)
  11. for key in conf:
  12. # We don't care about the hash when restoring here
  13. if key == '__INITIAL_HASH':
  14. continue
  15. if key == 'VERSION':
  16. for k, v in sorted(conf[key].items()):
  17. print(k + ': ' + v)
  18. continue
  19. # The key is the file name, so let's build it now
  20. outfile = open('Marlin/' + key + output_suffix, 'w')
  21. for k, v in sorted(conf[key].items()):
  22. # Make define line now
  23. if opt_output:
  24. if v != '':
  25. if '"' in v:
  26. v = "'%s'" % v
  27. elif ' ' in v:
  28. v = '"%s"' % v
  29. define = 'opt_set ' + k + ' ' + v + '\n'
  30. else:
  31. define = 'opt_enable ' + k + '\n'
  32. else:
  33. define = '#define ' + k + ' ' + v + '\n'
  34. outfile.write(define)
  35. outfile.close()
  36. # Try to apply changes to the actual configuration file (in order to keep useful comments)
  37. if output_suffix != '':
  38. # Move the existing configuration so it doesn't interfere
  39. shutil.move('Marlin/' + key, 'Marlin/' + key + '.orig')
  40. infile_lines = open('Marlin/' + key + '.orig', 'r').read().split('\n')
  41. outfile = open('Marlin/' + key, 'w')
  42. for line in infile_lines:
  43. sline = line.strip(" \t\n\r")
  44. if sline[:7] == "#define":
  45. # Extract the key here (we don't care about the value)
  46. kv = sline[8:].strip().split(' ')
  47. if kv[0] in conf[key]:
  48. outfile.write('#define ' + kv[0] + ' ' + conf[key][kv[0]] + '\n')
  49. # Remove the key from the dict, so we can still write all missing keys at the end of the file
  50. del conf[key][kv[0]]
  51. else:
  52. outfile.write(line + '\n')
  53. else:
  54. outfile.write(line + '\n')
  55. # Process any remaining defines here
  56. for k, v in sorted(conf[key].items()):
  57. define = '#define ' + k + ' ' + v + '\n'
  58. outfile.write(define)
  59. outfile.close()
  60. print('Output configuration written to: ' + 'Marlin/' + key + output_suffix)
  61. except:
  62. print('No marlin_config.json found.')