Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create cross-platform rename alias #3

Open
dotsdl opened this issue Jul 14, 2019 · 3 comments
Open

Create cross-platform rename alias #3

dotsdl opened this issue Jul 14, 2019 · 3 comments

Comments

@dotsdl
Copy link

dotsdl commented Jul 14, 2019

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
Copy link

deeuu commented Dec 7, 2019

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
Copy link

deeuu commented Dec 7, 2019

Initial xontrib draft, comments welcome.

@scopatz
Copy link
Member

scopatz commented Feb 29, 2020

This would be great to have in xoreutils!

@anki-code anki-code transferred this issue from xonsh/xonsh Feb 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants