[Python] My git operation through GitPython results in the same file be treated as completely...

Discussão em 'Python' iniciado por Stack, Julho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a script that clone a project, modify the specific file, and then make a git push. Currently I'm encountering a problem that when I'm trying to update the content of the file, git will treat the whole file as a complete diff from the original file. I'm wondering whether that's the problem with my git operations or file modify strategy. Here's my code:

    def main():
    print("开始处理本地仓库...")
    try:
    repo = Repo.clone_from(AUTH_REPO_URL, LOCAL_REPO_PATH, branch=SOURCE_BRANCH)

    repo.git.checkout(SOURCE_BRANCH)

    target_path = os.path.join(LOCAL_REPO_PATH, TARGET_FILE)

    if os.path.isfile(target_path):
    with open(target_path, 'r', encoding='utf-8') as f:
    original_content = f.read()

    repo.git.checkout('-b', TARGET_BRANCH)

    modify_file(target_path)


    with repo.config_writer() as config:
    config.set_value("user", "name", "Automation Script")
    config.set_value("user", "email", "automation@example.com")


    if repo.is_dirty():
    repo.index.add([TARGET_FILE])

    repo.index.commit(COMMIT_MSG)

    origin = repo.remote(name="origin")
    origin.push(TARGET_BRANCH)
    else:
    origin = repo.remote(name="origin")
    origin.push(TARGET_BRANCH)

    except git.exc.GitCommandError as e:
    print(f"❌ {str(e)}")
    except Exception as e:
    print(f"❌ {str(e)}")
    finally:
    print(" Done")


    def modify_file(file_path):

    try:
    with open(file_path, 'r', encoding='utf-8') as f:
    content = f.read()
    f.close()

    new_content = content + "test docsss"


    #AI's suggestion to keep file unchanged
    import stat
    original_stats = os.stat(file_path)

    with open(file_path, 'r+', encoding='utf-8') as f:
    f.seek(0)
    f.write(new_content)
    f.truncate()

    os.chmod(file_path, original_stats.st_mode)
    os.utime(file_path, (original_stats.st_atime, original_stats.st_mtime))


    return True

    except Exception as e:
    ...


    [​IMG]

    Any answers are appreciated!

    Continue reading...

Compartilhe esta Página