Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

&& and || operations #19

Open
nfischer opened this issue May 17, 2016 · 1 comment
Open

&& and || operations #19

nfischer opened this issue May 17, 2016 · 1 comment

Comments

@nfischer
Copy link
Owner

Add in translation for && and || as follows:

$ true && echo 'hi'
hi
$ false || echo 'hi'
hi

In general, it may be tough to get this working as nicely as possible. commands like test -f file.txt return booleans, and it would be nice to take advantage of that in translation, while other commands like exec('git status') have .code attributes that should be examined instead.

Also, this should work with other formats, such as [ "my string" ] && echo hi.

It'd be really great if better support for && and || could be worked into n_shell or ShellJS proper.

@nfischer
Copy link
Owner Author

nfischer commented Feb 7, 2018

Update:

Most shelljs methods have .code attributes (.code === 0 means success). shell.test() is the notable exception.

Some design ideas

We could translate this into an 'if' expression:

// cp file.txt dest/ && echo 'file copied successfully!'
var result = shell.cp('file.txt', 'dest/');
if (result.code === 0) shell.echo('file copied successfully!');
// But what if we need the combined stdout/stderr/code from the 'and' expression?

We could consider adding pre-defined and() and or() functions into the translation. If we add those into the translator, it would look like:

// cp file.txt dest/ && echo 'file copied successfully!'
and([ shell.cp, 'file.txt', 'dest/' ], [ shell.echo, 'file copied successfully!' ]);

function and(cmd1, cmd2) {
  var ret = cmd1.invoke(shell, cmd1.slice(1));
  if (ret.code === 0) {
    var ret2 = cmd2.invoke(shell, cmd2.slice(1));
    // merge .stdout, .stderr, .code from ret & ret2
    return combinedShellString;
  }
  return ret; // otherwise, never execute cmd2
}

This should work, but the array syntax is pretty ugly.


We could also consider implementing this upstream in shelljs:

shell.cp('file.txt', 'dest/').and().echo('file copied successfully!');

function and() {
  // |this| is a ShellString object
  if (this.code === 0) {
    // Return some object which has modified shelljs methods. They execute the same,
    // but they concatenate
  } else {
    // Return some object which has different modified shelljs methods. They're all NOOPs,
    // and they return |this| (the |this| from this invocation)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant