GitPython的Git、linux shell命令替代方案

2024-09-29 06:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取所有合并的分支以及过时的分支(3个月内未使用) 我已经为LinuxShell编写了命令。但是,我需要用Gitpyhon编写一个替代命令。有人能帮我吗

self.cmd("git branch --merged master") # <-- Display, merged branches
self.cmd(                              # <-- Display stale branches
    "for branch in `git branch -r | grep -v HEAD`;"
    "do echo -e `git log --before=\"3 months\" --no-merges"
    " -n 1 --format=\"%cr | %an | %ae | \""
    " $branch | head -n 1` \\t$branch; done | sort -M"
)

Tags: ingit命令selfmastercmdbranchfor
1条回答
网友
1楼 · 发布于 2024-09-29 06:26:44

下面是关于如何在GitPython中直接翻译git命令的提示

  1. 始终使用import git
  2. 使用g = git.Git()创建git处理程序
  3. 使用env = {'GIT_DIR': '/path/to/repo/.git', 'GIT_WORK_TREE': '/path/to/repo'}传递这两个变量,这样我们就可以在任何地方调用git命令。如果脚本涉及多个存储库,请记住切换变量值
  4. 对于命令,将git foo转换为g.foo(),将git foo-bar转换为g.foo_bar()。例如,git commit等于g.commit()git cherry-pick等于g.cherry_pick()
  5. 对于选项,将{}转换为{},{}转换为{},{}转换为{},{}转换为{},将{}转换为{}
  6. with_extended_output=True传递给命令,以便捕获status、stdout和stderr
  7. 使用try...catch...捕获命令错误。请注意,当stderr不是空的时,可能根本没有问题。即使命令成功,某些命令也会将结果打印到stderr
  8. 如果不想进行翻译,请调用g.execute()

现在试试你的命令。假设非裸存储库是/path/to/repo

import git
import logging

g = git.Git()
env = {'GIT_DIR': '/path/to/repo.git', 'GIT_WORK_TREE': '/path/to/repo'}
# git branch  merged master
try:
    status, stdout, stderr = g.branch(
        merged='master',
        env=env,
        with_extended_output=True)
    print(stdout.split('\n'))
except Exception as e:
    logging.exception(e)
    # more stuff

# git branch -r
stale_branches = []
try:
    status, stdout, stderr = g.branch(
        r=True,
        env=env
        with_extended_output=True)
    stale_branches += [l.strip() for l in stdout.split('\n')]
except Exception as e:
    logging.exception(e)
    # more stuff

for branch in stale_branches:
    if 'HEAD' in branch:
        continue
    # git log
    logs = []
    try:
        status, stdout, stderr = g.log(
            branch,
            before='3 months',
            no_merges=True,
            n=1,
            format='"%cr | %an | %ae | "',
            env=env,
            with_extended_output=True)
        logs += stdout.split('\n')
    except Exception as e:
        logging.exception(e)
        # more stuff

# leave the rest to you
        

对于某些命令,如git worktree add no-checkout foo HEADg.worktree('add', 'foo', 'HEAD', no_checkout=True)总是失败,因为它调用了无效的命令git worktree no-checkout add foo HEAD。在这种情况下,我们可以使用g.execute()。将整个命令转换为参数列表['git', 'worktree', 'add', ' no-checkout', 'foo', 'HEAD'],并将其传递给g.execute()

try:
    status, stdout, stderr = g.execute(
        ['git', 'worktree', 'add', ' no-checkout', 'foo', 'HEAD'],
        env=env,
        with_extended_output=True)
    print(stdout)
except Exception as e:
    logging.exception(e)
    # more stuff

相关问题 更多 >