Configure git to ignore a range of code

I had been asked to recompile a VPAID ActionScript SWF with a minor change to the code, but I had a lot of stuff lingering in my build I would like to temporarily disable, by commenting out, then only commit the minor change asked by using prune, ie: git add -p file.as. There was a lot of things that had changed, and it was becoming difficult to spot the changes, with all of the commented out code everywhere.

A few Google searches later, I stumbled upon a neat solution which meets my particular needs. I can mark ranges of code, and have git commit / diff ignore them. Then I can mark things that are commented out, and/or not meant for commit, and they will not be in my way.

1
2
3
4
5
6
7
8
9
cd /your_project_path

# 1. Create/Open gitattributes file (will be committed into repo):
echo "*.as filter=gitignore" > .gitattributes
# OR (won't be committed into repo)
echo "*.as filter=gitignore" > .git/info/attributes

# 2. Define the gitignore filter in your gitconfig
git config --global filter.gitignore.clean "sed '/\/\/gitIgnoreBegin$/,/\/\/gitIgnoreEnd$/d'"

Then in your code, you can mark sections of code to be skipped. So if I add this block of code below…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public function get thisWillRemain():Boolean {
var a:String = "blah";
return true;
}
/* //gitIgnoreBegin
public function get thisIsDevOnly():Boolean {
var a:String = "blah";
return false;
}
*/ //gitIgnoreEnd
/*
public function get thisRemainsButIsDisabled():Number {
var a:String = "blah";
return true;
}
*/
public function get thisTooRemains():Boolean {
var a:String = "blah";
return true;
}

A “git diff” would show me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
+ public function get thisWillRemain():Boolean {
+ var a:String = "blah";
+ return true;
+ }
+ /*
+ public function get thisRemainsButIsDisabled():Number {
+ var a:String = "blah";
+ return true;
+ }
+ */
+ public function get thisTooRemains():Boolean {
+ var a:String = "blah";
+ return true;
+ }

Note how the function “thisIsDevOnly()” was not displayed. It was marked as a range ignore using “//gitIgnoreBegin” and “//gitIgnoreEnd”. Lines ending with these strings will be ignored in git.

This is of course only going to apply to files matching *.as, and only works if the language allows “//“ comments. With minor modification, this should work in most any language.