自作のファイルテンプレート(雛形)を生成するCookiecutterの使い方
2018/05/20
累計閲覧数 2253 PV
開発に限らず、PC作業をしているとさまざまな場面でファイルやディレクトリツリーを構築します。 ここでは、生成されるこれらのファイル、ディレクトリ群をまとめてプロジェクトレイアウトと呼称します。
プロジェクトレイアウトをコピペで作っていると、プロジェクト名が異なっていると、 影響するファイル名やClass名が多いでしょう。 そんなツールの1つにcookiecutterというオープンソースがあります。
図で説明すると、次のようになります。
もっともシンプルなコマンドは、引数にテンプレートのURLもしくは相対パスを指定することです。
Pythonのパッケージを作る際のボイラープレートで試してみます(audreyr/cookiecutter-pypackage)。
$ cookiecutter https://github.com/audreyr/cookiecutter-pypackage.git
対話式に聞かれた後、プロジェクトレイアウトが生成されます。
cookiecutter -h
でヘルプを表示しておきます。
Usage: cookiecutter [OPTIONS] TEMPLATE [EXTRA_CONTEXT]...
Create a project from a Cookiecutter project template (TEMPLATE).
Cookiecutter is free and open source software, developed and managed by
volunteers. If you would like to help out or fund the project, please get
in touch at https://github.com/audreyr/cookiecutter.
Options:
-V, --version Show the version and exit.
--no-input Do not prompt for parameters and only use
cookiecutter.json file content
-c, --checkout TEXT branch, tag or commit to checkout after git clone
-v, --verbose Print debug information
--replay Do not prompt for parameters and only use
information entered previously
-f, --overwrite-if-exists Overwrite the contents of the output directory if
it already exists
-o, --output-dir PATH Where to output the generated project dir into
--config-file PATH User configuration file
--default-config Do not load a config file. Use the defaults
instead
--debug-file PATH File to be used as a stream for DEBUG logging
-h, --help Show this message and exit.
とてもシンプルです。 CookieCutterは内部のテンプレートエンジンにJinja2を採用しており、 Jinja2の記法が利用できます。
もっともシンプルなテンプレートを作成してみます。
simple-template/
├── cookiecutter.json
└── {{cookiecutter.project_name}}/
cookiecutter.json
の中身は次のようにします。
{
"project_name": "hello-world"
}
次に、simple-template
をテンプレートとして利用してみます。
$ cookiecutter ./simple-template
これでテンプレートとして利用できます。
cookiecutterで自作テンプレートを作るときは、次のルールを守っておけば良いでしょう。
cookiecutter.json
に書く。
{{cookiecutter.xxx}}
のように、Jinja2のテンプレートが展開できる記法で記述し、cookiecutter
のメンバー変数として展開できるようにしておく。
詳しい説明はAdvanced Usage - cookiecutterに載っています。
また、すで公開されているcookiecutter用のテンプレートを見てみることもオススメします。
とてもシンプルな答えはGitHubやBitbucketにホスティングすることです。
作っては捨て、という大量生産大量消費の時代にもってこいなパッケージとなっております。 cookiecutterはPythonで作成されていますが、テンプレートとするプロジェクトは言語を問いません。
DEMOでプレビューするときや、ちょっとした検証をしたい時用の雛形をあらかじめ作っておくと時間の節約になります。