#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import sys
import time

def get_remote_status():
    l = os.popen('ssh root@ "cd /var/www/mysite; git st"').readlines()
    s = ''.join(l)
    return s

def git_commit_change():
    l = os.popen('git status').readlines()
    l = [line.lstrip('#') for line in l]
    s = ''.join(l)
    if not 'nothing to commit' in s:
        if 'deleted:' in s:
            for line in [line for line in l if 'deleted' in line]:
                os.system('git rm %s'%line.strip().split(' ')[-1:][0])
        commit = [line for line in l if line.startswith("\t")]
        for i, line in enumerate(commit):
            if ':' not in line:
                commit[i] = "\tnew file:   %s\n"%line.strip()
        commit = ''.join(commit).rstrip()
        commit = commit.decode('utf-8').encode('gbk')	# git log 正常显示中文
        os.system('git add .')
        os.system('git commit -m "%s"'%commit)
        #os.system('git branch %s'%time.strftime("%Y-%m-%d_%H_%M_%S"))

def git_push_2_server():
    os.system('git push origin master')

if __name__ == '__main__':
    git_commit_change()
    if len(sys.argv)>1:
        argv1 = sys.argv[1]
        if argv1 == 'push':
            remote_status = get_remote_status()
            if 'nothing to commit, working tree clean' in remote_status:
                git_push_2_server()
            else:
                print('Remote Exception!!!!!!!!')
                print(remote_status)
        elif argv1 == 'local':
            os.system('git push local master')
        else:
            print('')
            print('    错误的参数:'+argv1)
            print('')