Commit graph

1693 commits

Author SHA1 Message Date
Andy Kipp
21da30e753
Fixed populating the return code for interrupted process. (#5380)
### Motivation

There is annoying behavior when you run command in the loop and can't
interrupt e.g. [this
report](https://github.com/xonsh/xonsh/discussions/5371) and a bit
#5342. After diving into this I see the issue around return code.

### The essence

Basically ``p = subprocess.Popen()`` populates ``p.returncode`` after
``p.wait()``, ``p.poll()`` or ``p.communicate()``
([doc](https://docs.python.org/3/library/os.html#os.waitpid)). But if
you're using `os.waitpid()` BEFORE these functions you're capturing
return code from a signal subsystem and ``p.returncode`` will be ``0``
like success but it's not success. So after ``os.waitid`` call you need
to set return code manually ``p.returncode = -os.WTERMSIG(status)`` like
in Popen. Example:
```xsh
python  # python interactive

import os, signal, subprocess as sp

p = sp.Popen(['sleep', '100'])
p.pid
# 123
p.wait()
# Ctrl+C or `kill -SIGINT 123` from another terminal
p.returncode
# -2

# BUT:

p = sp.Popen(['sleep', '100'])
p.pid
# 123

pid, status = os.waitpid(p.pid, os.WUNTRACED)
# status=2

# From another terminal:
kill -SIGINT 123

p.wait()
# 0
p.returncode
# 0
```

```xsh
from xonsh.tools import describe_waitpid_status
describe_waitpid_status(2)
# WIFEXITED - False - Return True if the process returning status exited via the exit() system call.
# WEXITSTATUS - 0 - Return the process return code from status.
# WIFSIGNALED - True - Return True if the process returning status was terminated by a signal.
# WTERMSIG - 2 - Return the signal that terminated the process that provided the status value.
# WIFSTOPPED - False - Return True if the process returning status was stopped.
# WSTOPSIG - 0 - Return the signal that stopped the process that provided the status value.
```

See also: [Helpful things for
knight](https://github.com/xonsh/xonsh/pull/5361#issuecomment-2078826181).

### Before

```xsh
$RAISE_SUBPROC_ERROR = True

sleep 100
# Ctrl+C
_.rtn
# 0  # It's wrong and RAISE_SUBPROC_ERROR ignored.

for i in range(5):
    print(i)
    sleep 5
# 0
# Ctrl+C  # Can't interrupt
# 1
# 2 
```

### After
```xsh
sleep 100
# Ctrl+C
_.rtn
# -2  # Like in default Popen

$RAISE_SUBPROC_ERROR = True
for i in range(5):
    print(i)
    sleep 5
# 0
# Ctrl+C
# subprocess.CalledProcessError
```

### Notes

* We need to refactor `xonsh.jobs`. It's pretty uncomfortable work with
module.
* The logic is blurry between Specs, Pipelines and Jobs. We need to
bring more clear functions.
* The `captured` variable looks like "just the way of capturing (stdout,
object)" but in fact it affects all logic very much. We need to create
table where we can see the logic difference for every type of capturing.
E.g. in `captured=stdout` mode we use `xonsh.jobs` to monitor the
command but in `captured=object` we avoid this and some logic from
`xonsh.jobs` applied in `stdout` mode but missed in `object` mode. We
need clear map.

## For community
⬇️ **Please click the 👍 reaction instead of leaving a `+1` or 👍
comment**

---------

Co-authored-by: a <1@1.1>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-05-02 22:10:53 +02:00
Andy Kipp
c5cb7044b5
feat: add subproc output format, autostrip singleline output (#5377)
### Motivation

* To have an ability to manage the output format added ``$XONSH_SUBPROC_OUTPUT_FORMAT`` to switch the way to return the output lines. Default ``stream_lines`` to return text. Alternative ``list_lines`` to return the list of lines. Also supported custom lambda function.
* Additionally the [proposal to change default behavior](https://github.com/xonsh/xonsh/pull/5377#discussion_r1587627131) for a single line case.
* Closes #3924 as soft solution.

### Before

```xsh
mkdir -p /tmp/tst && cd /tmp/tst && touch 1 2 3

$(ls)
# '1\n2\n3\n'

id $(whoami)
# id: ‘pc\n’: no such user: Invalid argument

du $(ls)
# du: cannot access '1'$'\n''2'$'\n''3'$'\n': No such file or directory

ls $(fzf)
# ls: cannot access 'FUNDING.yml'$'\n': No such file or directory
```

### After

```xsh
mkdir -p /tmp/tst && cd /tmp/tst && touch 1 2 3

$XONSH_SUBPROC_OUTPUT_FORMAT = 'list_lines'

$(ls)
# ['1', '2', '3']

[f for f in $(ls)]
# ['1', '2', '3']

id $(whoami)
# uid=501(user) gid=20(staff)

du $(ls)
# 0 1
# 0 2
# 0 3

ls $(fzf)
# FUNDING.yml

# etc
mkdir -p /tmp/@($(whoami))/dir
cat /etc/passwd | grep $(whoami)
```

### Notes

* It will be good to improve parser for cases like `mkdir -p /tmp/$(whoami)/dir`. PR is welcome!
* I named the default mode as `stream_lines` (instead of just `stream` or `raw`) because in fact we transform raw output into stream of lines and possibly reduce the length of output ([replacing `\r\n` to `\n`](c3a12b2a9c/xonsh/procs/pipelines.py (L380-L383))). May be some day we need to add raw "stream" output format.
* Now anybody can implement bash `IFS` behavior in [bashisms](https://github.com/xonsh/xontrib-bashisms).

---------

Co-authored-by: a <1@1.1>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-05-02 11:48:25 -04:00
a
79f02e9ea4 update 2024-04-21 17:14:31 +05:30
Andy Kipp
330f150f6a
EnvPath methods (append, remove, add, insert) prepare the path (#5349)
* EnvPath methods (append, remove, add, insert) prepare the path before add.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* update

* update

* update

* update

* update

---------

Co-authored-by: a <1@1.1>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-04-21 10:03:42 +02:00
Noortheen Raja
a5eb5bfbf2 test: xfail virtualenv plugin 2024-04-20 23:44:26 +05:30
Gil Forsyth
fde07cda5f
refactor(aliases): source foreign shell funcs without interactive mode (#5344)
Co-authored-by: Noortheen Raja <jnoortheen@gmail.com>
2024-04-18 19:51:39 +05:30
Noortheen Raja
aa857e8260 refactor: update line length to default setting
and ruff-format
2024-04-16 11:23:35 -04:00
Peter Ye
5a525e3789
feat: allow square brackets in command arguments (#5326)
Allow square brackets in command arguments
2024-04-09 22:33:43 +05:30
Peter Ye
08ac0d9759
Fix parsing of redirect tokens (#5322)
* Fix parsing of redirect tokens

In the parser, wrap redirect tokens such as ">", "a>", and "2>1" in a
tuple (along with the name of the redirect file, if applicable) to
differentiate them from regular command line arguments.

This ensures that a command like ![echo ">"] is parsed correctly.

We now need 2 types of IO-redirect tokens (IOREDIRECT1 and IOREDIRECT2)
so that the parser knows whether or not an IO-redirect has a file
argument. For example, "a>" has type IOREDIRECT1, whereas "2>1" has
type IOREDIRECT2.

* update ioredir tests

* add tests

* add news

* fix multiple redirections error message
2024-04-05 13:21:54 +05:30
Peter Ye
7461c507b2
Fix incorrect IOREDIRECT tokens in Python mode (#5013)
* add tests

* Fix incorrect IOREDIRECT tokens in Python mode

* add news

* Update lexer used in CompletionContextParser

The completion context lexer should start in subprocess mode so that
operators like ``2>`` are recognized as IOREDIRECT tokens.

This fixes the test case "command 2>/dev/nul{X}" for
test_completion_context.py::test_command.
2024-04-04 16:04:53 +05:30
Noortheen Raja
c930c9f234 fix: web config overwrite existing value
fixes #5297
2024-03-19 16:33:12 +05:30
Noortheen Raja
3574acfa51 test: add tests for webconfig post methods 2024-03-19 16:33:12 +05:30
pre-commit-ci[bot]
66c0490d37
[pre-commit.ci] pre-commit autoupdate (#5271)
* [pre-commit.ci] pre-commit autoupdate

updates:
- [github.com/psf/black: 23.12.1 → 24.1.1](https://github.com/psf/black/compare/23.12.1...24.1.1)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-01-30 12:23:50 +01:00
Airat Makhmutov
66f0ba39f2
fix test_bash_completer for the date command (#5258)
see https://github.com/xonsh/xonsh/issues/5257

Co-authored-by: Ajrat Makhmutov <rauty@altlinux.org>
2023-12-31 16:08:28 +01:00
Gil Forsyth
0fe0a6c03e
fix(dirstack): use XSH.env for $HOME check, not os.path (#5211)
`os.path.expanduser` relies on the value of `$HOME` set in `os.environ`.
This meant that a user who set `$HOME` would then not end up in that
directory with a no-argument call to `cd` unless they had set
`UPDATE_OS_ENVIRON`.

Now the value of `$HOME` is respected regardless of the setting in `UPDATE_OS_ENVIRON`
2023-09-25 14:53:15 +06:00
pre-commit-ci[bot]
3c78f77eea [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2023-09-18 11:08:08 +05:30
Noorhteen Raja NJ
b4d196db17 fix: ruff linter errors 2023-09-18 11:08:08 +05:30
Wilfried Pollan
b3c3e60a05
Fix/parse multiline foreign shell aliases (#5191)
* fix: Correctly multi line aliases

Bash aliases can span multi lines for readablity or if they are to long
for one line.

Here we just remove added the backslash before further processing.

* doc: Add news item for fix/parse-multiline-aliases branch

---------

Co-authored-by: Wilfried Pollan <wilfried.pollan@moqodow.com>
2023-08-23 00:47:47 +06:00
pre-commit-ci[bot]
7bd8f5da9f
[pre-commit.ci] pre-commit autoupdate (#5180)
* [pre-commit.ci] pre-commit autoupdate

updates:
- [github.com/astral-sh/ruff-pre-commit: v0.0.278 → v0.0.280](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.278...v0.0.280)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix: ruff linter errors

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Noorhteen Raja NJ <jnoortheen@gmail.com>
2023-07-27 13:17:51 +05:30
Cosine Chen
0e229fcc8c
Always load rc files except --no-rc is passed (#5099) 2023-07-26 22:44:55 +00:00
Noorhteen Raja NJ
769dfbe6aa
Py 312 pre-liminary support (#5156)
* refactor: project requires 3.9+

changed as per NEP-29
https://numpy.org/neps/nep-0029-deprecation_policy.html

* test: nose type tests are deprecated in pytest now

* fix: deprecation of ast.Str and ast.Bytes and .s attribute access

* fix: deprecation of ast.Num,ast.NameConstant,ast.Ellipsis

* refactor: upgrade code to be py39+ using ruff

the changes are auto-generated

* refactor: remove typing.Annotated compatibility code

* fix: temporarily disable having xonsh syntax inside f-strings

* test: skip failing tests

there is no workaround for this version. It might get solved in the
final release though

* refactor: make XonshSession.completer lazily populated

this speedsup the tests as cmd_cache would not be actively populated
when used in default_completers function

* refactor: make presence of walrus operator default
2023-07-04 22:18:37 +05:30
pre-commit-ci[bot]
6d58fb5bf7
[pre-commit.ci] pre-commit autoupdate (#5148)
* [pre-commit.ci] pre-commit autoupdate

updates:
- [github.com/charliermarsh/ruff-pre-commit: v0.0.269 → v0.0.270](https://github.com/charliermarsh/ruff-pre-commit/compare/v0.0.269...v0.0.270)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-05-30 17:10:53 +06:00
Noorhteen Raja NJ
479413b5d0
Ruff linter (#5118) 2023-04-19 12:59:32 +00:00
Andy Kipp
042487745a
Moving old xontribs to repositories (#5055)
* Update and rename README to README.rst

* Create hello_world.py

* Update README.rst

* init

* remove bashisms

* Transfer abbrevs to xontrib-abbrevs

* Transfer free-cwd to xontrib-free-cwd

* news

* black

* Transfer fish-completer to xonsh/xontrib-fish-completer

* Transfer vox to xonsh/xontrib-vox

* Transfer pdb, xog to xonsh/xontrib-debug-tools

* remove hello_world

* fix tests

* black

* fix whitespaces

* fix readme

* Update python_virtual_environments.rst

* Update README.rst

* Update xontribs_transfer.rst

---------

Co-authored-by: a <1@1.1>
2023-03-17 13:25:22 +06:00
Ivan Ogasawara
2a63f1f875
Improve error message for RAISE_SUBPROC_ERROR=True (#5072)
* Improve error message for RAISE_SUBPROC_ERROR=True

* Fix tests

* Add colors to the short output

* Move the colored code to a function

* Fix output
2023-03-05 07:49:42 +05:30
Andy Kipp
54962fb4b9
Mini fix chdir (#5080)
* Update tools.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-03-04 09:02:55 +05:30
Thomas Hess
cb95f0e487
Add support for Fossil SCM branch names in vc.py. (#5046)
Add support for Fossil VCS in vc.py.

The prompt now shows the currently active Fossil branch, while inside a Fossil checkout.
2023-03-02 12:35:22 +05:30
Andy Kipp
237e231e7f
Moving chdir to xonsh.tools (#5073)
* chdir

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: a <1@1.1>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-03-02 12:31:08 +05:30
Andy Kipp
ec378090ce
Using repr(cmd) for command not found (#5075)
repr cmd

Co-authored-by: a <1@1.1>
2023-03-02 11:13:36 +05:30
pre-commit-ci[bot]
ba8ae973b8 [pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/psf/black: 22.12.0 → 23.1.0](https://github.com/psf/black/compare/22.12.0...23.1.0)
- [github.com/pycqa/isort: 5.11.4 → 5.12.0](https://github.com/pycqa/isort/compare/5.11.4...5.12.0)
2023-02-14 22:57:36 +05:30
Gil Forsyth
df8952d99e fix(sqlite): skip sqlite history tests on windows with python 3.11
I've tried several workarounds and this isn't important enough to keep
spending time on.
2023-01-17 13:27:17 -05:00
Gil Forsyth
33b2ac052b fix: update ptk highlight tests to reflect new tokenizing
temporary fix while we sort out what broke upstream
2023-01-17 13:27:17 -05:00
yotamolenik
e6932747f9
commands_cache: ignore mtime check on non-darwin os (#4988)
* environ: add a configurable value to disable cache

* docs: update env variable doc

Co-authored-by: Noorhteen Raja NJ <jnoortheen@gmail.com>
2022-12-05 21:04:20 +05:30
Noorhteen Raja NJ
c63f75efd0
cmd cache refactor - optimize cache usage (#4954)
* todo:

* refactor: remove usage of singleton in cmd-cache

* refactor: pass aliases/env to commands_cache on creation

reduce the usage of singletons

* fix: setting up mockups for tests

* feat: add $XONSH_CACHE_DIR

* refactor: use cache path to stire cmds-cache

* chore: todo

* feat: efficient cache commands per path and modified time

* refactor: move aliases to commands cache

now XonshSession is not needed to setup cmds-cache

* refactor: update tests

* fix: type annotation

* refactor: init aliases at commands-cache

* test: update failing tests

* fix: handle paths mtime changing

* docs: add news item

* refactor: remove $COMMANDS_CACHE_SIZE_WARNING

* fix: loading on windows fails because of setup sequence

* fix: failing tests
2022-11-14 23:52:10 +05:30
austin-yang
ed11f319fa
Fix: Allows user to assign #XONSH_STYLE_OVERRIDES a {Token:str} dictionary #4375 (#4973)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-10-24 10:46:52 -04:00
Vasilis Gerakaris
9c1a751fee
Fix auto-suggestion completion stacking if no normal completion exists (#4970)
* Fix auto-suggestion completion stacking if no normal completion exists

* Add tests for auto-suggest completions
2022-10-21 00:48:31 +05:30
Blake Ramsdell
b0c81048af
feat: add on_command_not_found event (#4959) 2022-10-11 08:54:12 -04:00
Blake Ramsdell
b5c42d6716
Add XONSH_HISTORY_IGNORE_REGEX support (#4953)
* Add XONSH_HISTORY_IGNORE_REGEX support

* Add changelog text

* Add cleanup notes for XONSH_HISTORY_IGNORE_REGEX

* Rename should_append to is_ignored

* Change is_ignored to a History method

* Remove unused re imports

* Docstring formatting cleanup, Black compliance

* Move XONSH_HISTORY_IGNORE_REGEX to History class

* Clarify with parenthesis

* Formatting compliance

* Add validate_ignore_regex check

* Remove validation comment

* Remove XONSH_HISTORY_IGNORE_REGEX test comments

* Add __init__ chaining to DummyHistory

* Add broken test for XONSH_IGNORE_REGEX

* Remove extra test variants

* Fix unit test environment variable name

* Add test for bad regex error output

* Remove unneeded __init__ chaining

* Add test_is_ignore

* Add is_regex and associated tests

* Add doc for XONSH_HISTORY_IGNORE_REGEX

* Change validate_ignore_regex to use is_regex

* Compile regex once and use a cached property

* Let cached_property handle saving regex
2022-10-05 00:16:42 +05:30
Peter Ye
588881803c
Make gitstatus prompt field values None when there is no git repo (#4920)
Make gitstatus prompt fields None when there is no git repo
2022-08-17 10:08:02 +05:30
Peter Ye
6fa83f8305
Do not capture unthreaded callable aliases run with ![] (#4919)
* Fix `cd` command error message when `$THREAD_SUBPROCS=False`

* also test $[]
2022-08-11 22:50:21 +05:30
Peter Ye
08b302364a
Update terminal title before executing subprocess (#4916)
* Update terminal title before executing subprocess

This eliminates the need to use `pause_call_resume()`, which causes issues
when it sends SIGSTOP to a process that is in the middle of a syscall
(for example, the `swaymsg` command fails when it gets stopped during
a `recv` syscall).

Additionally, this approach is more flexible, as it allows captured
commands and callable aliases to also be updated as expected in the
terminal's title.

* Clear prompt cache in readline shell

* Add type annotation

* Use reset_key() to only reset current_job

* Convert into PromptField class

* Support PromptField with value of None

Allows {current_job:{} | } to work as expected when current_job is a
PromptField.

* Add tests
2022-08-10 09:50:09 +05:30
Stefano Rivera
9e5af81b89
We can't be sure there's a python binary (#4917)
Debian doesn't currently ship a /usr/bin/python binary, unless a user
specifically installs python-is-python3.

See also: #4802
2022-08-09 21:12:40 +05:30
jbw3
f2ca59a291
Fixing bash completion bug when prefix started with '>', '<', or ':' (#4826)
* Fixing bash completion bug when prefix started with '>', '<', or ':'

* Fixing code formatting

* More code formatting fixes

* Fixing test

* Refactor to fix bug by improving completion parser

* Supporting '<' and '>>' in completion parser

* Support for all IO redirect tokens
2022-08-06 14:37:09 +05:30
Noorhteen Raja NJ
dd6c873f3c
fix: empty gitstatus on paths without repo (#4907)
* fix: empty gitstatus on paths without repo

fixes #4900

* docs: add news item

* fix: failing test because of cache in git-dir per cwd
2022-08-03 19:09:43 +05:30
Peter Ye
86e4f004e3
Fix job control for callable aliases (#4901)
* Make job control task queue thread-local

This allows callable aliases to maintain a separate task queue from the
main thread.

* Make job control dictionary thread-local

Use XSH.all_jobs for the main thread and a separate dictionary for other
threads. This allows callable aliases to keep track of their jobs
separate from the main thread.

* Implement use_main_jobs() context manager

This allows threaded commands like jobs, disown, and bg to handle the
main thread's job control

* Run commands in the same process group if in a thread

* Fix tests that use jobs and tasks

* Add tests for subprocess call inside alias

* Add news

* Remove type declarations for _jobs_thread_local

Fixes the mypy error: "Type cannot be declared in assignment to non-self attribute"

Co-authored-by: Noorhteen Raja NJ <jnoortheen@gmail.com>
2022-08-03 11:37:26 +05:30
Noorhteen Raja NJ
8a5b50e084
Update test_pip_completer.py (#4890)
* Update test_pip_completer.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2022-07-25 15:05:00 +05:30
Eddie Peters
8b9a7e2782
fix(pyghooks): Fix some errors caused by an unset Xonsh session env when using XonshLexer as a Pygments plugin. (#4860) 2022-06-30 10:40:58 -04:00
Peter Ye
ed213f852b
fix: string literal concatenation (#4838)
* fix: string literal concatenation

Fix string literal concatenation involving f-strings and path literals.
Raise SyntaxError when string literal concatenation is attempted between
different literal types (e.g. str and bytes).

* Add tests

Make nodes_equal() check whether the values of Constant nodes are equal.

* add news

* update nodes_equal() error msg
2022-06-18 08:34:34 +05:30
Noorhteen Raja NJ
3716f3da86
Pr5 xontrib entrypoints (#4827) 2022-06-17 12:39:12 -04:00
Peter Ye
b2c42ed2f3
feat: f-glob strings (#4835)
* feat: add support for f-glob strings

Move xonsh_pathsearch() into the BaseParser class because it needs to use self._set_error()

Parametrize 6 backtick tests in test_parser.py into test_backtick() (and add cases for f-glob strings)

* add news

* docs: update tutorial

* fix news file
2022-06-12 13:45:16 +05:30