Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stage changes in git based on regex

Tags:

git

A lot of my debug code is wrapped in a header/footer. Usually I run a script that just removes all of it from source before I stage and commit the changes. If the debug code needs to persist a commit I'll run git add -p and stage the chunks individually.

My question is if it's possible to stage changes based on a regex? For example, given this snippet of javascript:

function littleNinja( sword ) {
    /* debug:start */
    console.log( sword );
    /* debug:stop */
    // do stuff
}

I don't want git to stage the lines between and including debug:start and debug:stop, and my hope is that this process could be automated.

like image 576
Trevor Norris Avatar asked Oct 26 '11 18:10

Trevor Norris


People also ask

What is stage changes in git?

When you're ready to save a copy of the current state of the project, you stage changes with git add . After you're happy with the staged snapshot, you commit it to the project history with git commit . The git reset command is used to undo a commit or staged snapshot.

Is git add the same as stage?

As the documentation says, git stage is just a synonym for git add , so there is no difference in usage.

What are staged files in git?

Git has three main states that your files can reside in: modified, staged, and committed: Modified means that you have changed the file but have not committed it to your database yet. Staged means that you have marked a modified file in its current version to go into your next commit snapshot.

Do you have to stage changes before commit?

You should separate them by staging the bug fixes and committing those first and then staging the improvements to Feature B and making a second commit.


1 Answers

A good way of doing this is to use clean and smudge filters to filter out the marked lines as they are staged. (The description below is essentially the same as the procedure described in that section of "Pro Git", and which is very similar to that in the git attributes documentation.) First of all, we need a command that removes the lines between (and including) each debug:start and debug:end — fortunately, this is a simple job with sed:

sed '/debug:start/,/debug:stop/d' < foo.js

Now create a .gitattributes file in the top level of your git repository which contains the following line:

*.js filter=strip-debug

And now define what the strip-debug filter does both when 'cleaning' (on staging) or 'smudging' (on checkout):

git config filter.strip-debug.clean "sed '/debug:start/,/debug:stop/d'"
git config filter.strip-debug.smudge cat

I've (very briefly) tested this and it seems to do what you want.

like image 185
Mark Longair Avatar answered Nov 15 '22 21:11

Mark Longair