Skip to content

Instantly share code, notes, and snippets.

@crhan
Created April 17, 2022 01:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crhan/4d45c28015f2046704cedb67a80d3cec to your computer and use it in GitHub Desktop.
Save crhan/4d45c28015f2046704cedb67a80d3cec to your computer and use it in GitHub Desktop.
vscode_container_initialize.py
#!/usr/bin/env python3
import hashlib
import logging
import os
import time
from pathlib import Path
logging.basicConfig(
format="%(asctime)s - %(filename)s:%(lineno)d - %(levelname)s - %(message)s",
level=logging.DEBUG,
)
_LOGGER = logging.getLogger(__name__)
def get_cwd():
return Path(os.path.abspath(__file__)).parent
def get_project_name():
"""假设文件夹结构是 project_name/.devcontainer/initialize.py"""
project_dir_name = get_cwd().parent.name
user_name = os.getenv("USER")
post_fix = get_random_hash()[:8]
project_name = f"{user_name}_{project_dir_name}_{post_fix}"
_LOGGER.info("project_name: %s", project_name)
return project_name
def get_random_hash():
return hashlib.sha1(str(time.time()).encode("utf-8")).hexdigest()
def write_project_name_to_dotenv(dotenv_path):
"""
将模板文件中的内容写入到 .env 文件中
"""
write_flag = False
project_name = get_project_name()
lines = open(dotenv_path, "r").readlines()
with open(dotenv_path, "w") as wf:
for line in lines:
if line.startswith("COMPOSE_PROJECT_NAME"):
line = f"COMPOSE_PROJECT_NAME={project_name}\n"
write_flag = True
wf.write(line)
if not write_flag:
wf.write(f"COMPOSE_PROJECT_NAME={project_name}\n")
def main():
cwd = get_cwd()
# check initlize flag file
init_flag = cwd / ".initialized"
if init_flag.exists():
_LOGGER.info("Already initialized")
return
write_project_name_to_dotenv(cwd.parent / ".env")
# create initlize flag file
init_flag.touch()
_LOGGER.info("Initialized")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment