Advertisement
Guest User

Untitled

a guest
Dec 20th, 2024
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.23 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import argparse
  5. from pathlib import Path
  6. from datetime import datetime
  7.  
  8.  
  9. def generate_tree(directory_path, output_file="file_tree.md"):
  10. """
  11. Generates a markdown file containing the directory/file tree structure.
  12. """
  13. try:
  14. # Convert to absolute path and verify directory exists
  15. abs_path = os.path.abspath(directory_path)
  16. if not os.path.isdir(abs_path):
  17. print(f"Error: '{directory_path}' is not a valid directory")
  18. return False
  19.  
  20. # Create or truncate output file
  21. with open(output_file, "w", encoding="utf-8") as outfile:
  22. # Write header with timestamp
  23. outfile.write(f"# Directory Tree Report\n\n")
  24. outfile.write(
  25. f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
  26. )
  27. outfile.write(f"Source directory: `{directory_path}`\n\n")
  28. outfile.write("```\n")
  29.  
  30. # Walk through directory recursively
  31. for root, dirs, files in os.walk(abs_path):
  32. # Calculate depth for indentation
  33. level = root.replace(abs_path, "").count(os.sep)
  34. indent = "│ " * level
  35.  
  36. # Print directory name
  37. dir_name = os.path.basename(root)
  38. if level == 0:
  39. outfile.write(f"{dir_name}/\n")
  40. else:
  41. outfile.write(f"{indent}├── {dir_name}/\n")
  42.  
  43. # Print files
  44. subindent = "│ " * (level + 1)
  45. for i, file in enumerate(sorted(files)):
  46. if i == len(files) - 1 and not dirs: # Last file in directory
  47. outfile.write(f"{subindent[:-4]}└── {file}\n")
  48. else:
  49. outfile.write(f"{subindent}├── {file}\n")
  50.  
  51. outfile.write("```\n")
  52. outfile.write("\n# End of Directory Tree Report\n")
  53.  
  54. print(f"Successfully generated directory tree in '{output_file}'")
  55. return True
  56.  
  57. except Exception as e:
  58. print(f"Error: {str(e)}")
  59. return False
  60.  
  61.  
  62. def combine_files(directory_path, output_file="combined_output.md"):
  63. """
  64. Recursively combines all files from the given directory into a single markdown file.
  65. Each file's content is formatted with markdown syntax for better readability.
  66. """
  67. try:
  68. # Convert to absolute path and verify directory exists
  69. abs_path = os.path.abspath(directory_path)
  70. if not os.path.isdir(abs_path):
  71. print(f"Error: '{directory_path}' is not a valid directory")
  72. return False
  73.  
  74. # Create or truncate output file
  75. with open(output_file, "w", encoding="utf-8") as outfile:
  76. # Write header with timestamp
  77. outfile.write(f"# Combined Files Report\n\n")
  78. outfile.write(
  79. f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
  80. )
  81. outfile.write(f"Source directory: `{directory_path}`\n\n")
  82. outfile.write("---\n\n")
  83.  
  84. # Walk through directory recursively
  85. for root, _, files in os.walk(abs_path):
  86. for filename in sorted(files):
  87. # Skip the output file itself if it's in the directory
  88. if filename == output_file:
  89. continue
  90.  
  91. file_path = os.path.join(root, filename)
  92.  
  93. # Calculate relative path from the input directory
  94. rel_path = os.path.relpath(file_path, abs_path)
  95.  
  96. try:
  97. # Try to read the file as text
  98. with open(file_path, "r", encoding="utf-8") as infile:
  99. # Write file header with path
  100. outfile.write(f"## {rel_path}\n\n")
  101.  
  102. # Determine language for syntax highlighting based on file extension
  103. ext = os.path.splitext(filename)[1].lstrip(".")
  104. if ext:
  105. outfile.write(f"```{ext}\n")
  106. else:
  107. outfile.write("```\n")
  108.  
  109. # Write file contents
  110. outfile.write(infile.read())
  111. outfile.write("\n```\n\n")
  112.  
  113. # Add separator between files
  114. outfile.write("---\n\n")
  115. except UnicodeDecodeError:
  116. # Handle binary files
  117. outfile.write(f"## {rel_path}\n\n")
  118. outfile.write("*[Binary file]*\n\n")
  119. outfile.write("---\n\n")
  120. except Exception as e:
  121. # Log other errors but continue processing
  122. outfile.write(f"## {rel_path}\n\n")
  123. outfile.write(f"*[Error reading file: {str(e)}]*\n\n")
  124. outfile.write("---\n\n")
  125.  
  126. # Write footer
  127. outfile.write("# End of Combined Files Report\n")
  128.  
  129. print(f"Successfully combined files into '{output_file}'")
  130. return True
  131.  
  132. except Exception as e:
  133. print(f"Error: {str(e)}")
  134. return False
  135.  
  136.  
  137. def main():
  138. parser = argparse.ArgumentParser(
  139. description="Combine files or generate directory tree structure."
  140. )
  141. parser.add_argument("directory", help="Directory path to process")
  142. parser.add_argument("-o", "--output", help="Output file name", default=None)
  143. parser.add_argument(
  144. "--tree",
  145. action="store_true",
  146. help="Generate directory tree instead of combining files",
  147. )
  148.  
  149. args = parser.parse_args()
  150.  
  151. if args.tree:
  152. output_file = args.output if args.output else "file_tree.md"
  153. if not generate_tree(args.directory, output_file):
  154. sys.exit(1)
  155. else:
  156. output_file = args.output if args.output else "combined_output.md"
  157. if not combine_files(args.directory, output_file):
  158. sys.exit(1)
  159.  
  160.  
  161. if __name__ == "__main__":
  162. main()
  163.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement