Search code examples
pythonshellxonsh

How to override built-in command in xonsh?


I'm trying to override 'ls' command to display dotfiles in "dotfiles" directory.

Here is my code.

def _ls():
    if $(pwd).rstrip(os.linesep) == $DOTFILES:
        ls -Ga
    else:
        ls -G
aliases['ls'] = _ls

This code goes into an endless loop because _ls function calls ls command and it calls _ls function.

Any ideas?


Solution

  • The infinite alias call shouldn't happen -- would you mind opening up an issue at github.com/xonsh/xonsh/issues?

    In the interim, here's a way to structure your alias that will work without any fixes:

    def _ls(args):
        args = args[0].replace('-', '') if args else ''
        if $(pwd).rstrip(os.linesep) == $DOTFILES:
            $(which -s ls) @(f"-{''.join(set(args + 'aG'))}")
        else:
            $(which -s ls) @(f"-{''.join(set(args + 'G'))}")
    aliases['ls'] = _ls
    

    The -s argument to which skips alias resolution, so that returns the path to the actual ls executable. Then the set logic is to make sure arguments aren't duplicated (although I'm not sure that's strictly necessary).