Ejemplo n.º 1
0
def loop(pairs, dry=False):
    for (old, new) in pairs:
        if dry:
            line = f'{old.absolute_path}\n{new.absolute_path}\n'
            safeprint.safeprint(line)
        else:
            os.rename(old.absolute_path, new.absolute_path)
Ejemplo n.º 2
0
def search_contents_generic(filepath, content_args):
    try:
        with filepath.open('r') as handle:
            text = handle.read()
    except UnicodeDecodeError:
        try:
            with filepath.open('r', encoding='utf-8') as handle:
                text = handle.read()
        except UnicodeDecodeError:
            #safeprint.safeprint(filepath.absolute_path)
            #traceback.print_exc()
            return
    except Exception:
        safeprint.safeprint(filepath.absolute_path)
        traceback.print_exc()
        return

    content_args['text'] = text
    content_args['line_numbers'] = True

    results = search(**content_args)
    results = list(results)
    if not results:
        return

    yield filepath.absolute_path
    yield from results
    yield ''
Ejemplo n.º 3
0
def _search_argparse(args):
    generator = search(**argparse_to_dict(args))
    result_count = 0
    for result in generator:
        safeprint.safeprint(result)
        result_count += 1
    if args.show_count:
        print('%d items.' % result_count)
Ejemplo n.º 4
0
def search_argparse(args):
    generator = search(**argparse_to_dict(args))
    result_count = 0
    for result in generator:
        safeprint.safeprint(result)
        result_count += 1
    if args.show_count:
        print('%d items.' % result_count)
Ejemplo n.º 5
0
def touch(glob_pattern):
    filenames = glob.glob(glob_pattern)
    if len(filenames) == 0:
        safeprint.safeprint(glob_pattern)
        open(glob_pattern, 'a').close()
    else:
        for filename in filenames:
            safeprint.safeprint(filename)
            os.utime(filename)
Ejemplo n.º 6
0
def touch(glob_pattern):
    filenames = glob.glob(glob_pattern)
    if len(filenames) == 0:
        safeprint.safeprint(glob_pattern)
        open(glob_pattern, 'a').close()
    else:
        for filename in filenames:
            safeprint.safeprint(filename)
            os.utime(filename)
Ejemplo n.º 7
0
def loop(pairs, dry=False):
    has_content = False
    for (x, y) in pairs:
        if dry:
            line = '{old}\n{new}\n'
            line = line.format(old=x, new=y)
            #print(line.encode('utf-8'))
            safeprint.safeprint(line)
            has_content = True
        else:
            os.rename(x, y)
    return has_content
Ejemplo n.º 8
0
def loop(pairs, dry=False):
    has_content = False
    for (x, y) in pairs:
        if dry:
            line = '{old}\n{new}\n'
            line = line.format(old=x, new=y)
            #print(line.encode('utf-8'))
            safeprint.safeprint(line)
            has_content = True
        else:
            os.rename(x, y)
    return has_content
Ejemplo n.º 9
0
def fileprefix(
        prefix='',
        sep=' ',
        ctime=False,
        dry=False,
    ):
    current_directory = pathclass.Path('.')

    prefix = prefix.strip()
    if prefix == ':':
        prefix = current_directory.basename + ' - '
    elif prefix != '':
        prefix += sep

    filepaths = current_directory.listdir()
    filepaths = [f for f in filepaths if f.is_file]
    filepaths = [f for f in filepaths if f.extension.lower() not in IGNORE_EXTENSIONS]

    try:
        pyfile = pathclass.Path(__file__)
        filepaths.remove(pyfile)
    except ValueError:
        pass

    # trust me on this.
    zeropadding = len(str(len(filepaths)))
    zeropadding = max(2, zeropadding)
    zeropadding = str(zeropadding)

    format = '{{prefix}}{{index:0{pad}d}}{{extension}}'.format(pad=zeropadding)

    if ctime:
        print('Sorting by time')
        filepaths.sort(key=lambda x: x.stat.st_ctime)
    else:
        print('Sorting by name')
        filepaths.sort(key=lambda x: natural_sorter(x.basename))

    for (index, filepath) in enumerate(filepaths):
        extension = filepath.extension
        if extension != '':
            extension = '.' + extension

        newname = format.format(prefix=prefix, index=index, extension=extension)
        if filepath.basename != newname:
            message = filepath.basename + ' -> ' + newname
            safeprint.safeprint(message)
            if not dry:
                os.rename(filepath.absolute_path, newname)
                pass
    if dry:
        print('Dry. No files renamed.')
Ejemplo n.º 10
0
def pathtree_argparse(args):
    from voussoirkit import safeprint
    from voussoirkit import spinal
    paths = spinal.walk()
    paths = [{'path': path.absolute_path, 'size': path.size} for path in paths]
    tree = from_paths(paths, '.')
    recursive_get_size(tree)

    if args.output_file:
        output_file = open(args.output_file, 'w', encoding='utf-8')
    else:
        output_file = None

    for line in recursive_print_node(tree, use_html=args.use_html):
        if output_file:
            print(line, file=output_file)
        else:
            safeprint.safeprint(line)
Ejemplo n.º 11
0
def search(
        *,
        yes_all=None,
        yes_any=None,
        not_all=None,
        not_any=None,
        case_sensitive=False,
        content_args=None,
        do_expression=False,
        do_glob=False,
        do_regex=False,
        line_numbers=False,
        local_only=False,
        text=None,
    ):
    if text is None:
        print('starting search')
    terms = {
        'yes_all': yes_all,
        'yes_any': yes_any,
        'not_all': not_all,
        'not_any': not_any
    }
    terms = {k: ([v] if isinstance(v, str) else v or []) for (k, v) in terms.items()}
    #print(terms, content_args)

    if all(v == [] for v in terms.values()) and not content_args:
        raise ValueError('No terms supplied')

    def term_matches(line, term):
        if not case_sensitive:
            line = line.lower()

        if do_expression:
            return term.evaluate(line)

        return (
            (term in line) or
            (do_regex and re.search(term, line)) or
            (do_glob and fnmatch.fnmatch(line, term))
        )

    if do_expression:
        # The value still needs to be a list so the upcoming any() / all()
        # receives an iterable as it expects. It just happens to be 1 tree.
        trees = {}
        for (key, value) in terms.items():
            if value == []:
                trees[key] = []
                continue
            tree = ' '.join(value)
            tree = expressionmatch.ExpressionTree.parse(tree)
            if not case_sensitive:
                tree.map(str.lower)
            trees[key] = [tree]
        terms = trees

    elif not case_sensitive:
        terms = {k: [x.lower() for x in v] for (k, v) in terms.items()}

    if text is None:
        search_objects = spinal.walk_generator(
            depth_first=False,
            recurse=not local_only,
            yield_directories=True,
        )
    else:
        search_objects = text.splitlines()

    for (index, search_object) in enumerate(search_objects):
        if index % 10 == 0:
            #print(index, end='\r', flush=True)
            pass
        if isinstance(search_object, pathclass.Path):
            search_text = search_object.basename
            result_text = search_object.absolute_path
        else:
            search_text = search_object
            result_text = search_object
        if line_numbers:
            result_text = '%4d | %s' % (index+1, result_text)

        if all_terms_match(search_text, terms, term_matches):
            if not content_args:
                yield result_text
            else:
                filepath = pathclass.Path(search_object)
                if not filepath.is_file:
                    continue
                try:
                    with open(filepath.absolute_path, 'r') as handle:
                        text = handle.read()
                except UnicodeDecodeError:
                    try:
                        with open(filepath.absolute_path, 'r', encoding='utf-8') as handle:
                            text = handle.read()
                    except UnicodeDecodeError:
                        #safeprint.safeprint(filepath.absolute_path)
                        #traceback.print_exc()
                        continue
                except Exception:
                    safeprint.safeprint(filepath.absolute_path)
                    traceback.print_exc()
                    continue

                content_args['text'] = text
                content_args['line_numbers'] = True
                results = search(**content_args)
                results = list(results)
                if not results:
                    continue

                yield filepath.absolute_path
                yield from results
                yield ''