Exemplo n.º 1
0
def filepull(pull_from='.', autoyes=False):
    files = list(spinal.walk(pull_from))
    cwd = os.getcwd()
    files = [f for f in files if os.path.split(f.absolute_path)[0] != cwd]

    if len(files) == 0:
        print('No files to move')
        return

    duplicate_count = {}
    for f in files:
        basename = f.basename
        duplicate_count.setdefault(basename, [])
        duplicate_count[basename].append(f.absolute_path)

    duplicates = [
        '\n'.join(sorted(copies))
        for (basename, copies) in duplicate_count.items() if len(copies) > 1
    ]
    duplicates = sorted(duplicates)
    if len(duplicates) > 0:
        raise Exception('duplicate names:\n' + '\n'.join(duplicates))

    for f in files:
        print(f.basename)

    if autoyes or interactive.getpermission(f'Move {len(files)} files?'):
        for f in files:
            local = os.path.join('.', f.basename)
            os.rename(f.absolute_path, local)
Exemplo n.º 2
0
def contentreplace(file,
                   replace_from,
                   replace_to,
                   autoyes=False,
                   do_regex=False):
    file = pathclass.Path(file)
    with file.open('r', encoding='utf-8') as f:
        content = f.read()

    if do_regex:
        occurances = len(re.findall(replace_from, content, flags=re.MULTILINE))
    else:
        occurances = content.count(replace_from)

    print(f'{file.absolute_path}: Found {occurances} occurences.')
    if occurances == 0:
        return

    if not (autoyes or interactive.getpermission('Replace?')):
        return

    if do_regex:
        content = re.sub(replace_from, replace_to, content, flags=re.MULTILINE)
    else:
        content = content.replace(replace_from, replace_to)

    with file.open('w', encoding='utf-8') as f:
        f.write(content)
Exemplo n.º 3
0
def prune_shortcuts(recurse=False, autoyes=False):
    if recurse:
        lnks = [file for file in spinal.walk('.') if file.extension == 'lnk']
    else:
        lnks = pathclass.cwd().glob('*.lnk')

    stale = []
    for lnk in lnks:
        shortcut = winshell.Shortcut(lnk.absolute_path)
        # There are some special shortcuts that do not have a path, but instead
        # trigger some action based on a CLSID that Explorer understands.
        # I can't find this information in the winshell.Shortcut object, so for
        # now let's at least not delete these files.
        if shortcut.path == '':
            continue
        if not os.path.exists(shortcut.path):
            stale.append(lnk)

    if not stale:
        return

    print(f'The following {len(stale)} will be recycled:')
    for lnk in stale:
        print(lnk.absolute_path)
    print()

    if autoyes or interactive.getpermission('Is that ok?'):
        for lnk in stale:
            print(lnk.absolute_path)
            send2trash.send2trash(lnk.absolute_path)
Exemplo n.º 4
0
def extension_registry(ico_file, human_name=None):
    if ico_file.extension != 'ico':
        raise ValueError('Must provide a .ico file.')

    name = ico_file.replace_extension('').basename

    dot_ex = f'.{name}'
    hash_ex = f'#{name}'

    prompt = [
        f'Set {dot_ex} = {hash_ex}',
        f'Set {hash_ex}\\DefaultIcon = {ico_file.absolute_path}',
    ]

    if human_name:
        prompt.append(f'Set {hash_ex} = {human_name}')

    prompt = '\n'.join(prompt)

    if not interactive.getpermission(prompt):
        return

    dot_key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, dot_ex)
    winreg.SetValueEx(dot_key, '', 0, winreg.REG_SZ, hash_ex)

    hash_key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, hash_ex)
    if human_name:
        winreg.SetValueEx(hash_key, '', 0, winreg.REG_SZ, human_name)

    icon_key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT,
                                f'{hash_ex}\\DefaultIcon')
    winreg.SetValueEx(icon_key, '', 0, winreg.REG_SZ, ico_file.absolute_path)

    print('Finished.')
Exemplo n.º 5
0
def brename(transformation,
            autoyes=False,
            do_naturalsort=False,
            recurse=False):
    if recurse:
        walker = spinal.walk('.', yield_files=True, yield_directories=True)
        olds = list(walker)
    else:
        olds = cwd.listdir()

    if do_naturalsort:
        olds.sort(key=lambda x: natural_sorter(x.absolute_path))
    else:
        olds.sort()

    pairs = []
    for (index, old) in enumerate(olds):
        # These variables are assigned so that you can use them in your
        # transformation string.
        x = old.basename
        parent = old.parent
        noext = old.replace_extension('').basename
        ext = old.extension.no_dot
        dot_ext = old.extension.with_dot
        index1 = index + 1

        new = eval(transformation)
        new = parent.with_child(new)
        if new.basename == old.basename:
            continue
        pairs.append((old, new))

    if not pairs:
        print('Nothing to replace')
        return

    loop(pairs, dry=True)

    if not (autoyes or interactive.getpermission('Is this correct?')):
        return

    # Sort in reverse so that renaming a file inside a directory always
    # occurs before renaming the directory itself. If you rename the
    # directory first, then the path to the file is invalid by the time
    # you want to rename it.
    pairs = sorted(pairs, reverse=True)
    loop(pairs, dry=False)
Exemplo n.º 6
0
def getcrx(extension_id, auto_overwrite=None):
    url = CRX_URL.format(extension_id=extension_id)
    response = session.get(url)
    response.raise_for_status()

    (name, version) = get_webstore_name_version(extension_id)
    if name is None or version is None:
        (crx_name, crx_ver) = get_crx_name_version(response.content)
        name = name or crx_name
        version = version or crx_ver

    name = name or extension_id
    version = version or time.strftime('%Y%m%d')

    version = version or response.url.split('/')[-1]

    crx_filename = '{name} ({id}) [{version}]'
    crx_filename = crx_filename.format(
        name=name,
        id=extension_id,
        version=version,
    )

    if not crx_filename.endswith('.crx'):
        crx_filename += '.crx'

    crx_filename = sanitize_filename(crx_filename)
    if os.path.isfile(crx_filename):
        if auto_overwrite is True:
            permission = True
        if auto_overwrite is None:
            message = f'"{crx_filename}" already exists. Overwrite?'
            permission = interactive.getpermission(message)
        else:
            permission = False
    else:
        permission = True

    if permission:
        crx_handle = open(crx_filename, 'wb')
        crx_handle.write(response.content)
        print(f'Downloaded "{crx_filename}".')
Exemplo n.º 7
0
def adbinstall_argparse(args):
    patterns = pipeable.input_many(args.apks, skip_blank=True, strip=True)
    apks = [file for pattern in patterns for file in winglob.glob(pattern)]
    installs = []
    for apk in args.apks:
        apk = pathclass.Path(apk)
        if apk.is_dir:
            files = apk.glob('*.apk')
            files.sort(key=lambda x: natural_sorter(x.basename.lower()))
            apk = files[-1]
        installs.append(apk)

    if not args.autoyes:
        for apk in installs:
            print(apk.absolute_path)
        if not interactive.getpermission('Is that okay?', must_pick=True):
            return 1

    for apk in installs:
        command = f'adb install "{apk.absolute_path}"'
        log.info(command)
        os.system(command)
Exemplo n.º 8
0
def bitwise_or_argparse(args):
    patterns = pipeable.input_many(args.files, skip_blank=True, strip=True)
    files = [file for pattern in patterns for file in winglob.glob(pattern)]
    files = [pathclass.Path(file) for file in files]

    if len(files) < 2:
        log.fatal('Need at least two input files.')
        return 1

    handles = [file.open('rb') for file in files]

    output = pathclass.Path(args.output)
    if output.is_dir:
        log.fatal('Output path "%s" is a directory.', args.output)
        return 1

    if not output.exists:
        pass
    elif args.overwrite:
        pass
    elif not interactive.getpermission(f'Overwrite "{output.absolute_path}"?'):
        return 1

    output_handle = output.open('wb')
    while True:
        chunk = 0
        length = 1
        for handle in handles[:]:
            read = handle.read(CHUNK_SIZE)
            length = max(length, len(read))
            if not read:
                handles.remove(handle)
            chunk |= int.from_bytes(read, 'big')
        if not handles:
            break
        output_handle.write(chunk.to_bytes(length, 'big'))
    pipeable.stdout(output.absolute_path)
Exemplo n.º 9
0
def pypi_release(do_tag=False, versionbump='patch'):
    git_assert_no_stashes()
    git_assert_pushable()

    (setup_py, name, old_version) = extract_info_from_setup()
    new_version = bump_version(old_version, versionbump)
    new_tag = f'v{new_version}'

    (latest_release_commit, latest_release_version) = git_determine_latest_release()

    git_assert_current_greater_than_latest(latest_release_version, new_version)

    commits_since_last_release = git_commits_since(latest_release_commit, show=False)
    if len(commits_since_last_release) == 0:
        print('No new commits to release')
        return

    (remote, branch) = git_current_remote_branch()

    def linebreak():
        cli_width = shutil.get_terminal_size()[0]
        line = '#' * (cli_width - 1)
        line += '\r'
        line += f'# {name} {new_version} '
        line = f'\n{line}\n'
        slowprint(line)

    linebreak()

    slowprint(f'Upgrading {name} from {old_version} --> {new_version}.')
    slowprint()

    if latest_release_commit:
        slowprint('Latest release:')
        git_show_commit(latest_release_commit)
        slowprint()

    slowprint('This release:')
    git_commits_since(latest_release_commit, show=True)
    slowprint()

    setup_py = update_info_in_setup(setup_py, name, new_version)
    slowprint('Rewrite setup.py:')
    slowprint(textwrap.indent(setup_py, '>>> '))
    slowprint()

    slowprint(f'Release will be pushed to {remote} {branch}.')

    linebreak()

    if not interactive.getpermission(f'READY TO RELEASE {name} {new_version}.'):
        return

    write_setup(setup_py)

    git_commit_bump(new_version)
    if do_tag:
        git_tag_version(new_tag)

    git_push(remote, branch)
    if do_tag:
        git_push_tag(remote, new_tag)

    did_stash = git_stash_push()
    pypi_upload(name)
    if did_stash:
        git_stash_restore()

    git_commits_since(latest_release_commit, show=True)