'''
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_call(
            ('yarn', 'install') + extra_args,
            **popen_kwargs)
    else:
        subprocess.check_call(
            ('npm', 'install') + extra_args,
            **popen_kwargs)


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