Skip to content

Instantly share code, notes, and snippets.

@dancojocaru2000
Last active May 2, 2018 05:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dancojocaru2000/f7c3875f424f47a769a1f87b609ca75a to your computer and use it in GitHub Desktop.
Save dancojocaru2000/f7c3875f424f47a769a1f87b609ca75a to your computer and use it in GitHub Desktop.
Remove comments in compatible files (tested for JS, HTML)
#!/usr/bin/env python3
import os
import sys
if len(sys.argv) < 2:
print("Remove comments in compatible files")
print("// ... = remove from // until LF")
print("/* ... */ = remove from /* to first */ found after it")
print("<!-- ... --> = similar to /* ... */")
print()
print("Usage:")
print("remove_comments.py \"path_to_folder_here\"")
sys.exit(0)
init_dir_location = sys.argv[1]
def process_file(filepath):
file_contents = ""
# Read file
with open(filepath, "r") as f:
file_contents = f.read()
# Process file
new_file_contents = ""
while file_contents.find("//") != -1:
new_file_contents = file_contents[:file_contents.find("//")] + file_contents[file_contents.find("\n", file_contents.find("//")):]
file_contents = new_file_contents
while file_contents.find("/*") != -1:
begin = file_contents.find("/*")
end = file_contents.find("*/", begin) + 2
new_file_contents = file_contents[:begin] + file_contents[end:]
file_contents = new_file_contents
while file_contents.find("<!--") != -1:
begin = file_contents.find("<!--")
end = file_contents.find("-->", begin) + 3
new_file_contents = file_contents[:begin] + file_contents[end:]
file_contents = new_file_contents
# Write file
with open(filepath, "w") as g:
g.write(file_contents)
def recurse_over_folders(folder):
for f in os.listdir(folder):
current_path = os.path.join(folder, f)
if not os.path.isfile(current_path):
recurse_over_folders(current_path)
else:
import mimetypes
mime = mimetypes.guess_type(current_path)
if mime[0] is None:
print(f"File not processed: {current_path}")
elif mime[0][:5] == "text/":
process_file(current_path)
else:
print(f"File not processed: {current_path}")
recurse_over_folders(init_dir_location)
print("Success!")
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment