env_var.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import os
  2. from tabulate import tabulate
  3. def find_env_files(directory):
  4. """Traverse the directory and find all .env files."""
  5. env_files = []
  6. for root, _, files in os.walk(directory):
  7. for file in files:
  8. if file.endswith('.env'):
  9. env_files.append(os.path.join(root, file))
  10. return env_files
  11. def read_env_file(file_path):
  12. """Read the contents of an .env file and return a list of key-value pairs."""
  13. key_value_pairs = []
  14. with open(file_path, 'r') as file:
  15. for line in file:
  16. line = line.strip()
  17. if line and not line.startswith('#') and '=' in line:
  18. key, value = line.split('=', 1)
  19. key_value_pairs.append((key.strip(), value.strip()))
  20. return key_value_pairs
  21. def create_table(env_files, root_directory):
  22. """Create a table with .env file name, environment key, and values."""
  23. table = []
  24. for env_file in env_files:
  25. key_value_pairs = read_env_file(env_file)
  26. directory_name = os.path.dirname(os.path.relpath(env_file, start=root_directory))
  27. file_name = os.path.basename(env_file)
  28. for key, value in key_value_pairs:
  29. table.append([directory_name, file_name, key, value])
  30. return table
  31. def main(directory):
  32. """Main function to find .env files, read their contents, and display the table."""
  33. env_files = find_env_files(directory)
  34. if not env_files:
  35. print("No .env files found.")
  36. return
  37. table = create_table(env_files, directory)
  38. headers = ["Directory", ".env File Name", "Environment Key", "Value"]
  39. print(tabulate(table, headers=headers, tablefmt="grid"))
  40. if __name__ == "__main__":
  41. directory_to_search = input("Enter the directory to search for .env files: ")
  42. main(directory_to_search)