#management/commands/addcomment.py
# coding:utf8
import os

from django.core.management import BaseCommand


class Command(BaseCommand):
""" usage: python manage.py addcomment"""
    help = u'add comment  *#coding:utf8* to all python file'

    def handle(self, *args, **options):
        walk_all_file()


def walk_all_file():
    project_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    replace_file = []
    for (dirpath, dirnames, filenames) in os.walk(project_dir):
        for filename in filenames:
            if filename.endswith('.py'):
                full_path_file_name = os.sep.join([dirpath, filename])
                with open(full_path_file_name, 'r+') as f:
                    if f.readline().startswith('#'):
                        print(u'already had:  %s' % full_path_file_name)
                    else:
                        replace_file.append(str(full_path_file_name))

    for file in replace_file:
        with open(file,'r') as f:
            with open('newfile.txt','w') as f2:
                f2.write('# coding:utf8 \n')
                f2.write(f.read())
        os.rename('newfile.txt',file)
        print(u'commenting : %s' % file)