<commit_before>"""be - Minimal Asset Management System

Usage:
    $ be project/item/type

Errors:
    PROJECT ERROR: Project has been misconfigured
    TEMPLATE ERROR: A template has been misconfigured

"""

import os
import sys
import time
import getpass
import tempfile
import subprocess

import _format
import _extern
import lib

from vendor import click

self = type("Scope", (object,), {})()
self.isactive = lambda: "BE_ACTIVE" in os.environ


@click.group()
def main():
    """be - Minimal Directory and Environment Management System

    be initialises a context-sensitive environment for
    your project. Use "new" to start a new project, followed
    by "in" to enter it. A directory structure will have been
    setup for you in accordance with a project-specific file
    "templates.yaml" for any particular item you request,
    e.g. "peter".

    See help for each subcommand for more information and
    http://github.com/abstractfactory/be/wiki for documentation.

    \b
    Usage:
        $ be new ad --name spiderman
        "spiderman" created.
        $ be ls
        - spiderman
        $ be in spiderman/shot1/animation
        $ be dump
        BE_PROJECT=spiderman
        BE_ITEM=peter
        BE_TASK=model

    \b
    Environment:
        BE_PROJECT (str): Name of current project
        BE_ITEM (str): Name of current item
        BE_TYPE (str): Family of current item
        BE_DEVELOPMENTDIR (str): Absolute path to current development directory
        BE_PROJECTROOT (str): Absolute path to current project
        BE_PROJECTSROOT (str): Absolute path to where projects are located
        BE_ACTIVE (bool): In an active environment

    """


@click.command()
@click.argument("context")
@click.option("-y", "--yes", is_flag=True,
              help="Automatically accept any questions")
@click.option("-a", "--as", "as_", default=getpass.getuser(),
              help="Enter project as a different user")
@click.option("-e", "--enter", is_flag=True,
              help="Change the current working "
                   "directory to development directory")
@click.pass_context
def in_(ctx, context, yes, as_, enter):
    """Set the current context to `context`

    \b
    Usage:
        $ be in project/item/type

    """

    if self.isactive():
        lib.echo("Error: Exit current project first")
        sys.exit(1)

    try:
        project, item, type = str(context).split("/")
    except:
        sys.stderr.write("Invalid syntax, the format is project/item/type")
        sys.exit(1)

    project_dir = _format.project_dir(_extern.cwd(), project)
    if not os.path.exists(project_dir):
        lib.echo("Project \"%s\" not found. " % project)
        lib.echo("\nAvailable:")
        ctx.invoke(ls)
        sys.exit(1)

    templates = _extern.load_templates(project)
    inventory = _extern.load_inventory(project)
    settings = _extern.load_settings(project)

    development_dir = _format.development_directory(
        templates, inventory, project, item, type, as_)
    if not os.path.exists(development_dir):
        create = False
        if yes:
            create = True
        else:
            sys.stdout.write("No development directory found. Create? [Y/n]: ")
            if raw_input().lower() in ("", "y", "yes"):
                create = True
        if create:
            os.makedirs(development_dir)
        else:
            sys.stdout.write("Cancelled")
            sys.exit(0)

    dirname = os.path.dirname(__file__)
    if os.name == "nt":
        shell = os.path.join(dirname, "_shell.bat")
    else:
        shell = os.path.join(dirname, "_shell.sh")

    tempdir = (tempfile.mkdtemp()
               if "BE_TEMPDIR" not in os.environ
               else os.environ["BE_TEMPDIR"])

    env = dict(os.environ, **{
        "BE_PROJECT": project,
        "BE_ITEM": item,
        "BE_TYPE": type,
        "BE_DEVELOPMENTDIR": development_dir,
        "BE_PROJECTROOT": os.path.join(
            _extern.cwd(), project).replace("\\", "/"),
        "BE_PROJECTSROOT": _extern.cwd(),
        "BE_ACTIVE": "True",
        "BE_USER": str(as_),
        "BE_SCRIPT": "",
        "BE_PYTHON": "",
        "BE_ENTER": "True" if enter else "",
        "BE_TEMPDIR": tempdir
    })

    # Parse be.yaml
    if "script" in settings:
        env["BE_SCRIPT"] = _extern.write_script(settings["script"], tempdir)

    if "python" in settings:
        script = ";".join(settings["python"])
        env["BE_PYTHON"] = script
        try:
            exec(script, {"__name__": __name__})
        except Exception as e:
            lib.echo("Error: %s" % e)

    # Create aliases
    aliases = settings.get("alias", {})
    aliases["home"] = "cd %s" % development_dir
    aliases_dir = _extern.write_aliases(aliases, tempdir)
    env["PATH"] = aliases_dir + os.pathsep + env.get("PATH", "")
    env["BE_ALIASDIR"] = aliases_dir

    for map_source, map_dest in settings.get("redirect", {}).items():
        env[map_dest] = env[map_source]

    if "BE_TESTING" in os.environ:
        os.chdir(development_dir)
        os.environ.update(env)
        return

    try:
        sys.exit(subprocess.call(shell, shell=True, env=env))
    finally:
        import shutil
        shutil.rmtree(tempdir)


@click.command()
@click.argument("preset")
@click.option("--name", help="Name of your new project")
@click.option("--silent", is_flag=True,
              help="Print only errors")
@click.option("--update", "-U", is_flag=True,
              help="Update preset to latest version before creating")
def new(preset, name, silent, update):<commit_msg>Adjusting home alias<commit_after>"""be - Minimal Asset Management System

Usage:
    $ be project/item/type

Errors:
    PROJECT ERROR: Project has been misconfigured
    TEMPLATE ERROR: A template has been misconfigured

"""

import os
import sys
import time
import getpass
import tempfile
import subprocess

import _format
import _extern
import lib

from version import version
from vendor import click

self = type("Scope", (object,), {})()
self.isactive = lambda: "BE_ACTIVE" in os.environ


@click.group()
def main():
    """be {0} - Minimal Directory and Environment Management System

    be initialises a context-sensitive environment for
    your project. Use "new" to start a new project, followed
    by "in" to enter it. A directory structure will have been
    setup for you in accordance with a project-specific file
    "templates.yaml" for any particular item you request,
    e.g. "peter".

    See help for each subcommand for more information and
    http://github.com/mottosso/be/wiki for documentation.

    \b
    Usage:
        $ be new ad --name spiderman
        "spiderman" created.
        $ be ls
        - spiderman
        $ be in spiderman/shot1/animation
        $ be dump
        BE_PROJECT=spiderman
        BE_ITEM=peter
        BE_TASK=model

    \b
    Environment:
        BE_PROJECT (str): Name of current project
        BE_ITEM (str): Name of current item
        BE_TYPE (str): Family of current item
        BE_DEVELOPMENTDIR (str): Absolute path to current development directory
        BE_PROJECTROOT (str): Absolute path to current project
        BE_PROJECTSROOT (str): Absolute path to where projects are located
        BE_ACTIVE (bool): In an active environment

    """

main.help = main.help.format(version)


@click.command()
@click.argument("context")
@click.option("-y", "--yes", is_flag=True,
              help="Automatically accept any questions")
@click.option("-a", "--as", "as_", default=getpass.getuser(),
              help="Enter project as a different user")
@click.option("-e", "--enter", is_flag=True,
              help="Change the current working "
                   "directory to development directory")
@click.pass_context
def in_(ctx, context, yes, as_, enter):
    """Set the current context to `context`

    \b
    Usage:
        $ be in project/item/type

    """

    if self.isactive():
        lib.echo("Error: Exit current project first")
        sys.exit(1)

    try:
        project, item, type = str(context).split("/")
    except:
        sys.stderr.write("Invalid syntax, the format is project/item/type")
        sys.exit(1)

    project_dir = _format.project_dir(_extern.cwd(), project)
    if not os.path.exists(project_dir):
        lib.echo("Project \"%s\" not found. " % project)
        lib.echo("\nAvailable:")
        ctx.invoke(ls)
        sys.exit(1)

    templates = _extern.load_templates(project)
    inventory = _extern.load_inventory(project)
    settings = _extern.load_settings(project)

    development_dir = _format.development_directory(
        templates, inventory, project, item, type, as_)
    if not os.path.exists(development_dir):
        create = False
        if yes:
            create = True
        else:
            sys.stdout.write("No development directory found. Create? [Y/n]: ")
            if raw_input().lower() in ("", "y", "yes"):
                create = True
        if create:
            os.makedirs(development_dir)
        else:
            sys.stdout.write("Cancelled")
            sys.exit(0)

    dirname = os.path.dirname(__file__)
    if os.name == "nt":
        shell = os.path.join(dirname, "_shell.bat")
    else:
        shell = os.path.join(dirname, "_shell.sh")

    tempdir = (tempfile.mkdtemp()
               if "BE_TEMPDIR" not in os.environ
               else os.environ["BE_TEMPDIR"])

    env = dict(os.environ, **{
        "BE_PROJECT": project,
        "BE_ITEM": item,
        "BE_TYPE": type,
        "BE_DEVELOPMENTDIR": development_dir,
        "BE_PROJECTROOT": os.path.join(
            _extern.cwd(), project).replace("\\", "/"),
        "BE_PROJECTSROOT": _extern.cwd(),
        "BE_ACTIVE": "True",
        "BE_USER": str(as_),
        "BE_SCRIPT": "",
        "BE_PYTHON": "",
        "BE_ENTER": "True" if enter else "False",
        "BE_TEMPDIR": tempdir
    })

    # Parse be.yaml
    if "script" in settings:
        env["BE_SCRIPT"] = _extern.write_script(settings["script"], tempdir)

    if "python" in settings:
        script = ";".join(settings["python"])
        env["BE_PYTHON"] = script
        try:
            exec(script, {"__name__": __name__})
        except Exception as e:
            lib.echo("Error: %s" % e)

    # Create aliases
    cd_alias = ("cd %BE_DEVELOPMENTDIR%"
                if os.name == "nt" else "cd $BE_DEVELOPMENTDIR")

    aliases = settings.get("alias", {})
    aliases["home"] = cd_alias
    aliases_dir = _extern.write_aliases(aliases, tempdir)

    env["PATH"] = aliases_dir + os.pathsep + env.get("PATH", "")
    env["BE_ALIASDIR"] = aliases_dir

    for map_source, map_dest in settings.get("redirect", {}).items():
        env[map_dest] = env[map_source]

    if "BE_TESTING" in os.environ:
        os.chdir(development_dir)
        os.environ.update(env)
        return

    try:
        sys.exit(subprocess.call(shell, shell=True, env=env))
    finally:
        import shutil
        shutil.rmtree(tempdir)


@click.command()
@click.argument("preset")
@click.option("--name", help="Name of your new project")
@click.option("--silent", is_flag=True,
              help="Print only errors")
@click.option("--update", "-U", is_flag=True,
              help="Update preset to latest version before creating")
def new(preset, name, silent, update):
{'fraction_non_alphanumeric': 0.12461470717745486, 'fraction_numerical': 0.000968736239542052, 'mean_word_length': 2.5092707045735474, 'pattern_counts': {'":': 28, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '159751', 'n_tokens_mistral': 3505, 'n_tokens_neox': 3430, 'n_words': 938}