Repository: xonsh/xonsh

Issue:
Deleting $PWD crashes xonsh
`$PWD` can be deleted completely since it doesn't have default entries in the environment. 

That will crashes xonsh: 
```
snail@sea ~\Documents\xonsh 
$ del $PWD
prompt: error: on field 'cwd'
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\prompt\base.py", line 82, in _get_field_value
    value = field_value() if callable(field_value) else field_value
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\prompt\cwd.py", line 48, in _dynamically_collapsed_pwd
    originial_path = _replace_home_cwd()
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\prompt\cwd.py", line 31, in _replace_home_cwd
    return _replace_home(builtins.__xonsh_env__['PWD'])
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\environ.py", line 936, in __getitem__
    raise KeyError(e.format(key))
KeyError: 'Unknown environment variable: $PWD'
prompt: error: on field 'cwd'
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\prompt\base.py", line 82, in _get_field_value
    value = field_value() if callable(field_value) else field_value
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\prompt\cwd.py", line 48, in _dynamically_collapsed_pwd
    originial_path = _replace_home_cwd()
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\prompt\cwd.py", line 31, in _replace_home_cwd
    return _replace_home(builtins.__xonsh_env__['PWD'])
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\environ.py", line 936, in __getitem__
    raise KeyError(e.format(key))
KeyError: 'Unknown environment variable: $PWD'
```
I can be a separate issue. 


Discussion:
Hmm I am not able to reproduce this on linux.

```console
scopatz@andromache ~ $ del $PWD
scopatz@andromache ~ $ $PWD
'/home/scopatz'
scopatz@andromache ~ $ xonfig
+------------------+----------------------+
| xonsh            | 0.5.6.dev13          |
| Git SHA          | f0eecaa              |
| Commit Date      | Feb 23 10:44:34 2017 |
| Python           | 3.5.3                |
| PLY              | 3.9                  |
| have readline    | True                 |
| prompt toolkit   | 1.0.13               |
| shell type       | prompt_toolkit       |
| pygments         | 2.2.0                |
| on posix         | True                 |
| on linux         | True                 |
| distro           | debian               |
| on darwin        | False                |
| on windows       | False                |
| on cygwin        | False                |
| is superuser     | False                |
| default encoding | utf-8                |
| xonsh encoding   | utf-8                |
| encoding errors  | surrogateescape      |
+------------------+----------------------+
```


Arhh.. `python setup.py develop` sometimes plays tricks on me. 

I thought it was still running code from the `resolve_symlinks` branch. So this wasn't a separate issue after all. 

Sorry for the noise here. 
No worries! Thanks for reporting it anyways @melund 
@melund, I've stopped using `setup.py develop` because of some weird `sys.path` issues over time. Which is a bummer because it's convenient when experimenting but it can be a real pain sometimes, too.
yeah develop mode has some unexpected behavior now and then,
i just reinstall in develop every time i pull from upstream.
This is strange, do you guys think it's a xonsh issue or?
FWIW I think I last used develop in 2009-2010. It may be less broken than it was then, but I haven't heard of anything major.
So I am reopening this. #2235 got merged, but my comment was probably missed https://github.com/xonsh/xonsh/pull/2235#pullrequestreview-23560160

So now this bug is in master. 
What would the right solution be here? Let `$PWD` have default values and ensures in the Env class?
@melund Uh?

> You need to check that PWD exists

[I did check that `$PWD` exists](https://github.com/xonsh/xonsh/pull/2235/files#diff-8534328692230305271758ac1f48a813R378):

```python
if 'PWD' in env and os.path.realpath(cwd) != os.path.realpath(env['PWD']):
```

The rest of access to `PWD` are guarded by the `if` so it's only accessed when it exists. And there isn't any other place where I access it.

Ohhh. Sorry @StreakyCobra.  Maybe some of the other new PR caused this issue. I just tried `del $PWD` on master this morning and saw the issue was back. But I can see that it is hardly your fault. 

Can you reproduce the problem on master?
@StreakyCobra 

Git bisect does tell me that error started after this one. 
```
72d04e996194782247cee3d969eaa3a625699ace is the first bad commit
commit 72d04e996194782247cee3d969eaa3a625699ace
Author: Fabien Dubosson <fabien.dubosson@gmail.com>
Date:   Thu Feb 23 23:15:05 2017 +0100

    Fix how ``$PWD`` is managed in order to work with symlinks gracefully
```

Maybe, the change has some side effect that causes the prompt fields to get updated. The error comes from a place that is really unrelated to your code. 

```
$ del $PWD
prompt: error: on field 'cwd'
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\prompt\base.py", line 82, in _get_field_value
    value = field_value() if callable(field_value) else field_value
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\prompt\cwd.py", line 48, in _dynamically_collapsed_pwd
    originial_path = _replace_home_cwd()
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\prompt\cwd.py", line 31, in _replace_home_cwd
    return _replace_home(builtins.__xonsh_env__['PWD'])
  File "C:\Users\mel\Anaconda3\lib\site-packages\xonsh\environ.py", line 936, in __getitem__
    raise KeyError(e.format(key))
KeyError: 'Unknown environment variable: $PWD'
```
@melund So if `git bissect` tells it me, then it is definitively me. But what's the cause of this… :flushed: 

Resolving patch:
diff --git a/xonsh/base_shell.py b/xonsh/base_shell.py
--- a/xonsh/base_shell.py
+++ b/xonsh/base_shell.py
@@ -375,12 +375,15 @@ def _fix_cwd(self):
         """Check if the cwd changed out from under us."""
         env = builtins.__xonsh_env__
         cwd = os.getcwd()
-        if 'PWD' in env and os.path.realpath(cwd) != os.path.realpath(env['PWD']):
-            old = env['PWD']  # working directory changed without updating $PWD
-            env['PWD'] = cwd  # track it now
-            if old is not None:
-                env['OLDPWD'] = old  # and update $OLDPWD like dirstack.
-            events.on_chdir.fire(olddir=old, newdir=cwd)  # fire event after cwd actually changed.
+        if 'PWD' not in env:
+            # $PWD is missing from env, recreate it
+            env['PWD'] = cwd
+        elif os.path.realpath(cwd) != os.path.realpath(env['PWD']):
+            # The working directory has changed without updating $PWD, fix this
+            old = env['PWD']
+            env['PWD'] = cwd
+            env['OLDPWD'] = old
+            events.on_chdir.fire(olddir=old, newdir=cwd)
 
     def push(self, line):
         """Pushes a line onto the buffer and compiles the code in a way that


Test patch: