filegenを使ったscaffold scriptの作成のしかた

filegenを使ったscaffold scriptの作成のしかた

filegenでscaffold用のスクリプトを生成する方法は以下のようなコードを書く。

filegen_script.py

# -*- coding:utf-8 -*-
from filegen import Filegen
from filegen.asking import AskString


def gen():
    fg = Filegen()
    yourname = str(AskString("yourname", description="what is your name", default="foo"))
    YOURNAME = yourname.upper()

    with fg.dir("greeting"):
        with fg.file("hello.txt") as wf:
            wf.write("{}: hello.".format(yourname))
        with fg.file("bye.txt") as wf:
            wf.write("{}: bye.".format(yourname))
        with fg.file("is_angry.txt") as wf:
            wf.write("{}: HEY!".format(YOURNAME))
    return fg

if __name__ == "__main__":
    from filegen import FilegenApplication
    FilegenApplication().run(gen)

このようなコードを書きこれをpythonで実行する。

直接使う事もできる。

$ python filegen_script.py  # file生成

filegenに非依存なスクリプトを生成することが出来る

$ python filegen_script.py  --action=code > gen.py
$ python gen.py tmp
yourname (what is your name)['foo']:
INFO:__main__:[d] create: tmp/
INFO:__main__:[d] create: tmp/greeting
INFO:__main__:[f] create: tmp/greeting/hello.txt
INFO:__main__:[f] create: tmp/greeting/bye.txt
INFO:__main__:[f] create: tmp/greeting/is_angry.txt
$ tree tmp
tmp
└── greeting
    ├── bye.txt
    ├── hello.txt
    └── is_angry.txt

1 directory, 3 files
$ cat tmp/greeting/hello.txt
foo: hello.
$ cat tmp/greeting/is_angry.txt
foo: HEY!

ちなみに生成されるコードは以下のようなもの

https://gist.github.com/podhmo/67c54ef42101764bf47e