2
"scripts": {
    "cr": "git commit -am ${message} && git pull origin master --rebase && git push --force",
}

I'm trying to figure out how to run the above with something like:

# yarn cr "commit message"
RobC
  • 22,977
  • 20
  • 73
  • 80
antonpug
  • 13,724
  • 28
  • 88
  • 129
  • 1
    Seems like that would work better as a shell alias? Make sure to use `--force-with-lease` to avoid races. – Ry- Nov 07 '19 at 00:43
  • You can try to modify the whole package.json file to substitute any of its part. You need to parse JSON first, then change the corresponding key value, then stringify the resulting JSON and save it to file. – Arfeo Nov 07 '19 at 01:00
  • There has to be a simple solution to this I feel like? And shell alias would work, but I want this to be easily re-usable by anyone who pulls down the project. – antonpug Nov 07 '19 at 02:12

2 Answers2

1

Yes. you can do something like this

"scripts": {
{
  "cr": "f(){ git commit -am $1;};f",

}
}

and yarn run cr -- 'commit message'

you can pass n number of arguments seperated with space and can be accesible via $1 ,$2 ..

NIsham Mahsin
  • 340
  • 5
  • 18
0

The pattern sh -c 'shell_command' works on *nix and Windows Powershell. Then, you can use $0, $1, and so on to access the command line arguments. So write this in your package.json:

"scripts": {
    "cr": "sh -c 'git commit -am $0 && git pull origin master --rebase && git push --force'",
}

Now you can run this command in a terminal:

yarn cr commit_message
Abdollah
  • 4,579
  • 3
  • 29
  • 49
  • This will fail on Windows when the default shell utilized by npm is `cmd.exe` – RobC Nov 09 '19 at 10:09
  • Thanks for your point. I tested it on Ubuntu and Windows Powershell and it worked fine. – Abdollah Nov 09 '19 at 10:20
  • Sure Ubuntu is _*nix_ in which case npm uses `sh` by default. Powershell will typically use `cmd` by default. The [npm docs](https://docs.npmjs.com/cli/run-script) state: _"By default, on Unix-like systems it is the /bin/sh command, on Windows it is the cmd.exe."_. For true cross-platform compatibility you'll need to shell-out from a node.js script - for instance see my answer [here](https://stackoverflow.com/questions/55470546/pass-git-commit-message-to-npm-script-and-append-to-predefined-string). – RobC Nov 09 '19 at 10:30