Eduard Daduya Eduard Daduya - 4 months ago 18
Git Question

Run an external program upon git add a specific file with the specific file as a parameter

So here's the thing, I've got a binary file that I can

git diff
using
iconv
via the
git bash
using this type of convertion method.

textconv = "iconv -f ISO-8859-1 -t UTF-8//IGNORE"


I'm not sure if the binary file encoding is
ISO-8859-1
because there are a lot of special characters left whenever I use
git diff
.

Main problem: I cannot view the diff on our github. So what I did was to convert the binary file to a much readable file to get rid of all those special characters. My lil piece of code produces an
.xml
file. I want to include this file as a
source code
basis so that whenever a merge request is made, the need for a
git diff
via
bash
is eliminated.

What I'm after: I would like to execute the program upon using
git add
on a specific file. I've read about
aliases
, but I'm not exactly sure how to use the file as a parameter, and to invoke it whenever the specific file type is added. Should I modify the program to read the file type?

Summary: Upon using
git add
(or maybe an alias) on a specific file type, I would like to run an external command to convert the file, then invoke git add to include the converted file.

TIA :)

UPDATE: I am now experimenting with
alias
and assign it as i.e.
add-filetype = "!../convert.er my.file && git commit my.file -m 'Auto-generated file on filetype add'"
so I can just run
git add-filetype my.file
.

Solution:
Finally I came up with this on my gitconfig:

[alias]
add-filetype = "!f(){ \
../convert.er $1; \
git add $1.xml; \
git commit $1.xml -m \"Auto Generate XML file\"; \
); f"


and simple type
git add-filetype my.file
on git-bash.

Thanks @VonC!

Answer

afaik bash is for linux based machines right? Our release team uses windows, so I'm now looking into working with batch files

That will work: git uses git-bash bases on msys2, which means any Linux command in the git alias will be interpreted by that shell, even on Windows.

my_alias = "!f() { 〈your complex command〉 }; f"

See "One weird trick for powerful Git aliases "


The OP Eduard Daduya embedded the script in the alias:

[alias]
    add-filetype = "!f(){ \
                        ../convert.er $1; \
                        git add $1.xml; \
                        git commit $1.xml -m \"Auto Generate XML file\"; \
                    ); f"

But that same script could have been written as:

git-add-filetype:

/full/path/to/convert.er $1
git add $1.xml; \
git commit $1.xml -m \"Auto Generate XML file\"

Any git-xxx script (no extension, in the %PATH%) can be called as git xxx: no git alias needed in that case.