Make a branch with a small subset of changes in Git



  • So, I've made maybe 10 commits on a branch in various C# projects.

    I'd like to make a branch containing only my changes to one of those projects, so I can have some hope of it getting through a code review.

    Google does not help with a problem like this.

    I should be able to localize this to only changes in one directory?



  • @magus You should, but Git is Git.

    You can do what you want if you're ok with throwing away revision history by just doing this:

    1. Check out your branch with all the changes
    2. Copy the one project you're interested in somewhere outside of Git's purview (desktop or where ever)
    3. Check out the "develop" branch or whatever branch is the original
    4. Copy your project back in, let Git detect the changes
    5. Make a commit on a new branch
    6. Create the pull request from that new branch

    If you want to do this and preserve revision history, you can do this but it makes for a messy repo:

    1. Tell your Git client to make a "reverse commit" between your current up to date branch and the original branch. ("reverse commit" meaning to generate a commit that just undoes all the changes from the other commits, how you do this depends on your Git client but I know SourceTree is capable of it)
    2. Go into your staging browser and remove the one project you're interested, but keeping the other changes in the reverse commit
    3. Push the reverse commit

    Basically this version you'll have all the changes for all the projects, but then the last change is one that undoes all the projects except the specific one you're interested in. It's still going to make for a messy and confusing pull request.

    (And yes this is WAY easier in TFS.)



  • @blakeyrat At this point, I don't think I care about the commit history all that much, since all the changes are implementing Stylecop rules, so I think I'll go for the first option.



  • @magus Oh yeah. In that case, do the first option and you can just put in "implement stylecop rules" for the commit message. That makes it easier.



  • For posterity, you can preserve history and keep your repo clean with git filter-branch --subdirectory-filter but every time I have ever needed to do that I've had to read the documentation for an hour.



  • @lb_ Good to know never to bother.


Log in to reply