cookiecutter 是一个非常快捷的基于命令行的项目创建工具。
相比使用模板项目然后手动修改,配置客制化项目模板更加灵活通用。cookiecutter使用jinja2作为模版引擎,使用起来很简单方便。当然cookiecutter不仅仅局限于python项目,其他语言也同样适用。
安装
如果有pipx 可以直接安装
pipx install cookiecutter
如果没有也可以使用pip
python -m pip install --user cookiecutter
使用
我们可以直接运行cookiecutter,然后进行提示输入,输入完成创建特殊对应配置项目。
例如我个人的rye通用项目,可以运行如下命令进行初始化。
cookiecutter https://github.com/yuvenhol/cookiecutter-rye
进过一些交互,可以得到一个初始项目。
当我们有需求的时候,可以通过一些别人创建好的模版进行创建—[大量模版库](https://github.com/search?q=cookiecutter&type=Reposito ries),但是更常用的是做一个自己客制化的模板。
客制化
通过{{}}的方式来调用配置文件夹等变量名词。
模版项目结构
cookiecutter-something/
├── {{ cookiecutter.project_name }}/ <--------- Project template
│ └── ...
├── blah.txt <--------- Non-templated files/dirs
│ go outside
│
└── cookiecutter.json <--------- Prompts & default values
模版输出
mysomething/ <---------- Value corresponding to what you enter at the
│ project_name prompt
│
└── ... <-------- Files corresponding to those in your
cookiecutter's `{{ cookiecutter.project_name }}/` dir
cookiecutter.json 配置
通过配置cookiecutter.json 文件,来设置参数(key)和默认值(value)。
{
"project_name": "Cookiecutter Website Simple",
"project_slug": "{{ cookiecutter.project_name.lower().replace(' ', '_') }}",
"author": "Anonymous"
}
文件调用配置
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>{{ cookiecutter.project_name }}</title>
</head>
<body>
<h1>{{ cookiecutter.project_name }}</h1>
<p>by {{ cookiecutter.author }}</p>
</body>
</html>