Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. #!/usr/bin/python2.7
  2.  
  3. import os
  4. import sys
  5. import fnmatch
  6. import subprocess
  7. import traceback
  8.  
  9. # whichever directory is running on.
  10. cwd = os.getcwd()
  11.  
  12.  
  13. def which(program):
  14. """
  15. Emulates which command. Checks if exacutable does exist in PATH
  16. """
  17. def is_exe(fpath):
  18. return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
  19.  
  20. fpath, fname = os.path.split(program)
  21.  
  22. if fpath:
  23. if is_exe(program):
  24. return program
  25. else:
  26. for path in os.environ["PATH"].split(os.pathsep):
  27. path = path.strip('"')
  28. exe_file = os.path.join(path, program)
  29. if is_exe(exe_file):
  30. return exe_file
  31. return None
  32.  
  33.  
  34. def format_files(file_list, overwrite=False):
  35. """
  36. Not sure
  37. """
  38. if len(file_list) > 0:
  39. if overwrite is True:
  40. for file in file_list:
  41. cmd = ['xmllint', '--format']
  42. cmd.append(file)
  43. print "[Formatting] " + file
  44. cmd = " ".join(cmd)
  45. p = subprocess.Popen(
  46. cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  47. (output, err) = p.communicate()
  48. p_status = p.wait()
  49. f = open(file, 'w')
  50. f.truncate()
  51. f.write(output)
  52. f.close()
  53.  
  54. else:
  55. for file in file_list:
  56. newfile = file.replace('.xml', '-formatted.xml')
  57. cmd = ['xmllint', '--format']
  58. cmd.append(file)
  59. cmd.append('>>')
  60. cmd.append(newfile)
  61. print "[Formatting] " + file
  62. subprocess.call(" ".join(cmd), shell=True)
  63. else:
  64. print "No valid files to format, Quit!"
  65.  
  66.  
  67. def main():
  68. """
  69. Module
  70. """
  71. if which('xmllint') is None:
  72. print "XMLlint can not be found. Quit!"
  73. sys.exit(1)
  74.  
  75. print 'Working on ' + cwd
  76. try:
  77. matches = []
  78. for root, dirnames, filenames in os.walk(cwd):
  79. for filename in fnmatch.filter(filenames, '*.xml'):
  80. matches.append(os.path.join(root, filename))
  81. print "\n".join(matches)
  82. confirm = raw_input("Listed files will be formatted, yes? 5$ pls!\n")
  83. overwrite = raw_input("Overwrite files, yes?\n")
  84. if confirm in ['y', 'yes']:
  85. if overwrite in ['y', 'yes']:
  86. format_files(matches, True)
  87. else:
  88. format_files(matches)
  89.  
  90. except KeyboardInterrupt:
  91. print "Shutdown requested...exiting"
  92. except Exception:
  93. traceback.print_exc(file=sys.stdout)
  94. sys.exit(0)
  95.  
  96.  
  97. if __name__ == "__main__":
  98. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement