Skip to content

Commit

Permalink
feat: detect available best shell
Browse files Browse the repository at this point in the history
  • Loading branch information
jclab-joseph committed Jun 1, 2021
1 parent 9b1fca0 commit ea4cd78
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ const {
GLOBAL_DEFAULT_KEY,
DEFAULT_STAGES,
} = require("./src/constants");
const {
getShellCommandLine,
} = require("./src/shell");

// ----- globals -----

Expand Down Expand Up @@ -64,7 +67,7 @@ async function execCommands({

try {
exec = await container.exec({
Cmd: ["sh", "-c", command],
Cmd: getShellCommandLine(command),
AttachStdout: true,
AttachStderr: true,
WorkingDir: workdir,
Expand Down Expand Up @@ -450,6 +453,7 @@ async function main() {
Image: preparedImageName,
Entrypoint: entrypoint,
Tty: true,
Cmd: getShellCommandLine(),
Env: Object.keys(variables).map((key) => `${key}=${variables[key]}`),
HostConfig: {
AutoRemove: true,
Expand Down
49 changes: 49 additions & 0 deletions src/shell.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// References:
// * https://gitlab.com/gitlab-org/gitlab-runner/-/blob/master/shells/bash.go
// * https://gitlab.com/gitlab-org/gitlab-runner/-/blob/master/executors/shell/shell.go

/**
* get bash detect shell script
*
* @param isLoginShell {boolean} login shell
* @return {string} generated code
*/
function getBashDetectShellScript(isLoginShell) {
const bashDefaultArguments = isLoginShell ? '--login' : '';
return `if [ -x /usr/local/bin/bash ]; then
exec /usr/local/bin/bash ${bashDefaultArguments} "$@"
elif [ -x /usr/bin/bash ]; then
exec /usr/bin/bash ${bashDefaultArguments} "$@"
elif [ -x /bin/bash ]; then
exec /bin/bash ${bashDefaultArguments} "$@"
elif [ -x /usr/local/bin/sh ]; then
exec /usr/local/bin/sh "$@"
elif [ -x /usr/bin/sh ]; then
exec /usr/bin/sh "$@"
elif [ -x /bin/sh ]; then
exec /bin/sh "$@"
elif [ -x /busybox/sh ]; then
exec /busybox/sh "$@"
else
echo shell not found
exit 1
fi
`;
}

function getShellCommandLine(userCommand) {
const command = [
'sh', '-c', getBashDetectShellScript(true)
];
if (userCommand) {
command.push('--');
command.push('-c');
command.push(userCommand);
}
return command;
}


module.exports = {
getShellCommandLine
};

0 comments on commit ea4cd78

Please sign in to comment.