env_var2.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import os
  2. import argparse
  3. from tabulate import tabulate
  4. import csv
  5. def find_env_files(directory):
  6. """Recursively traverse the directory and find all .env files."""
  7. env_files = []
  8. for root, _, files in os.walk(directory):
  9. for file in files:
  10. if file.endswith('.env'):
  11. env_files.append(os.path.join(root, file))
  12. return env_files
  13. def read_env_file(file_path):
  14. """Read the contents of an .env file and return a list of key-value pairs."""
  15. key_value_pairs = []
  16. with open(file_path, 'r') as file:
  17. for line in file:
  18. line = line.strip()
  19. if line and not line.startswith('#') and '=' in line:
  20. key, value = line.split('=', 1)
  21. key_value_pairs.append((key.strip(), value.strip()))
  22. return key_value_pairs
  23. def create_table(env_files, root_directory):
  24. """Create a table with directory name, .env file name, environment key, and values."""
  25. table = []
  26. for env_file in env_files:
  27. key_value_pairs = read_env_file(env_file)
  28. directory_name = os.path.dirname(os.path.relpath(env_file, start=root_directory))
  29. file_name = os.path.basename(env_file)
  30. for key, value in key_value_pairs:
  31. table.append([directory_name, file_name, key, value])
  32. return table
  33. def save_to_csv(table, output_file):
  34. """Save the table data to a CSV file."""
  35. headers = ["Directory", ".env File Name", "Environment Key", "Value"]
  36. with open(output_file, 'w', newline='') as csvfile:
  37. writer = csv.writer(csvfile)
  38. writer.writerow(headers)
  39. writer.writerows(table)
  40. print(f"Data saved to {output_file}")
  41. def main(directory, output_format, output_file):
  42. """Main function to find .env files, read their contents, and display/save the results."""
  43. env_files = find_env_files(directory)
  44. if not env_files:
  45. print(f"No .env files found in '{directory}'.")
  46. return
  47. table = create_table(env_files, directory)
  48. headers = ["Directory", ".env File Name", "Environment Key", "Value"]
  49. if output_format == "table":
  50. print(tabulate(table, headers=headers, tablefmt="grid"))
  51. elif output_format == "csv":
  52. save_to_csv(table, output_file)
  53. else:
  54. print("Invalid output format. Choose 'table' or 'csv'.")
  55. if __name__ == "__main__":
  56. # Set up command-line argument parsing
  57. parser = argparse.ArgumentParser(description="Find and display .env files in a directory.")
  58. parser.add_argument("directory", help="Directory to search for .env files")
  59. parser.add_argument("--format", choices=["table", "csv"], default="table", help="Output format (table or csv)")
  60. parser.add_argument("--output", default="output.csv", help="Output file name for CSV format")
  61. args = parser.parse_args()
  62. if not os.path.isdir(args.directory):
  63. print(f"Error: '{args.directory}' is not a valid directory.")
  64. else:
  65. main(args.directory, args.format, args.output)