generate_docker_compose 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #!/usr/bin/env python3
  2. import os
  3. import re
  4. import sys
  5. def parse_env_example(file_path):
  6. """
  7. Parses the .env.example file and returns a dictionary with variable names as keys and default values as values.
  8. """
  9. env_vars = {}
  10. with open(file_path, "r") as f:
  11. for line_number, line in enumerate(f, 1):
  12. line = line.strip()
  13. # Ignore empty lines and comments
  14. if not line or line.startswith("#"):
  15. continue
  16. # Use regex to parse KEY=VALUE
  17. match = re.match(r"^([^=]+)=(.*)$", line)
  18. if match:
  19. key = match.group(1).strip()
  20. value = match.group(2).strip()
  21. # Remove possible quotes around the value
  22. if (value.startswith('"') and value.endswith('"')) or (
  23. value.startswith("'") and value.endswith("'")
  24. ):
  25. value = value[1:-1]
  26. env_vars[key] = value
  27. else:
  28. print(f"Warning: Unable to parse line {line_number}: {line}")
  29. return env_vars
  30. def generate_shared_env_block(env_vars, anchor_name="shared-api-worker-env"):
  31. """
  32. Generates a shared environment variables block as a YAML string.
  33. """
  34. lines = [f"x-shared-env: &{anchor_name}"]
  35. for key, default in env_vars.items():
  36. # If default value is empty, use ${KEY:-}
  37. if default == "":
  38. lines.append(f" {key}: ${{{key}:-}}")
  39. else:
  40. # If default value contains special characters, wrap it in quotes
  41. if re.search(r"[:\s]", default):
  42. default = f'"{default}"'
  43. lines.append(f" {key}: ${{{key}:-{default}}}")
  44. return "\n".join(lines)
  45. def insert_shared_env(template_path, output_path, shared_env_block, header_comments):
  46. """
  47. Inserts the shared environment variables block and header comments into the template file,
  48. removing any existing x-shared-env anchors, and generates the final docker-compose.yaml file.
  49. """
  50. with open(template_path, "r") as f:
  51. template_content = f.read()
  52. # Remove existing x-shared-env: &shared-api-worker-env lines
  53. template_content = re.sub(
  54. r"^x-shared-env: &shared-api-worker-env\s*\n?",
  55. "",
  56. template_content,
  57. flags=re.MULTILINE,
  58. )
  59. # Prepare the final content with header comments and shared env block
  60. final_content = f"{header_comments}\n{shared_env_block}\n\n{template_content}"
  61. with open(output_path, "w") as f:
  62. f.write(final_content)
  63. print(f"Generated {output_path}")
  64. def main():
  65. env_example_path = ".env.example"
  66. template_path = "docker-compose-template.yaml"
  67. output_path = "docker-compose.yaml"
  68. anchor_name = "shared-api-worker-env" # Can be modified as needed
  69. # Define header comments to be added at the top of docker-compose.yaml
  70. header_comments = (
  71. "# ==================================================================\n"
  72. "# WARNING: This file is auto-generated by generate_docker_compose\n"
  73. "# Do not modify this file directly. Instead, update the .env.example\n"
  74. "# or docker-compose-template.yaml and regenerate this file.\n"
  75. "# ==================================================================\n"
  76. )
  77. # Check if required files exist
  78. for path in [env_example_path, template_path]:
  79. if not os.path.isfile(path):
  80. print(f"Error: File {path} does not exist.")
  81. sys.exit(1)
  82. # Parse .env.example file
  83. env_vars = parse_env_example(env_example_path)
  84. if not env_vars:
  85. print("Warning: No environment variables found in .env.example.")
  86. # Generate shared environment variables block
  87. shared_env_block = generate_shared_env_block(env_vars, anchor_name)
  88. # Insert shared environment variables block and header comments into the template
  89. insert_shared_env(template_path, output_path, shared_env_block, header_comments)
  90. if __name__ == "__main__":
  91. main()