Defining a loop within a script inside package.json - bash

Is it possible to include a for loop inside a package.json file to recurse into subdirectories and execute a command in each:
# .env File
DIRECTORIES="Dir1, Dir2"
# package.json file in parent directory
"scripts": {
"install-all-inefficient": "(cd ./dir/Dir1/ && npm install) && (cd ./dir/Dir2/ && npm install)",
"install-all-ideal": ". .env && functionToLoopThroughDirectoriesDefinedInEnvironmentVariables",
},
I was looking at this: Defining an array as an environment variable in node.js as an example for defining the array, and then trying to somehow use process.env.DIRECTORIES to create a loop without writing too much ugly bash script.

You can try :
"install-all-ideal": ". .env; for dir in \"${DIRECTORIES[#]}\"; do (cd \"$dir\" && npm install); done"
with .env :
DIRECTORIES=("Dir1" "Dir2")

Related

Iterating over directories containing a string shell script

I have a set of directories, 10 at the moment that are named client-1, client-2,..., client-10 and 1 directory that is named nestjs-wrapper
I want to iterate over the client directories, enter each of them and fire npm install and node index.js in every one.
I could do it by hand, but the number of clients may increment in the future so I would like to automate this process.
So the flow would be something like this:
in the parent directory I would like to fire nvm use to make sure I have the desired node version
then cd into each directory, fire npm install & node index.js
cd back to parent directory
repeat this until packages are installed in every client directory
run docker-compose up in a detached terminal
cd from parent directory into a nestjs-wrapper and start it in watch mode with npm run start:dev
This is the start of the attempt, it installs the packages in the client directories, now I would somehow need to do the rest of the flow:
pattern="/home/dario/my-folder/client"
for _dir in "${pattern}-"[[:digit:]]*; do
[ -d "$_dir" ] || continue;
pushd "$_dir" && npm install;
done
I would like to start docker-compose from the parent directory in a detached terminal.
To do this, I just created a new script named start-docker.sh in which I only have docker-compose up.
And after that open a separate dir in the parent directory (one that is not named client-) and run npm run start:dev in it.
So it would go something like:
pattern="client"
for _dir in "${pattern}-"[[:digit:]]*; do
[ -d "$_dir" ] || continue;
pushd "$_dir" && npm install && node index.js;
popd;
done
gnome-terminal -- ./start-docker.sh;
pushd nestjs_wrapper && npm run start:dev;
This does the trick, I switched back to relative pathnames. First I iterate over all the client directories and install the packages, then after that I bring up docker-compose and start the wrapper in watch mode.
Following the input from the comments, here is the working solution:
pattern="client"
for _dir in "${pattern}-"[[:digit:]]*; do
[ -d "$_dir" ] || continue;
pushd "$_dir" && npm install && node index.js;
popd;
done
gnome-terminal -- ./start-docker.sh;
pushd nestjs_wrapper && npm run start:dev;

Execute Shell file functions in Mac

I have the following shell file that contains this:
sh
nightlyTag() {
echo $1-alpha.$(date +%Y%m%d).$(($(date +%s%N)/1000000))
}
yarnPubCanaryVersion() {
if [ -z "$1" ]
then
echo "No version argument supplied, maybe you meant v1.0.0?"
return 1
fi
version=`nightlyTag $1`
yarn version --new-version $version --no-git-tag-version
npm publish --tag canary
git reset --hard HEAD
}
I make the file executable with chmod +x canary.sh, then I run it doing ./canary.sh then my terminal changes to sh-3.2$ then I try to run the functions in the terminal like this nightlyTag and I get
sh: nightlyTag: command not found
Same for yarnPubCanaryVersion.
I was looking at this SO question
You won't be able to run functions from the terminal after you run the script.
You need to source the script to do this:
source ./canary.sh
Or add the contents of the file to the .bashrc file or its equivalent, and then source it.
The source command is used to load any function file into the current shell.
Now once you call those functions you will get the expected output.
At the top of your sh file you need to include:
#! /path/to/bash
the path to the bash that you are using.

NPM call bash script with multiple arguments

I have created a bash script to automate the git release flow. This script takes one or multiple branch names as argument.
I can call the script in the terminal with: ./releaseGit.sh -b branch1 -b branch2
But I want to use the script with npm. My current package.json contains:
"scripts": {
(other scripts..)
"git-release": "scripts/releaseGit.sh -b $*"
}
But with this configuration I can only pass one branch as argument to the script. How can I change that?
works:
npm run git-release -b only-one-branch
Doesn't work:
npm run git-release -b first-branch -b second-branch
Package.json:
scripts: {
test: "sh init.sh"
}
Pass args:
npm run test -- a b c

How to check if npm script exists?

I am creating a bash script which runs through each of my projects and runs npm run test if the test script exists.
I know that if I get into a project and run npm run it will give me the list of available scripts as follows:
Lifecycle scripts included in www:
start
node server.js
test
mocha --require #babel/register --require dotenv/config --watch-extensions js **/*.test.js
available via `npm run-script`:
dev
node -r dotenv/config server.js
dev:watch
nodemon -r dotenv/config server.js
build
next build
However, I have no idea how to grab that information, see if test is available and then run it.
Here is my current code:
#!/bin/bash
ROOT_PATH="$(cd "$(dirname "$0")" && pwd)"
BASE_PATH="${ROOT_PATH}/../.."
while read MYAPP; do # reads from a list of projects
PROJECT="${MYAPP}"
FOLDER="${BASE_PATH}/${PROJECT}"
cd "$FOLDER"
if [ check here if the command exists ]; then
npm run test
echo ""
fi
done < "${ROOT_PATH}/../assets/apps-manifest"
EDIT:
As mentioned by Marie and James if you only want to run the command if it exists, npm has an option for that:
npm run test --if-present
This way you can have a generic script that work with multiple projects (that may or may not have an specific task) without having the risk of receiving an error.
Source: https://docs.npmjs.com/cli/run-script
EDIT
You could do a grep to check for the word test:
npm run | grep -q test
this return true if the result in npm run contains the word test
In your script it would look like this:
#!/bin/bash
ROOT_PATH="$(cd "$(dirname "$0")" && pwd)"
BASE_PATH="${ROOT_PATH}/../.."
while read MYAPP; do # reads from a list of projects
PROJECT="${MYAPP}"
FOLDER="${BASE_PATH}/${PROJECT}"
cd "$FOLDER"
if npm run | grep -q test; then
npm run test
echo ""
fi
done < "${ROOT_PATH}/../assets/apps-manifest"
It just would be a problem if the word test is in there with another meaning
Hope it helps
The right solution is using the if-present flag:
npm run test --if-present
--if-present doesn't allow you to "check if a npm script exists", but runs the script if it exists. If you have fallback logic this won't suffice. In my case, I want to run npm run test:ci if it exists and if not check for and run, npm run test. Using --if-present would run the test:ci AND test scripts if both exists. By checking if one exists first, we can decide which to run.
Because I have both "test" and "test:ci" scripts, the npm run | grep approach wasn't sufficient. As much as I'd like to do this with strictly npm, I have jq in my environments so I decided to go that route to have precision.
To check for a script named "test:ci":
if [[ $(jq '.scripts["test:ci"]' < package.json;) != null ]]; then
// script exists
fi

Source and npm sripts

I wrote the script in package.json
"scripts": {
"build": ". ./envsetup.sh | ./build"
}
when in envsetup.sh script I set variables and I want to share them in build script.
If I run it by npm run build I see KeyError the variable does not exist.
But if I run this script in console by 2 commands:
. ./envsetup.sh
./build
the script is successful.
You can't use a pipe here. This should work though:
"scripts": {
"build": ". ./envsetup.sh && ./build"
}

Resources