Home > Enterprise >  how to run git push conditionally
how to run git push conditionally

Time:06-01

I want to push changed files using:

git add . 
git commit -m 'build: maintenance' 
git push

but I want to ignore these commands if package-lock.json file is the only changed file

how to configure it to push the changed files only if there is at least any file other than package-lock.json

and it would be nice to get it to run in cross-platforms

solved by creating a js script and here is the solution

import { execSync } from 'node:child_process';

/**
 * push changed files, ignore if package-lock.json is the only changed file
 */
export function push() {
  let changed = execSync(
    'git add . && git diff-index --cached --name-only HEAD'
  )
    .toString()
    .split('\n')
    .filter((el) => el.trim() !== '' && el.trim() !== 'package-lock.json');

  if (changed.length > 0) {
    execSync("git commit -m 'build: maintenance' && git push");
  }
}

thank you guys for your appreciated help <3

CodePudding user response:

This lists the files with staged changes:

git diff-index --cached --name-only HEAD

Assuming you're using the bash shell, you can check whether there's anything there besides package-lock.json:

git add .
if git diff-index --cached --name-only HEAD | grep -vsxF package-lock.json; then
    git commit -m 'build: maintenance'
    git push
fi

I'm assuming that package-lock.json is in the root; adjust to taste.

  •  Tags:  
  • git
  • Related