Esempio n. 1
0
def pr(cc, repo):
    # squash commit, list from and into branches (both local and remote). if need, notify codereviewer.
    base = ''
    cutie.cprint('wait', (cc.value('git-talk', 'wait')))
    cutie.cprint('', '')
    tt = cc.value('access', 'token')
    if len(tt) < 5:
        cutie.cprint(
            'error', 'invalid token, please config in .git_talk.ini correctly')
        return
    gh = github_api.GitHubAPI(cc.value('access', 'git_api'),
                              cc.value('access', 'token'))
    gh.set_repo(repo['url'])
    current_b, status = stts.current_status(cc, repo)
    command = [['git', 'branch']]
    b, _ = gfunc.subprocess_cmd(repo['path'], command)
    # b = gfunc.execute_git_command(repo['path'], 'branch')
    br_list = b[0].split("\n")
    head = cutie.select_propmt(cc.value('pr', 'head'),
                               br_list).replace('*', '')
    head = head.strip()
    if head.startswith(repo["task"]):
        base = 'dev'
    elif head.startswith(repo["hotfix"]):
        base = 'master'

    #elif head == 'dev':
    #    base = 'release'
    #elif head == 'release':
    #    base = 'master'
    #else:
    #    base = ''
    #base = cutie.select_propmt(cc.value('pr','base'),b).replace('*','')
    base = base.strip()
    if head == base or base == '':
        cutie.cprint('error', (cc.value('git-talk', 'error')))
    else:
        title = cutie.get_input(cc.value('pr', 'title'))
        #summary = cutie.get_input(cc.value('pr','summary'))
        detail = cutie.get_input(cc.value('pr', 'detail'))
        #detail = summary.upper() + '\n' + detail
        pr = gh.pull_request(title, detail, head, base)
        if pr is None:
            cutie.cprint('error', (cc.value('git-talk', 'error')))
        else:
            cutie.cprint('info', (cc.value('pr', 'done').format(base, head)))

    b = gfunc.subprocess_cmd(repo['path'], [["git", "checkout", current_b]])
Esempio n. 2
0
def current_status(cc, repo):
    cutie.cprint('wait', 'updating the git status...')
    command = [["git", "fetch", "--all"], ["git", "status", "-v", "-s", "-b"]]
    b, error = gfunc.subprocess_cmd(repo['path'], command, display=False)
    if error == 0:
        #  result windows   ## dev...origin/dev [behind/head 2] or nothing if equal, not []
        #                   M git_talk/cmd.py --------> if head
        #                   blank line

        rs = b[1].split("\n")
        for i, r in enumerate(rs):
            if i == 0:
                current_branch, remote_status = '', ''
                if "..." not in r:  #no remote branch
                    current_branch = r
                else:
                    current_branch, remote_status = r.split("...")

                current_branch = current_branch.replace("##", "").strip()
                if "[" in remote_status:
                    remote_status = "[" + remote_status.split("[")[-1].split(
                        "]")[0].strip() + "]"
                else:
                    remote_status = "[=]"

        return current_branch, remote_status
    else:
        print(b)
        return "error", error
Esempio n. 3
0
def gitflow(cc, repo):
    '''
    create gitflow structure
    master=prod,release=release,dev=dev,hotfix=hotfix,feature=feature 
    '''
    #
    # git config --global alias.hist "log --graph --date-order --date=short --pretty=format:'%C(auto)%h%d %C(reset)%s %C(bold blue)%ce %C(reset)%C(green)%cr (%cd)'"

    #Usage:
    # git hist - Show the history of current branch
    # git hist --all - Show the graph of all branches (including remotes)
    # git hist master devel - Show the relationship between two or more branches
    # git hist --branches - Show all local branches

    # Add --topo-order to sort commits topologically, instead of by date (default in this alias)

    # Benefits:
    # Looks just like plain --decorate, so with separate colors for different branch names
    # Adds committer email
    # Adds commit relative and absolute date
    # Sorts commits by date
    # Setup:

    cmd = [["git", "hist", "--branches"]]

    b, error = gfunc.subprocess_cmd(repo['path'], cmd)
Esempio n. 4
0
def rebase(cc, repo):
    cutie.cprint('wait', (cc.value('git-talk', 'wait')))
    # get all branch from remote
    cutie.cprint('info', cc.value('rebase', 'remote_branch'))
    get_all_remote_brancb = [["git", "branch", "--all"]]

    b, error = gfunc.subprocess_cmd(repo['path'], get_all_remote_brancb)
    # clean the branch, remove * remotes
    if error == 1:
        return

    bs = b[0].split('\n')
    local_branches = []
    remote_branches = []
    current_branch = ''
    for i in bs:
        if '*' in i:
            i = i.replace('*', '')
            current_branch = i.strip()
        i = i.strip()
        if 'remotes/' in i:
            remote_branches.append(i.replace('remotes/', ''))
        else:
            local_branches.append(i)
    for i in remote_branches:
        local = i.split('/')[-1]
        if local not in local_branches:
            cutie.cprint('info', cc.value('rebase', 'no_local').format(i))
            remote_branch = [["git", "branch", "--track", local, i]]
            b, error = gfunc.subprocess_cmd(repo['path'], remote_branch)
        else:
            cutie.cprint('info', cc.value('rebase', 'pull').format(local))
            remote_branch = [["git", "checkout", local], ["git", "pull"]]
            b, error = gfunc.subprocess_cmd(repo['path'], remote_branch)
        if error == 1:
            break
    # merge master
    if error == 0:
        command = [["git", "checkout", "dev"], ["git", "merge", "master"],
                   ["git", "push"], ["git", "checkout", current_branch],
                   ["git", "merge", "master"]]
        # ["git","merge","master"],["git", "push"]]
        b, error = gfunc.subprocess_cmd(repo['path'], command)

    #print(remote_branches, local_branches)
    # cutie.cprint('info',cc.value('git-talk','error'))
    return error
Esempio n. 5
0
def git_simple(cc, repo):
    count = 0
    current_branch, remote_status = stts.current_status(cc, repo)
    c = [['git', 'checkout', 'master']]
    result = gfunc.subprocess_cmd(repo["path"], c)

    c = [['git', 'log', '--graph', '--oneline', '--decorate', '-2000']]
    result, error = gfunc.subprocess_cmd(repo["path"], c, display=False)
    if error != 0:
        cutie.cprint('error', result[0])
        return

    cutie.color_print(
        'WHITE',
        '\n----------------------- Git Graph (last 20 branch level event)-----------------------'
    )
    for r in result[0].split('\n'):
        if count > 20:
            break
        if '*' in r:
            if 'Merge pull request' in r:
                cutie.color_print('GREEN', string_filter(r))
                count += 1
            elif '(' in r:
                cutie.color_print('YELLOW', string_filter(r))
                count += 1
            else:
                pass
                # cutie.color_print('MAGENTA', string_filter(r))
                # count += 1
        else:
            cutie.color_print('WHITE', r)
            count += 1
    cutie.color_print(
        'WHITE',
        '\n----------------------- Git Graph             (end)          -----------------------\n'
    )
    c = [['git', 'checkout', current_branch]]
    result, error = gfunc.subprocess_cmd(repo["path"], c)
Esempio n. 6
0
def add_tag(cc, repo):
    error = "no defined error"
    current_branch, remote_status = stts.current_status(cc,repo)
    command = [["git", "checkout", "master"]]
    b, error = gfunc.subprocess_cmd(repo['path'], command)
    #j = control_package(cc,repo["path"])
    version = cutie.get_input(
        cc.value('pr', 'tag').format(repo["version"]))
    comment = cutie.get_input(cc.value('commit', 'comment')) 
    if len(version) >= 5  and version.count(".") == 2 :
        repo["version"] = version
        #control_package(cc,repo["path"], j)

        command = [["git","add",".","&&","git","commit","-m",'"tag version bump up"'],["git", "checkout", "dev","&&", "git", "pull"],
                    ["git", "checkout", "master","&&", "git", "pull"],
                    ["git", "merge", "dev"], 
                    ["git", "tag", "-a", version, "-m", '"' + comment + '"'],
                    ["git","push","origin","--tag"]]
        cutie.cprint('info', 'creating tag {} and its changelog.md, please wait...'.format(version))
        b, error = gfunc.subprocess_cmd(repo['path'], command)
        
        changelog.main(repo = repo["path"], description=comment ,latest_version= version )

        # auto-changelog -p && git add CHANGELOG.md
        command = [["git","add","."],["git", "commit", "-m", "'Others: version bump to: " + version + "'"], 
                   ["git", "push", "origin","HEAD:master"]]
        b, error = gfunc.subprocess_cmd(repo['path'], command)
        #menu.bumper_changelog(cc,repo)
        # repo['version'] = version
        # rp = cc.value('my_repositories', repo["name"]).split(
        #         "VERSION=")[0] + "VERSION=" + version
        # cc.save('current_repo', repo["name"], rp)
        cc.save_json("repo_json",repo["name"],repo)
    else:
        pass
    command = [["git","checkout",current_branch]]
    b, error = gfunc.subprocess_cmd(repo['path'], command)
    return error
Esempio n. 7
0
def commit(cc, repo, comment="", up_stream="origin"):
    if repo['branch'] in ('master'):
        cutie.cprint('alert',
                     (cc.value('commit', 'error').format(repo['branch'])))
    else:
        summary = ''
        names = cc.value('commit', 'commit_prefix').strip().split(",")
        while len(summary) < 1:
            summary = cutie.select_propmt(cc.value('commit', 'summary'), names)
            if summary.lower() in ('exit', 'cancel'):
                cutie.get_exit()
                return None
        while len(comment) < 1:
            comment = cutie.get_input(cc.value('commit', 'comment'))
        comment = summary + ': ' + comment
        cutie.cprint('wait', (cc.value('git-talk', 'wait')))
        path = repo['path']
        # git_path = "C:/Program Files/Git/cmd/git.exe"
        command = [["git", "add", "."], ["git", "commit", "-m", comment],
                   ["git", "pull", up_stream],
                   ["git", "push", "-u", up_stream, repo['branch'].strip()]]
        b, error = gfunc.subprocess_cmd(path, command)
Esempio n. 8
0
def create_project(cc):
    repo = {}
    # if prompt_yn(cc.value('project','create_doyou')):
    # input directory and git clone
    #pro = cutie.get_input(cc.value('project','project_name'))
    cnt = 0

    user, password = '', ''
    if (cutie.prompt_yn("Do you use ssh connect to repository?")):
        repo["connection-ssh"] = True
    else:
        repo["connection-ssh"] = False

    while True:
        cnt += 1
        repo['url'] = cutie.get_input(cc.value('project', 'project_url'))
        repo['name'] = stts.get_repo_name(url=repo['url'])
        # {"name": "ddo-data-images",
        # "path": "c:/github/ddo-data-images",
        # "url": "https://github.customerlabs.com.au/iagcl/ddo-data-images.git",
        if repo['name']:
            break
        elif cnt > 2:
            cutie.cprint('error', "try failed, exit")
            cutie.get_exit()
        else:
            cutie.cprint('error', "invalid url, must contain .git")

    path = cutie.linux_path(
        cutie.get_input(cc.value('project', 'path_message')))
    repo["path"] = path
    if not repo["connection-ssh"]:
        user = cutie.get_input(cc.value('project', 'user_message'))
        password = cutie.get_pass(cc.value('project', 'password_message'))
    repo["up-stream"] = ""
    repo["version"] = cutie.get_input("Latest Tag Version (x.x.x) format:")
    repo["task"] = cutie.get_input("task branch prefix (CLD- ):")
    repo["hotfix"] = cutie.get_input("hotfix branch prefix (HFX- ):")
    repo["is-current"] = False
    repo["git-flow"] = True
    repo["descption"] = ""
    repo["jira-link"] = ""
    repo["issue"] = ""

    # if cddir(path) :
    if cutie.prompt_yn(
            cc.value('project', 'gitclone_message').format(repo['url'], path)):
        cutie.cprint('wait', cc.value('git-talk', 'wait'))
        try:
            created = False
            if not os.path.exists(path):
                os.mkdir(path)

            # cutie.cprint('info','my_repositories',repo['repo'],path)
            # To save credentials you can clone Git repository by setting a username and password on the command line:
            # https://www.shellhacks.com/git-config-username-password-store-credentials/
            if not repo["connection-ssh"]:
                git_url_user_password = repo['url'].replace(
                    "://", "://" + user + ":" + password + "@")
            else:
                git_url_user_password = repo['url']

            command = [['git', 'clone', git_url_user_password]]
            b, _ = gfunc.subprocess_cmd(path, command)
            # b = gfunc.execute_git_command(
            #     path, 'clone {0}'.format(git_url_user_password))

            created = True
            # else:
            #     if prompt_yn(cc.value('project','gitclone_existing').format(repo['url'],path)):
            #         created = True
            if created:
                repo["path"] = cutie.linux_path(
                    os.path.join(path, repo["name"]))
                #gitflow(repo["path"], cc)
                # rp = repo["path"] + "|" + repo["url"] + "|VERSION=0.0.0"
                cc.save_json('repo_json', repo["name"], repo)

                cutie.cprint('done', cc.value('git-talk', 'done'))
                repo["branch"] = branches.pick_branch(cc, repo)
        except Exception as e:
            cutie.cprint('error', str(e))
            cutie.cprint('error', cc.value('git-talk', 'error'))
            cutie.get_exit()
        else:
            cutie.get_exit()
    else:
        cutie.get_exit()
    return repo
Esempio n. 9
0
def pick_branch(cc, repo):
    
    path = repo['path']
    cc.save("access","current_repo", repo["name"])
    command =[['git','branch']]
    b,error = gfunc. subprocess_cmd(path, command)
    selected_branch = ''
    working_list = []
    for ib in b[0].split('\n'):
        if ib.strip():
            if ib.strip().startswith('*'):
                selected_branch = ib.strip().replace('*', '')
            if ib.strip().replace('*', '') not in ('master', 'dev', 'release'):
                working_list.append(ib)
    create_b = cc.value("branch", "create_branch")
    working_list.append(create_b)
    delete_b = cc.value("branch", "close_branch")
    working_list.append(delete_b)

    name = cutie.select_propmt(cc.value('project', 'branch'),
                         working_list).replace('*', '').strip()
    if not cutie.get_exit(name):
        # TODO: will config prefix_ ,created by xxxxx and linked issue or jira
        if name == create_b:
            br_type = {'feature': repo["task"], 'hotfix': repo["hotfix"]}
            ty = cutie.select_propmt(cc.value('branch', 'branch_type'), [
                               'feature', 'hotfix']).strip()
            if not cutie.get_exit(ty):
                if ty == 'hotfix':
                    nb_from = 'master'
                else:
                    nb_from = 'dev'

                nb = cutie.get_input(cc.value('branch', 'new_branch'))
                nb = br_type[ty] + nb
                cutie.cprint('info', 'creating {0} branch: {1}'.format(ty, nb))
                if nb not in b:
                    cmd_branch = [["git", "checkout", nb_from], [
                        "git", "pull"], ["git", "checkout", "-b", nb],["git","push","--set-upstream", "origin", nb]]
                    b, error = gfunc.subprocess_cmd(path, cmd_branch)
                    if error == 0:
                        selected_branch = nb
                    else:
                        cutie.cprint('error', cc.value('git-talk', 'error'))

                    # b = gfunc. subprocess_cmd(path, 'checkout {0}'.format(nb_from))
                    # b = gfunc. subprocess_cmd(path, 'checkout -b {0}'.format(nb))
                else:
                    cutie.cprint('alarm', cc.value(
                    'branch', 'existing_branch').fromat(nb))
        elif name == delete_b:
            command = [["git", "branch"]]
            b, error = gfunc.subprocess_cmd(repo['path'], command)
            if error == 0:
                ty = cutie.select_propmt(
                    cc.value('branch', 'close_picked'), b[0].split('\n')).strip()
                if not cutie.get_exit(ty):
                    if '*' in ty:
                        cutie.cprint('alarm', cc.value(
                            'branch', 'current_alarm'))
                    else:
                        b, error = gfunc.subprocess_cmd(repo['path'], [["git", "branch", "-d", ty]])
                        if error == 1 :
                            if cutie.prompt_yn(cc.value('branch', 'confirm_delete').format(ty)):
                                b, error = gfunc.subprocess_cmd(repo['path'], [["git", "branch", "-D", ty]])
                                if error == 0 :
                                    b, error = gfunc.subprocess_cmd(repo['path'], [["git", "push", "origin", "--delete",ty]])
                        else:
                            b, error = gfunc.subprocess_cmd(repo['path'], [["git", "push", "origin", "--delete",ty]])
        else:
            # checkout the branch
            if name != selected_branch:
                command =[['git','checkout', name]]
                bb,error = gfunc. subprocess_cmd(path,command )
                if error == 0:
                    cutie.cprint('info', cc.value(
                        'project', 'checkout').format(name))
                    selected_branch = name
                else:
                    cutie.cprint('error', bb + '------------\n error:', str(error))
                    cutie.cprint('info', cc.value('project', 'checkout_error').format(name))
                    cutie.cprint('error', cc.value('git-talk', 'error'))

    repo['branch'] = selected_branch
    cc.save_json("repo_json", repo["name"], repo)
    return repo