'''
Run npm commands. Uses yarn if present.
'''
import shutil
import subprocess

from elm_doc.decorators import capture_subprocess_error


def has_yarn():
    return shutil.which('yarn') is not None


@capture_subprocess_error
def install(*extra_args, **popen_kwargs):
    if has_yarn():
        subprocess.check_output(
            ('yarn', 'install') + extra_args,
            stderr=subprocess.STDOUT,
            **popen_kwargs)
    else:
        subprocess.check_output(
            ('npm', 'install') + extra_args,
            stderr=subprocess.STDOUT,
            **popen_kwargs)


@capture_subprocess_error
def add(*extra_args, **popen_kwargs):
    if has_yarn():
        subprocess.check_output(
            ('yarn', 'add') + extra_args,
            stderr=subprocess.STDOUT,
            **popen_kwargs)
    else:
        subprocess.check_output(
            ('npm', 'install') + extra_args,
            stderr=subprocess.STDOUT,
            **popen_kwargs)
