internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: xonsh/xonsh

Issue:
Potential OSError: [Errno 22] Invalid argument
In current `proc.py:CommandPipeline` implementation, we built and run procs first, then give controlling terminal to them. There are cases that all the processes have finished, then the "give terminal to them" will raise errors.

```
$ ls
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xonsh/base_shell.py", line 322, in default
    run_compiled_code(code, self.ctx, None, 'single')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xonsh/codecache.py", line 65, in run_compiled_code
    func(code, glb, loc)
  File "<xonsh-code>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xonsh/built_ins.py", line 858, in subproc_captured_hiddenobject
    return run_subproc(cmds, captured='hiddenobject')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xonsh/built_ins.py", line 799, in run_subproc
    command = HiddenCommandPipeline(specs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xonsh/proc.py", line 1756, in __init__
    if update_fg_process_group(pipeline_group, background):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xonsh/proc.py", line 1691, in update_fg_process_group
    return give_terminal_to(pipeline_group)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/xonsh/jobs.py", line 138, in give_terminal_to
    os.tcsetpgrp(FD_STDERR, pgid)
OSError: [Errno 22] Invalid argument
```


Discussion:
I think this just needs a try-except. Thanks for reporting @mitnk 
@scopatz yes, PR is coming.

Resolving patch:
diff --git a/xonsh/jobs.py b/xonsh/jobs.py
--- a/xonsh/jobs.py
+++ b/xonsh/jobs.py
@@ -135,9 +135,19 @@ def give_terminal_to(pgid):
         def give_terminal_to(pgid):
             oldmask = signal.pthread_sigmask(signal.SIG_BLOCK,
                                              _block_when_giving)
-            os.tcsetpgrp(FD_STDERR, pgid)
-            signal.pthread_sigmask(signal.SIG_SETMASK, oldmask)
-            return True
+            try:
+                os.tcsetpgrp(FD_STDERR, pgid)
+                return True
+            except OSError as e:
+                if e.errno == 22:  # [Errno 22] Invalid argument
+                    # there are cases that all the processes of pgid have
+                    # finished, then we don't need to do anything here, see
+                    # issue #2220
+                    return False
+                else:
+                    raise
+            finally:
+                signal.pthread_sigmask(signal.SIG_SETMASK, oldmask)
 
     def wait_for_active_job(last_task=None, backgrounded=False):
         """


Test patch:
Repository: xonsh/xonsh

Issue:
"history play" does not work when not installed "pygments"
I found it if the library does not installed, `history replay` does not work by diving in source code.
![screenshot 2017-02-26 16 29 06](https://cloud.githubusercontent.com/assets/5797788/23337943/df086af6-fc40-11e6-99b0-a4e769e95278.png)

Since there is no explanation about `pygments` or `style` in the document(http://xon.sh/tutorial_hist.html), I want you to add the sentences about that.


Discussion:
Thanks for reporting @harukaeru!

I can reproduce this error, here's a full traceback:

```console
history replay -o ~/new.json /home/gil/.local/share/xonsh
............... /xonsh-8e015a67-ae61-48c8-b551-f59e7180df5f.json
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
  File "/home/gil/miniconda3/lib/python3.5/site-packages/xonsh/proc.py", line 1333, in run
    r = self.f(self.args, sp_stdin, sp_stdout, sp_stderr, spec)
  File "/home/gil/miniconda3/lib/python3.5/site-packages/xonsh/proc.py", line 1175, in proxy_four
    return f(args, stdin, stdout, stderr)
  File "/home/gil/miniconda3/lib/python3.5/site-packages/xonsh/history/main.py", line 338, in history_main
    xrp.replay_main_action(hist, ns, stdout=stdout, stderr=stderr)
  File "/home/gil/miniconda3/lib/python3.5/site-packages/xonsh/replay.py", line 111, in replay_main_action
    hist = replayer.replay(merge_envs=ns.merge_envs, target=ns.target)
  File "/home/gil/miniconda3/lib/python3.5/site-packages/xonsh/replay.py", line 52, in replay
    new_env = self._merge_envs(merge_envs, re_env)
  File "/home/gil/miniconda3/lib/python3.5/site-packages/xonsh/replay.py", line 76, in _merge_envs
    new_env = Env(**new_env)
  File "/home/gil/miniconda3/lib/python3.5/site-packages/xonsh/environ.py", line 789, in __init__
    self[key] = val
  File "/home/gil/miniconda3/lib/python3.5/site-packages/xonsh/environ.py", line 945, in __setitem__
    val = ensurer.convert(val)
  File "/home/gil/miniconda3/lib/python3.5/site-packages/xonsh/tools.py", line 1562, in intensify_colors_on_win_setter
    delattr(builtins.__xonsh_shell__.shell.styler, 'style_name')
AttributeError: 'NoneType' object has no attribute 'style_name'
```

It's curious that I'm hitting a windows-specific ensurer.

Resolving patch:
diff --git a/xonsh/tools.py b/xonsh/tools.py
--- a/xonsh/tools.py
+++ b/xonsh/tools.py
@@ -1576,7 +1576,8 @@ def intensify_colors_on_win_setter(enable):
     """
     enable = to_bool(enable)
     if hasattr(builtins, '__xonsh_shell__'):
-        delattr(builtins.__xonsh_shell__.shell.styler, 'style_name')
+        if hasattr(builtins.__xonsh_shell__.shell.styler, 'style_name'):
+            delattr(builtins.__xonsh_shell__.shell.styler, 'style_name')
     return enable
 
 


Test patch:
Repository: xonsh/xonsh

Issue:
could not launch xonsh on suse leap..
hi.
i use xonsh as my default shell. after updating could not launch it and this error comes up:

```
Traceback (most recent call last):
  File "/usr/lib/python3.4/site-packages/xonsh/__amalgam__.py", line 18345, in main
    args = premain(argv)
  File "/usr/lib/python3.4/site-packages/xonsh/__amalgam__.py", line 18297, in premain
    builtins.__xonsh_shell__ = Shell(**shell_kwargs)
  File "/usr/lib/python3.4/site-packages/xonsh/__amalgam__.py", line 17479, in __init__
    kwargs.get('cacheall', False))
  File "/usr/lib/python3.4/site-packages/xonsh/__amalgam__.py", line 17533, in _init_environ
    debug_level=debug)
  File "/usr/lib/python3.4/site-packages/xonsh/__amalgam__.py", line 17080, in __init__
    load_builtins(execer=self, config=config, login=login, ctx=xonsh_ctx)
  File "/usr/lib/python3.4/site-packages/xonsh/__amalgam__.py", line 16916, in load_builtins
    builtins.__xonsh_env__ = Env(default_env(config=config, login=login))
  File "/usr/lib/python3.4/site-packages/xonsh/__amalgam__.py", line 14970, in default_env
    issue_warning=False)
  File "/usr/lib/python3.4/site-packages/xonsh/__amalgam__.py", line 9139, in load_foreign_envs
    shenv, _ = foreign_shell_data(**shell)
  File "/usr/lib64/python3.4/functools.py", line 452, in wrapper
    result = user_function(*args, **kwds)
  File "/usr/lib/python3.4/site-packages/xonsh/__amalgam__.py", line 8834, in foreign_shell_data
    shkey = CANON_SHELL_NAMES[shell]
  File "/usr/lib/python3.4/site-packages/xonsh/__amalgam__.py", line 331, in __getitem__
    return obj[item]
KeyError: 'Bash'
Xonsh encountered an issue during launch
Failback to /bin/bash
```

i already fixed it. i had to go to /usr/lib/python3.4/site-packages/xonsh/__amalgam__.py
and change line 8675.. change key 'bash' to 'Bash'

this had happenned in a previous update. and now after updating to version 0.5.3-5.5 happened again.



Discussion:
Can you list the content of your static [configuration file](http://xon.sh/xonshconfig.html)?
`~/.config/xonsh/config.json`

I suspect that you wrote the shell name with a capital B in that file. 

@scopatz. Maybe we should consider converting the shell name to lowercase here: 
https://github.com/xonsh/xonsh/blob/master/xonsh/foreign_shells.py#L493


Yeah I think we should @melund. In fact, I thought we were already doing that!

Resolving patch:
diff --git a/xonsh/foreign_shells.py b/xonsh/foreign_shells.py
--- a/xonsh/foreign_shells.py
+++ b/xonsh/foreign_shells.py
@@ -490,7 +490,7 @@ def ensure_shell(shell):
     if not (shell_keys <= VALID_SHELL_PARAMS):
         msg = 'unknown shell keys: {0}'
         raise KeyError(msg.format(shell_keys - VALID_SHELL_PARAMS))
-    shell['shell'] = ensure_string(shell['shell'])
+    shell['shell'] = ensure_string(shell['shell']).lower()
     if 'interactive' in shell_keys:
         shell['interactive'] = to_bool(shell['interactive'])
     if 'login' in shell_keys:


Test patch:
Repository: xonsh/xonsh

Issue:
Python 3.4 no longer supported?
Hi all,

First of all, thank you all for your great work. 

I have noticed that the version bump to 0.5.7 introduced a call to `os.scandir` which is not supported by Python <3.5 afaik. As I am still using Ubuntu 14.04 with Python 3.4 on a few machines, this is a little bit of a headache... I don't know the codebase, but it looks like `xonsh.platform.scandir` could be used instead?


Discussion:

Resolving patch:
diff --git a/xonsh/prompt/vc.py b/xonsh/prompt/vc.py
--- a/xonsh/prompt/vc.py
+++ b/xonsh/prompt/vc.py
@@ -58,7 +58,7 @@ def _get_hg_root(q):
     while True:
         if not os.path.isdir(_curpwd):
             return False
-        if any([b.name == '.hg' for b in os.scandir(_curpwd)]):
+        if any([b.name == '.hg' for b in xt.scandir(_curpwd)]):
             q.put(_curpwd)
             break
         else:


Test patch:
diff --git a/tests/test_prompt.py b/tests/test_prompt.py
--- a/tests/test_prompt.py
+++ b/tests/test_prompt.py
@@ -150,6 +150,17 @@ def test_test_repo(test_repo):
         assert os.path.isfile(os.path.join(test_repo['dir'], 'test-file'))
 
 
+def test_no_repo(xonsh_builtins):
+    import queue
+    temp_dir = tempfile.mkdtemp()
+    xonsh_builtins.__xonsh_env__ = Env(VC_BRANCH_TIMEOUT=2, PWD=temp_dir)
+    q = queue.Queue()
+    try:
+        vc._get_hg_root(q)
+    except AttributeError:
+        assert False
+
+
 def test_vc_get_branch(test_repo, xonsh_builtins):
     xonsh_builtins.__xonsh_env__ = Env(VC_BRANCH_TIMEOUT=2)
     # get corresponding function from vc module
Repository: xonsh/xonsh

Issue:
which broken on Windows
`which` seem to be broken on windows.
```
snail@sea ~\Documents\xonsh master
$ which man
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\__amalgam__.py", line 13009, in run
    r = self.f(self.args, sp_stdin, sp_stdout, sp_stderr, spec)
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\xoreutils\which.py", line 127, in which
    original_os_path = xp.os_environ['PATH']
KeyError: 'PATH'
```


Discussion:

Resolving patch:
diff --git a/xonsh/platform.py b/xonsh/platform.py
--- a/xonsh/platform.py
+++ b/xonsh/platform.py
@@ -11,6 +11,7 @@
 import platform
 import functools
 import subprocess
+import collections
 import importlib.util
 
 from xonsh.lazyasd import LazyBool, lazyobject, lazybool
@@ -358,6 +359,58 @@ def windows_bash_command():
 # Environment variables defaults
 #
 
+if ON_WINDOWS:
+    class OSEnvironCasePreserving(collections.MutableMapping):
+        """ Case-preseving wrapper for os.environ on Windows.
+            It uses nt.environ to get the correct cased keys on
+            initialization. It also preserves the case of any variables
+            add after initialization.
+        """
+        def __init__(self):
+            import nt
+            self._upperkeys = dict((k.upper(), k) for k in nt.environ)
+
+        def _sync(self):
+            """ Ensure that the case sensitive map of the keys are
+                in sync with os.environ
+            """
+            envkeys = set(os.environ.keys())
+            for key in envkeys.difference(self._upperkeys):
+                self._upperkeys[key] = key.upper()
+            for key in set(self._upperkeys).difference(envkeys):
+                del self._upperkeys[key]
+
+        def __contains__(self, k):
+            self._sync()
+            return k.upper() in self._upperkeys
+
+        def __len__(self):
+            self._sync()
+            return len(self._upperkeys)
+
+        def __iter__(self):
+            self._sync()
+            return iter(self._upperkeys.values())
+
+        def __getitem__(self, k):
+            self._sync()
+            return os.environ[k]
+
+        def __setitem__(self, k, v):
+            self._sync()
+            self._upperkeys[k.upper()] = k
+            os.environ[k] = v
+
+        def __delitem__(self, k):
+            self._sync()
+            if k.upper() in self._upperkeys:
+                del self._upperkeys[k.upper()]
+                del os.environ[k]
+
+        def getkey_actual_case(self, k):
+            self._sync()
+            return self._upperkeys.get(k.upper())
+
 
 @lazyobject
 def os_environ():
@@ -367,8 +420,7 @@ def os_environ():
     dropped.
     """
     if ON_WINDOWS:
-        import nt
-        return nt.environ
+        return OSEnvironCasePreserving()
     else:
         return os.environ
 


Test patch:
Repository: xonsh/xonsh

Issue:
Add _repr_pretty_ method to EnvPath
The `$PATH` variable doesn't pretty print like other python lists.

We should add the `def _repr_pretty_` to the class. see https://github.com/xonsh/xonsh/blob/master/xonsh/pretty.py#L29


Discussion:

Resolving patch:
diff --git a/xonsh/tools.py b/xonsh/tools.py
--- a/xonsh/tools.py
+++ b/xonsh/tools.py
@@ -204,6 +204,18 @@ def __eq__(self, other):
             return False
         return all(map(operator.eq, self, other))
 
+    def _repr_pretty_(self, p, cycle):
+        """ Pretty print path list """
+        if cycle:
+            p.text('EnvPath(...)')
+        else:
+            with p.group(1, 'EnvPath(\n[', ']\n)'):
+                for idx, item in enumerate(self):
+                    if idx:
+                        p.text(',')
+                        p.breakable()
+                    p.pretty(item)
+
 
 class DefaultNotGivenType(object):
     """Singleton for representing when no default value is given."""


Test patch:
Repository: xonsh/xonsh

Issue:
xonsh $PATH does not include user env vars on Windows
xonsh $PATH does not include user environment variables on Windows. As a result, some commands that can be found correctly in `cmd.exe` cannot be found in xonsh.

For example, my global PATHs are:
```python
['C:\\Windows\\System32', 'C:\\Windows', ...]
```
And my user PATHs are:
```python
['D:\\Programs\\nodejs', '...']
```

In xonsh, `$PATH` contains only the global PATHs, while `os.environ['PATH']` contains everything.

In Windows `cmd.exe`, `npm` works, but `xonsh` says `command not found`.
After typing `$PATH = os.environ['PATH'].split(';')`, it works.
BTW, if a command refers to a `.exe` file, it will be found even if its path not in `$PATH`, but not `.bat`.

So the question is, should I set `$PATH = os.environ['PATH'].split(';')` manually or do I miss anything?


Discussion:
I can't reproduce this. Can you post the output of running `xonfig` 

I get the same path no matter where I get it from: 
```
snail@sea ~\Documents\xonsh master
$ xonsh_path = set($PATH)
snail@sea ~\Documents\xonsh master
$ cmd_path = set($(cmd /c echo ! %PATH%).strip().split(';'))
snail@sea ~\Documents\xonsh master
$ os_env_path = set(os.environ['PATH'].split(';'))
snail@sea ~\Documents\xonsh master
$ len(xonsh_path), len(cmd_path), len(os_env_path)
(41, 41, 41)
```


![image](https://cloud.githubusercontent.com/assets/3139113/23942501/740c8d1c-09a7-11e7-8e4b-2b1d35c75f78.png)

By running `xonfig` I get:

| Name | Value |
|---|---|
| xonsh            | 0.5.8           |
| Python           | 3.6.0           |
| PLY              | 3.9             |
| have readline    | False           |
| prompt toolkit   | 1.0.13          |
| shell type       | prompt_toolkit  |
| pygments         | 2.2.0           |
| on posix         | False           |
| on linux         | False           |
| on darwin        | False           |
| on windows       | True            |
| on cygwin        | False           |
| is superuser     | False           |
| default encoding | utf-8           |
| xonsh encoding   | utf-8           |
| encoding errors  | surrogateescape |

FYI, I installed xonsh through miniconda with the commands [here](http://xon.sh/windows.html).

And something more, `$PATH` seems to read the raw PATH entries while `os.environ['PATH']` contains the expanded values.
![image](https://cloud.githubusercontent.com/assets/3139113/23943127/5ba9652c-09a9-11e7-9324-1056ef0df887.png)


Resolving patch:
diff --git a/xonsh/environ.py b/xonsh/environ.py
--- a/xonsh/environ.py
+++ b/xonsh/environ.py
@@ -794,6 +794,10 @@ def __init__(self, *args, **kwargs):
             args = (os_environ,)
         for key, val in dict(*args, **kwargs).items():
             self[key] = val
+        if ON_WINDOWS:
+            path_key = next((k for k in self._d if k.upper() == 'PATH'), None)
+            if path_key:
+                self['PATH'] = self._d.pop(path_key)
         if 'PATH' not in self._d:
             # this is here so the PATH is accessible to subprocs and so that
             # it can be modified in-place in the xonshrc file


Test patch:
Repository: xonsh/xonsh

Issue:
xoreutils: echo fails with KeyError: 'help'
Any `echo` invocation fails:

```shell
$ $XONSH_SHOW_TRACEBACK = True
$ echo
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 13061, in run
    r = self.f(self.args, sp_stdin, sp_stdout, sp_stderr, spec)
  File "/usr/local/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 12896, in proxy_four
    return f(args, stdin, stdout, stderr)
  File "/usr/local/lib/python3.6/site-packages/xonsh/xoreutils/echo.py", line 9, in echo
    if opts['help']:
KeyError: 'help'
$ echo foo
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 13061, in run
    r = self.f(self.args, sp_stdin, sp_stdout, sp_stderr, spec)
  File "/usr/local/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 12896, in proxy_four
    return f(args, stdin, stdout, stderr)
  File "/usr/local/lib/python3.6/site-packages/xonsh/xoreutils/echo.py", line 9, in echo
    if opts['help']:
KeyError: 'help'
$ echo "foo"
xonsh: To log full traceback to a file set: $XONSH_TRACEBACK_LOGFILE = <filename>
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 13061, in run
    r = self.f(self.args, sp_stdin, sp_stdout, sp_stderr, spec)
  File "/usr/local/lib/python3.6/site-packages/xonsh/__amalgam__.py", line 12896, in proxy_four
    return f(args, stdin, stdout, stderr)
  File "/usr/local/lib/python3.6/site-packages/xonsh/xoreutils/echo.py", line 9, in echo
    if opts['help']:
KeyError: 'help'
```

Obviously, the problem is that `help` is looked up but missing: http://xon.sh/_modules/xonsh/xoreutils/echo.html#echo


Discussion:
This is a serious issue since echo is one of the essential commands.
The work around is `del aliases['echo']` which will cause xonsh  to revert to your system's echo instead of its own built-in implementation.
@astronouth7303 Thanks for the tip!

Should I PR the following simple fix, or is the issue more complex than it seems:

```diff
- if opts['help']:
+ if opts.get('help'):
```
Hey @moigagoo -- that seems like a good fix to me.
Either that or set a default 'help' in `_echo_parse_args()`.

Resolving patch:
diff --git a/xonsh/xoreutils/echo.py b/xonsh/xoreutils/echo.py
--- a/xonsh/xoreutils/echo.py
+++ b/xonsh/xoreutils/echo.py
@@ -17,7 +17,7 @@ def echo(args, stdin, stdout, stderr):
 
 
 def _echo_parse_args(args):
-    out = {'escapes': False, 'end': '\n'}
+    out = {'escapes': False, 'end': '\n', 'help': False}
     if '-e' in args:
         args.remove('-e')
         out['escapes'] = True


Test patch:
Repository: xonsh/xonsh

Issue:
@$ result is not satisfying
When I run `@$(which ls)` I expect to see this result:
`some_file  some_other_file`

But I see this:
`ls: invalid option -- '
'
Try 'ls --help' for more information.
`

xonsh version: 0.5.9
os : linux (Ubuntu 16.04.2)



Discussion:
 thx for reporting @shipup !  this is defo a bug and maybe related to #2329
@laerus Are you sure you mean #2329 ?
I think this may be separate from #2329 and more a function of using `@$` with aliased commands?

`@$(which ls)` works as expected for me if I first do a `aliases.pop('ls')`

Resolving patch:
diff --git a/xonsh/built_ins.py b/xonsh/built_ins.py
--- a/xonsh/built_ins.py
+++ b/xonsh/built_ins.py
@@ -858,7 +858,7 @@ def subproc_captured_inject(*cmds):
     or shlex.split().
     """
     s = run_subproc(cmds, captured='stdout')
-    toks = builtins.__xonsh_execer__.parser.lexer.split(s)
+    toks = builtins.__xonsh_execer__.parser.lexer.split(s.strip())
     return toks
 
 


Test patch:
diff --git a/tests/test_integrations.py b/tests/test_integrations.py
--- a/tests/test_integrations.py
+++ b/tests/test_integrations.py
@@ -217,6 +217,14 @@ def _echo(args):
 echo --option1 \
 --option2
 """, '--option1 --option2\n', 0),
+#
+# test @$() with aliases
+#
+("""
+aliases['ls'] = 'spam spam sausage spam'
+
+echo @$(which ls)
+""", 'spam spam sausage spam\n', 0),
 ]