generate_docker_compose 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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 key == "COMPOSE_PROFILES":
  37. continue
  38. # If default value is empty, use ${KEY:-}
  39. if default == "":
  40. lines.append(f" {key}: ${{{key}:-}}")
  41. else:
  42. # If default value contains special characters, wrap it in quotes
  43. if re.search(r"[:\s]", default):
  44. default = f"{default}"
  45. lines.append(f" {key}: ${{{key}:-{default}}}")
  46. return "\n".join(lines)
  47. def insert_shared_env(template_path, output_path, shared_env_block, header_comments):
  48. """
  49. Inserts the shared environment variables block and header comments into the template file,
  50. removing any existing x-shared-env anchors, and generates the final docker-compose.yaml file.
  51. """
  52. with open(template_path, "r") as f:
  53. template_content = f.read()
  54. # Remove existing x-shared-env: &shared-api-worker-env lines
  55. template_content = re.sub(
  56. r"^x-shared-env: &shared-api-worker-env\s*\n?",
  57. "",
  58. template_content,
  59. flags=re.MULTILINE,
  60. )
  61. # Prepare the final content with header comments and shared env block
  62. final_content = f"{header_comments}\n{shared_env_block}\n\n{template_content}"
  63. with open(output_path, "w") as f:
  64. f.write(final_content)
  65. print(f"Generated {output_path}")
  66. def main():
  67. env_example_path = ".env.example"
  68. template_path = "docker-compose-template.yaml"
  69. output_path = "docker-compose.yaml"
  70. anchor_name = "shared-api-worker-env" # Can be modified as needed
  71. # Define header comments to be added at the top of docker-compose.yaml
  72. header_comments = (
  73. "# ==================================================================\n"
  74. "# WARNING: This file is auto-generated by generate_docker_compose\n"
  75. "# Do not modify this file directly. Instead, update the .env.example\n"
  76. "# or docker-compose-template.yaml and regenerate this file.\n"
  77. "# ==================================================================\n"
  78. )
  79. # Check if required files exist
  80. for path in [env_example_path, template_path]:
  81. if not os.path.isfile(path):
  82. print(f"Error: File {path} does not exist.")
  83. sys.exit(1)
  84. # Parse .env.example file
  85. env_vars = parse_env_example(env_example_path)
  86. if not env_vars:
  87. print("Warning: No environment variables found in .env.example.")
  88. # Generate shared environment variables block
  89. shared_env_block = generate_shared_env_block(env_vars, anchor_name)
  90. # Insert shared environment variables block and header comments into the template
  91. insert_shared_env(template_path, output_path, shared_env_block, header_comments)
  92. if __name__ == "__main__":
  93. main()