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

用我的代码要标注来源!


# 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")]




要实现Git对比不同分支的代码增量信息,可以使用JGit库来操作Git仓库。以下是一个简单的Java代码示例,用于比较两个分支之间的代码差异: ```java import java.io.IOException; import java.util.List; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.diff.RawTextComparator; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.CanonicalTreeParser; import org.eclipse.jgit.treewalk.TreeWalk; public class GitDiff { public static void main(String[] args) throws IOException, GitAPIException { String repositoryPath = "/path/to/your/repository"; // replace with your repository path String oldBranch = "old-branch"; // replace with the name of the old branch String newBranch = "new-branch"; // replace with the name of the new branch try (Repository repository = Git.open(new File(repositoryPath)).getRepository()) { ObjectId oldHead = repository.resolve(oldBranch + "^{commit}"); ObjectId newHead = repository.resolve(newBranch + "^{commit}"); try (RevWalk revWalk = new RevWalk(repository)) { RevCommit oldCommit = revWalk.parseCommit(oldHead); RevCommit newCommit = revWalk.parseCommit(newHead); CanonicalTreeParser oldTreeParser = new CanonicalTreeParser(); try (ObjectReader oldReader = repository.newObjectReader()) { oldTreeParser.reset(oldReader, oldCommit.getTree().getId()); } CanonicalTreeParser newTreeParser = new CanonicalTreeParser(); try (ObjectReader newReader = repository.newObjectReader()) { newTreeParser.reset(newReader, newCommit.getTree().getId()); } try (Git git = new Git(repository)) { List<DiffEntry> diffs = git.diff() .setOldTree(oldTreeParser) .setNewTree(newTreeParser) .call(); for (DiffEntry diff : diffs) { System.out.println("Diff: " + diff.getChangeType() + " " + diff.getNewPath()); try (DiffFormatter formatter = new DiffFormatter(System.out)) { formatter.setRepository(repository); formatter.setDiffComparator(RawTextComparator.DEFAULT); formatter.format(diff); } } } } } } } ``` 在此示例中,我们使用JGit库打开Git仓库,并使用`Git.open()`方法获取仓库的引用。然后,我们解析旧和新分支的提交ID,并将它们传递给`CanonicalTreeParser`,以便可以比较它们之间的树差异。最后,我们使用`Git.diff()`方法比较树,并使用`DiffFormatter`格式化差异输出。 请注意,这只是一个基本示例,您可能需要根据您的需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值