两断小代码、改改就拿去做 git的增量发布

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/swg0110/article/details/53308776

用我的代码要标注来源!


# coding:utf-8
import  os, commands,datetime,re
from app.config import common as config

'''
从ubuntu 上 操作centos 先要使用密码命令 ssh user@host 登录下才行
错误 target uses selinux but python bindings (libselinux-python) aren't installed! ====>yum install libselinux-python
'''


class Ansible:
    repo_path = ""
    to_path = ""
    tar_path = ""
    delfile_path = ""
    group = ""
    woner = ""
    mode = ""
    fname = ""
    hosts = ""

    #远程执行命令、可指定执行目录,默认在git目录
    def runcmd(self,cmd,remote_path =None,statusLineOnly = True,noStatus =False):
        if None == remote_path:
            remote_path = self.repo_path
        grep = " |grep rc | awk '{print $1\":\"$3}'" if statusLineOnly else ""
        if noStatus==True and remote_path==False:
           grep = " |grep -v rc "
        cmd = "ansible %s -a '%s chdir=%s ' -f 20 %s " % (self.hosts,cmd,remote_path,grep)
        return commands.getoutput(cmd).split("\n")

    def __init__(self, hosts="test_group", repo="vas",mkdir=True):
        now = datetime.datetime.now()
        timeNow = now.strftime("%Y%m%d-%H%M%S")
        cfg = config.GIT_REPO[repo]
        lockpath = config.APP_PATH+"/runtime/lock/"+hosts+".lock"
        if not os.path.exists(lockpath):
            mkdir = False
            with open(lockpath, 'w') as fobj:
                fobj.write(hosts)
        self.repo_path = cfg['path']
        self.to_path = cfg['remote']['path']
        self.tar_path = config.TAR_TMP_PATH
        self.delfile_path = config.DEL_LIST_PATH.replace('last_delfile','dellist_'+timeNow)
        self.group = cfg['remote']['group']
        self.owner = cfg['remote']['owner']
        self.mode = cfg['remote']['mode']
        self.hosts = hosts if hosts else config.ANSIBLE_GROUP['test_group']['ip']

        self.fname = self.tar_path+"/update_" + timeNow + ".tar.gz"
        if mkdir ==True:
            self.mkdir()
        os.chdir(self.repo_path)
        commands.getoutput("git fetch --all")

    def mkdir(self):
        # print u"\ngit repo path :", self.repo_path
        commands.getoutput("mkdir %s -p" % self.tar_path)
        ans_cmd = "ansible %s -a 'mkdir  %s -p ; mkdir  %s  -p ;mkdir -p %s' " % (self.hosts, self.to_path, self.tar_path,self.tar_path)
        mkdir = commands.getoutput(ans_cmd)
        # print ans_cmd
        res = [l for l in mkdir.split("\n")][0].split("|")[1].strip()
        # print "init remote dir: %s , %s \t %s" % (self.to_path, self.tar_path, res)
        commands.getoutput("echo '' > %s" % self.delfile_path)

    def incrPush(self):
        ret = ""
        '''
        git 增量更新操作
        :return:
        '''
        #git_cmd = "git diff $(git log --pretty=format:'%h' -1) --name-status HEAD^ | grep -v '.idea' | grep -v '.svn' |awk '{if($1==\"D\") print $2}' >" + self.delfile_path
        git_cmd = u"git diff HEAD^ --name-status | grep -v '.idea' | grep -v '.svn' |awk '{if($1 ==\"D\") print $2}' >" + self.delfile_path
        commands.getoutput(git_cmd)
        ret +=    u"<b>创建本次删除的文件列表到</b> ==> %s  SUCCESS " % self.delfile_path
        dellist = []
        with open(self.delfile_path) as f:
               dellist = f.readlines()
        if dellist:
           ret +=    u"\n<b>删除文件明细:</b>\n" + "\n".join(dellist)
        else:
            ret += u"\n无文件删除记录"

        git_cmd = "git diff  --name-status HEAD^ | grep -v '.idea' | grep -v '.svn' |awk '{if($1!=\"D\") print $2}' | xargs tar cf " + self.fname
        res = commands.getoutput(git_cmd)

        if not os.path.exists(self.fname):
            ret +=  u"\n <b>查找本次变更的文件: None</b>"
        else:
            listCmd = "git diff  --name-status HEAD^ | grep -v '.idea' | grep -v '.svn' |awk '{if($1!=\"D\") print $2}' "
            listRes = commands.getoutput(listCmd)
            ret +=  u"\n <b>打包变更的文件到</b> ==> %s   SUCCESS " % self.fname
            ret +=  u"\n <b>文件变更明细:</b>\n" + listRes

            ans_cmd = "ansible %s -m copy -a 'src=%s dest=%s remote_src=False group=%s mode=%s owner=%s ' " % (
                self.hosts, self.fname, self.fname, self.group, self.mode, self.owner
            )
            put = commands.getoutput(ans_cmd)
            result = [l for l in put.split("\n")][0].split("|")[1][:8].strip()
            ret += u"\n\n <b>推送文件到(%s) </b> : %s " % (self.hosts,result)
            if result.lower() !="success":
                ret += put
            #zipflle
            ans_cmd = "ansible %s -a 'tar xvf %s  -C %s' " % (self.hosts, self.fname, self.to_path)
            put = commands.getoutput(ans_cmd)
            result = [l for l in put.split("\n")][0].split("|")[1].strip()
            ret += u"\n<b>执行远程(%s)解压文件</b> : %s " % (self.hosts,result)
            if result.lower() !="success":
                ret += put

        ret += u"\n <b>删除远程服务器文件</b>:"
        if os.path.getsize(self.delfile_path) >0:
            #del files
            flist = open(self.delfile_path).readlines()
            if flist:
                ret += "\n"
                for line in flist:
                    f = line.strip()
                    ans_cmd = "ansible %s -a 'rm -rf %s' " % (self.hosts, self.to_path + "/%s" % f)
                    put = commands.getoutput(ans_cmd)
                    ret +=  u'  D  %s %s ' % (f , [l for l in put.split("\n")][0].split("|")[1].strip())
            else:
                ret += u" 无"
        else:
            ret += u" 无删除列表文件 \n"
        return ret



# coding:utf-8
import subprocess, os, time, commands, sys


class gittool:
    remote = "origin"
    curr_branch = ""

    def __init__(self, repoPath):
        self.path = repoPath
        os.chdir(repoPath)

    def diff(self, commi1, commit2):
        return self.__run("git diff %s  %s --name-status | grep -v .svn | grep -v .idea")

    def checkout(self, branch, isNew=False):
        return self.__run("git checkout " + (' -b ' if isNew else "") + branch)

    def merge(self, branch):
        return self.__run("git merge " + branch)

    def commit(self, commitinfo):
        res = self.__run("git commit -am '%s' " % commitinfo)
        ret = []
        for i in res:
            ret.append(i.strip())
        return ret

    def fetch(self, remote=""):
        return self.__run("git fetch -v " + (remote if remote != '' else " --all"))

    def log(self, full=False):
        if full:
            return self.__run('git log -n 30')
        else:
            return self.__run('git log --pretty=format:"%h | %ad | %s | %ae |%an " --date=local -n 50')

    def status(self):
        return self.__run("git status -s ")

    def push(self, remote, branch):
        cmd = "git push " + remote.strip() + " " + branch.strip()
        return self.__run(cmd)

    def pull(self, branch="", remote=""):
        branch = branch if branch != '' else self.curr_branch
        return self.__run("git pull " + remote.strip() + " " + branch.strip())

    def show(self,tagName):
        res = self.__run("git show --name-status --pretty=format:'%h | %ad | %s | %ae |%an #br' --date=local " + tagName)
        return res

    def tag(self, tagName=None, tagDesc=None, showTag=False):
        if showTag:
            return self.__run("git tag %s -v" % tagName)
        else:
            if None == tagName:
                return self.__run("git tag")
            else:
                if None == tagDesc:
                    raise Exception(u"必须输标签注释")
                cmd = " git tag -a %s -m '%s' " % (tagName, tagDesc)
                self.__run(cmd)
                return ["create tag success"]

    def reset(self, to=None):
        return self.__run("git reset " + "--hard " + to if to != "" else "")

    def branch(self):
        return [x.replace("*", "") for x in self.__run("git branch")]

    def remote_list(self):
        cmd = "git remote -v |  awk '{print $1}' | uniq"
        return self.__run(cmd)

    def current_branch(self):
        branchs = self.__run("git branch")
        for x in branchs:
            if x.find("*") != -1:
                return x.strip().replace('*', '')
        return None

    def __run(self, cmd):
        res = commands.getoutput(cmd)
        print "cmd:" + cmd
        return [x.strip().replace("\t", '    ') for x in res.split("\n")]




阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页