Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the new name of a renamed file in git

Tags:

git

I'm looking through git history, and I've found some file of interest. Unfortunately, it's been renamed! Is there a tidy way to discover what the new path to the file is?

My current approach is

[dbn repo]$ git log -- -1 --pretty=oneline old_directory/interesting_file.py
5ee1cf move old_directory files
[dbn repo]$ git log --stat -1 5ee1cf
commit 5ee1cf
Author: oh, it was me, the scoundral <[email protected]>

    move old_directory files

{old_directory => new_directory}/interesting_file.py

I could collapse this into a one-liner, but the move commit may have a bunch of other stuff in it that I don't care about.

background - I'm doing this manually now, but it's part of some archeology work I'm hoping to script up, so it would be nice to have a solution that could fit in a script.

like image 488
dbn Avatar asked Feb 02 '26 21:02

dbn


1 Answers

Update July 2025

git-whatchanged(1) is as of Git 2.50.0 “nominated for removal”.

Original

Maybe this can help:

#!/usr/bin/env python3

import sys
import subprocess

# Usage: ./script <file>
file = sys.argv[1]
search_next = True
while search_next:
    sha1 = subprocess.check_output(["git", "log", "--format=%H", "-1", "--", file]).rstrip().decode()
    if sha1 == '':
        exit(0)
    file_stat = subprocess.check_output(["git", "whatchanged", "--format=", "-1", sha1]).strip().decode()
    for line in file_stat.splitlines():
        columns = line.split()
        change_type = columns[4]
        old_file = columns[5]
        if change_type.startswith("R") and old_file == file:
            print(f"File ‘{file}’ was renamed to ‘{columns[6]}’ in commit {sha1}")
            file = columns[6]
            search_next = True
            break
        search_next = False

git whatchanged has less annoying to parse “stat” output.

You can apparently pass git-log(1)’s -M switch to git-whatchanged(1) (i.e. the thing that controls the file difference detection).

like image 146
Guildenstern Avatar answered Feb 05 '26 13:02

Guildenstern



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!