xonsh / xontrib-coreutils

Additional cross-platform core utilities that are implemented in xonsh.
2 stars 1 forks source link

Create cross-platform `rename` alias #3

Open dotsdl opened 5 years ago

dotsdl commented 5 years ago

Reference xonsh/xonsh#308

Create a rename alias that works across platforms. This is currently unavailable on e.g. MacOS.

For community

⬇️ Please click the 👍 reaction instead of leaving a +1 or 👍 comment

deeuu commented 4 years ago

Do we really need to ship a rename alias? There are cross-platform implementations out there, e.g. brename. Perhaps a xontrib might be more appropriate?

Any how, what about wrapping re.sub, keeping things simple yet familiar to Pythonistas:

import os
import re

def _srename(args, stdin=None):

    pattern, repl, files, options = _parse_srename_args(args)

    if options['invert']:
        pattern, repl = repl, pattern

    for old_name in files:
        if not os.path.exists(old_name):
            print(f'Warning: {old_name} does not exist')
            continue

        new_name = re.sub(pattern, repl, old_name)

        if (old_name == new_name):
            continue

        if os.path.exists(new_name):
            print(f'Warning: {new_name} already exists')
            continue

        if options['dry-run']:
            print(f'Info: {old_name} → {new_name} (not renaming as dry run)')
        else:
            os.rename(old_name, new_name)

def _parse_srename_args(args):
    options = {'dry-run': False, 'invert': False}
    if '--dry-run' in args:
        args.remove('--dry-run')
        options['dry-run'] = True
    if '--invert' in args:
        args.remove('--invert')
        options['invert'] = True
    pattern, repl, *rest = args 
    return pattern, repl, rest, options

aliases['srename'] = _srename

e.g.

touch foo1.txt foo2.txt
srename foo bar *.txt
srename foo bar *.txt --invert
srename foo @(lambda match: f'{match.group(0).upper()}BAR') *.txt
deeuu commented 4 years ago

Initial xontrib draft, comments welcome.

scopatz commented 4 years ago

This would be great to have in xoreutils!