#!/usr/bin/env python
# (c) 2012-2013 Anaconda, Inc. / http://continuum.io
# All Rights Reserved
#
# conda is distributed under the terms of the BSD 3-clause license.
# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.

from subprocess import check_output, PIPE, Popen, STDOUT
from os.path import join, dirname, abspath, isdir
from os import makedirs, pathsep
from collections import OrderedDict

from concurrent.futures import ThreadPoolExecutor

try:
    from shlex import quote
except ImportError:
    from pipes import quote

import sys
import json
import re

manpath = join(dirname(__file__), 'build', 'man')
if not isdir(manpath):
    makedirs(manpath)
rstpath = join(dirname(__file__), 'source', 'commands')
if not isdir(rstpath):
    makedirs(rstpath)

RST_HEADER = """
.. _{command}_ref:

conda {command}
=======================

.. raw:: html

"""

def run_command(*args, **kwargs):
    include_stderr = kwargs.pop('include_stderr', False)
    if include_stderr:
        stderr_pipe = STDOUT
    else:
        stderr_pipe = PIPE
    p = Popen(*args, stdout=PIPE, stderr=stderr_pipe, **kwargs)
    out, err = p.communicate()
    if err is None:
        err = b''
    out, err = out.decode('utf-8'), err.decode('utf-8')
    if p.returncode != 0:
        print("%r failed with error code %s" % (' '.join(map(quote, args[0])), p.returncode), file=sys.stderr)
    elif err:
        print("%r gave stderr output: %s" % (' '.join(*args), err))

    return out

def str_check_output(*args, **kwargs):
    return check_output(*args, **kwargs).decode('utf-8')

def conda_help(cache=[]):
    if cache:
        return cache[0]
    cache.append(str_check_output(['conda', '--help']))
    return cache[0]

def conda_command_help(command):
    return str_check_output(['conda'] + command.split() + ['--help'])

def conda_commands():
    print("Getting list of core commands")