How to automatically invoke a script before a git

2020-06-08 16:40发布

问题:

Here's my use case: I commit PNGs and other stuff in my Git repo. I would like to apply a specific process to every PNGs I would like to commit and this is the result of the process I finally want to commit (the potential modified PNG).

At the beginning I thought about a hook (like a pre-commit) but it's a little weird because the process will change the file so I will need to re-add it! And according to what I read, there is no pre-add hook (or something like that).

May be a solution is to create a git alias ? But I don't want to change - too much - the way people work, I'm searching for a smooth and transparent way.

If you have a clue... even if the clue is to change my process idea.

回答1:

You may want to consider a smudge & clean filter, with the clean being applied during the git add, and the smudge during checkout. These can be allocated by file type. Look at the 'git attributes(5)' man page and Git SCM book : Git Attributes.



回答2:

There may be a good reason to use clean instead, but there's actually nothing preventing you from re-adding the files during the pre-commit hook, which is a bit more intuitive in my opinion.

Your pre-commit would look something like:

*run your PNG processing here* (after processing completes) git add *.png

The commit will then continue as usual. If you want to get fancy you can throw an exit 1 in there when something goes wrong with the compression, and it will stop the commit.



回答3:

I did something similar to disso, using gulp and gulp-git.

var git = require('gulp-git')

// ... other tasks

gulp.task('add', function(){
  return gulp.src('cdn/**')
    .pipe(git.add())
})

This add task is then called at the end of everything else. Then I have gulp set up with a pre-commit hook. Works like a charm.

So in your case, the full file might look something like:

var gulp = require('gulp')
var $ = require('gulp-load-plugins')()
var runSequence = require('run-sequence')

gulp.task('default', function () {
  return runSequence(
    'images',
    'add'
    )
})

gulp.task('images', function() {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
})

gulp.task('add', function(){
  return gulp.src('dist/**')
    .pipe($.git.add())
})

(Note that I haven't tested it... I got the images task code from Google.)