<commit_before>from __future__ import absolute_import
from glob import glob
import logging
import os
import re
import sys

import click

from localconfig import LocalConfig
from workspace.config import product_groups

from workspace.commands import AbstractCommand
from workspace.commands.helpers import expand_product_groups
from workspace.scm import is_repo, product_name, product_path
from workspace.utils import run


log = logging.getLogger(__name__)

BASHRC_FILE = "~/.bashrc"
WSTRC_FILE = "~/.wstrc"

WS_SETUP_START = '# Added by "workspace setup" (do not remove comments before / after function)'
WS_SETUP_END = "# workspace setup - end"

WS_FUNCTION_TEMPLATE = """\
alias _wst=%s

function ws() {
  if [ $# -gt 0 ]; then
    _wst "$@";
  else
    cd %s
    ls
  fi
}

function activate() {
  venv=${1:-${PWD##*/}}
  if [ -e ./activate ]; then
    source ./activate
  elif [ -e bin/activate ]; then
    source bin/activate
  elif [ -e ../build/$venv/venv/bin/activate ]; then
    source ../build/$venv/venv/bin/activate
  elif [ -e build/$venv/venv/bin/activate ]; then
    source build/$venv/venv/bin/activate
  elif [ -e $venv/activate ]; then
    source $venv/activate
  elif [ -e ~/.virtualenvs/$venv/bin/activate ]; then
    source ~/.virtualenvs/$venv/bin/activate
  elif [ -e .tox/$venv/bin/activate ]; then
    source .tox/$venv/bin/activate
  else
    echo "No activate script found. Please setup your venv."
  fi
}

function open_files_from_last_command() {
  if [ "$1" ]; then
    last_command="1 ag '$@'"
  else
    last_command=`history 100 | grep  -E "^\s+[0-9]+\s+(ag|ack|grep|find|which|ls) " | tail -1`
  fi

  if [ -z "$last_command" ]; then
    echo No ag, ack, grep, find, or which command found in last 100 commands.
    return
  fi

  declare -a "parts=($last_command)"
  command=${parts[1]}

  if [[ "$command" = "ag" || "$command" = "ack" || "$command" = "grep" ]]; then
    full_command=${parts[@]:1}
    pattern=+/${parts[2]}

    raw_parts=(${last_command// / })  # Need the quote retained to sub properly
    last_part=${raw_parts[@]:(-1)}

    if [[ $last_part != "-l" ]]; then
        sub_expr=" $last_part= $last_part -l"
    else
        sub_expr=
    fi

    if [ "$1" ]; then
      files=`ag -l "$@"`
    elif [ -z "$sub_expr" ]; then
      files=`fc -s $command`
    else
      files=`fc -s "$sub_expr" $command`
    fi

    if [ -z "$files" ]; then
      echo No files found from output
    else
      vim -p $files "$pattern" --cmd "set ignorecase smartcase"
    fi

  else
    files=`fc -s $command`

    if [ -z "$files" ]; then
      echo No files found from output
    else
      vim -p $files
    fi

  fi
}
"""
COMMAND_FUNCTION_TEMPLATE = 'function %s() { _wst %s "$@"; }\n'
COMMAND_ALIAS_TEMPLATE = 'alias %s=%s\n'
COMMANDS = {
  'a': "'activate'",
  'd': "'deactivate'",
  'tv': "'open_files_from_last_command'  # from ag/ack/grep/find/which [t]o [v]im",

  'co': 'checkout',
  'ci': 'commit',
  'di': '_diff',
  'st': 'status',
  'up': 'update',

  '_bu': 'bump',
  '_cl': 'clean',
  '_lo': 'log',
  '_mg': 'merge',
  '_pu': 'push',
  '_pb': 'publish',
  '_te': 'test',
}
AUTO_COMPLETE_TEMPLATE = """
function _branch_file_completer() {
  local cur=${COMP_WORDS[COMP_CWORD]}

  if git status &> /dev/null; then
    branches=`git branch`
  else
    branches=
  fi

  if [ ! -z "$branches" ]; then
    COMPREPLY=( $( compgen -W "$branches" -- $cur ) )
  fi
}
function _env_file_completer() {
  local cur=${COMP_WORDS[COMP_CWORD]}

  if ls tox*.ini &>/dev/null || ls .tox*.ini &>/dev/null; then
    envs=`grep -h '^\[testenv:' .tox*.ini tox*.ini 2>/dev/null | sed -E 's/^\[testenv:(.+)]/\\1/' | grep -vE '^(py|pydev)$'`
    COMPREPLY=( $( compgen -W "$envs" -- $cur ) )
  fi
}

complete -o default -F _branch_file_completer co
complete -o default -F _branch_file_completer checkout
complete -o default -F _env_file_completer test
complete -F _branch_file_completer push

complete -o default log
complete -o default di
"""
TOX_INI_FILE = 'tox.ini'
TOX_INI_TMPL = """\
[tox]
envlist = test

[testenv]
# Consolidate all deps here instead of separately in test/style/cover so we
# have a single env to work with, which makes debugging easier (like which env?).
# Not as clean but easier to work with during development, which is better.
deps =
    flake8
    mock
    pytest
    pytest-xdist
    pytest-cov
    sphinx!=1.2b2
install_command =
    pip install -U {packages}
recreate = False
skipsdist = True
usedevelop = True
setenv =
    PIP_PROCESS_DEPENDENCY_LINKS=1
    PIP_DEFAULT_TIMEOUT=60
    ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future
basepython = python3
envdir = {toxworkdir}/%s

[testenv:test]
commands =
    py.test {env:PYTESTARGS:}

[testenv:style]
commands =
    flake8 --config tox.ini

[testenv:cover]
commands =
    py.test {env:PYTESTARGS:} --cov . --cov-report=xml --cov-report=html --cov-report=term --cov-fail-under=80

[flake8]
exclude = .git,.tox,.eggs,__pycache__,docs,build,dist
ignore = E111,E121,W292,E123,E226
max-line-length = 140

[pytest]
addopts = -n 4
"""
SETUP_PY_TMPL = """\<commit_msg>Use ~/.virtualenvs as the envdir for tox<commit_after>from __future__ import absolute_import
from glob import glob
import logging
import os
import re
import sys

import click

from localconfig import LocalConfig
from workspace.config import product_groups

from workspace.commands import AbstractCommand
from workspace.commands.helpers import expand_product_groups
from workspace.scm import is_repo, product_name, product_path
from workspace.utils import run


log = logging.getLogger(__name__)

BASHRC_FILE = "~/.bashrc"
WSTRC_FILE = "~/.wstrc"

WS_SETUP_START = '# Added by "workspace setup" (do not remove comments before / after function)'
WS_SETUP_END = "# workspace setup - end"

WS_FUNCTION_TEMPLATE = """\
alias _wst=%s

function ws() {
  if [ $# -gt 0 ]; then
    _wst "$@";
  else
    cd %s
    ls
  fi
}

function activate() {
  venv=${1:-${PWD##*/}}
  if [ -e ./activate ]; then
    source ./activate
  elif [ -e bin/activate ]; then
    source bin/activate
  elif [ -e ../build/$venv/venv/bin/activate ]; then
    source ../build/$venv/venv/bin/activate
  elif [ -e build/$venv/venv/bin/activate ]; then
    source build/$venv/venv/bin/activate
  elif [ -e $venv/activate ]; then
    source $venv/activate
  elif [ -e ~/.virtualenvs/$venv/bin/activate ]; then
    source ~/.virtualenvs/$venv/bin/activate
  elif [ -e .tox/$venv/bin/activate ]; then
    source .tox/$venv/bin/activate
  else
    echo "No activate script found. Please setup your venv."
  fi
}

function open_files_from_last_command() {
  if [ "$1" ]; then
    last_command="1 ag '$@'"
  else
    last_command=`history 100 | grep  -E "^\s+[0-9]+\s+(ag|ack|grep|find|which|ls) " | tail -1`
  fi

  if [ -z "$last_command" ]; then
    echo No ag, ack, grep, find, or which command found in last 100 commands.
    return
  fi

  declare -a "parts=($last_command)"
  command=${parts[1]}

  if [[ "$command" = "ag" || "$command" = "ack" || "$command" = "grep" ]]; then
    full_command=${parts[@]:1}
    pattern=+/${parts[2]}

    raw_parts=(${last_command// / })  # Need the quote retained to sub properly
    last_part=${raw_parts[@]:(-1)}

    if [[ $last_part != "-l" ]]; then
        sub_expr=" $last_part= $last_part -l"
    else
        sub_expr=
    fi

    if [ "$1" ]; then
      files=`ag -l "$@"`
    elif [ -z "$sub_expr" ]; then
      files=`fc -s $command`
    else
      files=`fc -s "$sub_expr" $command`
    fi

    if [ -z "$files" ]; then
      echo No files found from output
    else
      vim -p $files "$pattern" --cmd "set ignorecase smartcase"
    fi

  else
    files=`fc -s $command`

    if [ -z "$files" ]; then
      echo No files found from output
    else
      vim -p $files
    fi

  fi
}
"""
COMMAND_FUNCTION_TEMPLATE = 'function %s() { _wst %s "$@"; }\n'
COMMAND_ALIAS_TEMPLATE = 'alias %s=%s\n'
COMMANDS = {
  'a': "'activate'",
  'd': "'deactivate'",
  'tv': "'open_files_from_last_command'  # from ag/ack/grep/find/which [t]o [v]im",

  'co': 'checkout',
  'ci': 'commit',
  'di': '_diff',
  'st': 'status',
  'up': 'update',

  '_bu': 'bump',
  '_cl': 'clean',
  '_lo': 'log',
  '_mg': 'merge',
  '_pu': 'push',
  '_pb': 'publish',
  '_te': 'test',
}
AUTO_COMPLETE_TEMPLATE = """
function _branch_file_completer() {
  local cur=${COMP_WORDS[COMP_CWORD]}

  if git status &> /dev/null; then
    branches=`git branch`
  else
    branches=
  fi

  if [ ! -z "$branches" ]; then
    COMPREPLY=( $( compgen -W "$branches" -- $cur ) )
  fi
}
function _env_file_completer() {
  local cur=${COMP_WORDS[COMP_CWORD]}

  if ls tox*.ini &>/dev/null || ls .tox*.ini &>/dev/null; then
    envs=`grep -h '^\[testenv:' .tox*.ini tox*.ini 2>/dev/null | sed -E 's/^\[testenv:(.+)]/\\1/' | grep -vE '^(py|pydev)$'`
    COMPREPLY=( $( compgen -W "$envs" -- $cur ) )
  fi
}

complete -o default -F _branch_file_completer co
complete -o default -F _branch_file_completer checkout
complete -o default -F _env_file_completer test
complete -F _branch_file_completer push

complete -o default log
complete -o default di
"""
TOX_INI_FILE = 'tox.ini'
TOX_INI_TMPL = """\
[tox]
envlist = test

[testenv]
# Consolidate all deps here instead of separately in test/style/cover so we
# have a single env to work with, which makes debugging easier (like which env?).
# Not as clean but easier to work with during development, which is better.
deps =
    flake8
    mock
    pytest
    pytest-xdist
    pytest-cov
    sphinx!=1.2b2
install_command =
    pip install -U {packages}
recreate = False
skipsdist = True
usedevelop = True
setenv =
    PIP_PROCESS_DEPENDENCY_LINKS=1
    PIP_DEFAULT_TIMEOUT=60
    ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future
basepython = python3
envdir = {homedir}/.virtualenvs/%s

[testenv:test]
commands =
    py.test {env:PYTESTARGS:}

[testenv:style]
commands =
    flake8 --config tox.ini

[testenv:cover]
commands =
    py.test {env:PYTESTARGS:} --cov . --cov-report=xml --cov-report=html --cov-report=term --cov-fail-under=80

[flake8]
exclude = .git,.tox,.eggs,__pycache__,docs,build,dist
ignore = E111,E121,W292,E123,E226
max-line-length = 140

[pytest]
addopts = -n 4
"""
SETUP_PY_TMPL = """\
{'fraction_non_alphanumeric': 0.15609422343856905, 'fraction_numerical': 0.00996969993158049, 'mean_word_length': 3.2298470442331544, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, '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': '896814', 'n_tokens_mistral': 3868, 'n_tokens_neox': 3730, 'n_words': 996}