Guest User

Untitled

a guest
May 22nd, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. import os
  2.  
  3. def enforce_tmp(name, contents=None):
  4. """
  5. Enforce a temp file has the desired contents.
  6. name
  7. The name of the file to change. (Under '/tmp'.)
  8. contents
  9. The value you will be storing.
  10. """
  11.  
  12. return_dict = {
  13. 'name': name,
  14. 'changes': {},
  15. 'result': False,
  16. 'comment': ''
  17. }
  18.  
  19. tmp_file = os.path.join('/tmp', name)
  20. file_ok = False
  21. content_ok = False
  22. file_contents = None
  23.  
  24. if os.path.isfile(tmp_file):
  25. file_ok = True
  26. with open(tmp_file, 'r') as fp:
  27. file_contents = fp.read()
  28. file_contents = file_contents.rstrip('\n')
  29.  
  30. if file_contents == contents:
  31. content_ok = True
  32.  
  33. comments = ""
  34. if file_ok:
  35. comments += 'File exists ({0})\n'.format(tmp_file)
  36. else:
  37. comments += 'File created ({0})\n'.format(tmp_file)
  38. if content_ok:
  39. comments += 'Contents correct ({0})\n'.format(file_contents)
  40. else:
  41. comments += 'Contents updated ({0})\n'.format(contents)
  42. return_dict['comment'] = comments
  43.  
  44. # Check if this is a test run, if so do not change anything.
  45. if __opts__['test'] == True:
  46. return_dict['result'] = None
  47. return_dict['changes'] = {}
  48. if not content_ok:
  49. return_dict['comment'] = {
  50. 'contents': {
  51. 'old': file_contents,
  52. 'new': contents
  53. }
  54. }
  55. return return_dict
  56.  
  57. if not content_ok:
  58. with open(tmp_file, 'w') as fp:
  59. contents += "\n"
  60. fp.write(contents)
  61. return_dict['result'] = True
  62. return_dict['changes'] = {
  63. 'contents': {
  64. 'old': file_contents,
  65. 'new': contents
  66. }
  67. }
  68. else:
  69. return_dict['changes'] = {}
  70. return_dict['result'] = True
  71.  
  72. return return_dict
Add Comment
Please, Sign In to add comment