def message_console(message, sub_msg='', c_pat=">> ", color=_f.beige, c_pat_color=_f.beige, time_delay=0, end=_f.end + '\n'): """ Write some message in console """ time.sleep(time_delay) c_pat_color = '' if not color else c_pat_color print(_f.paint(c_pat, c_pat_color, color) + _f.paint(str(message), color, ''), str(sub_msg), end=end)
def rename(old, new, public=False, branch_view=3, fl=_fl): """ Rename exist file/ folder by path """ success = False if not _catch_exception(old): item0, item1 = _init(old, fl=fl), _init(new, fl=fl) # print(str(item1)) if not item0.exist: success, new = None, '' else: try: new = op.join(item0.dir, str(item1.content)) if item1.kind in [ "string", "number" ] else new new += ('' if new.count('.') > 0 else '.' + item0.extension) if item0.type == "file" else '' os.rename(old, new) success = True except Exception as e: print("[RN]", _f.paint(e, _f.red), [old, new]) _note.result(old, success, _mode(), new, lambda x: sp_path(x, branch_view), init=[item0.sign, True]) if public else None return new if success else success
def parameters(*args, marker=_obj.get("element"), color=_f.beige, general_color='', end='\n'): """ Write list of parameters in console """ color = general_color if general_color else color if isinstance(args[0], dict): for key in dict(args[0]).keys(): print(general_color + marker, key + ":", _f.paint(args[0].get(key), color), end=end) else: for x in args: print(marker, _f.paint(x, color), end=end) print() if end.count('\n') == 0 else None
def _preparing(directory): """ Get, colorize and block items in path directory """ _set_time(0) _exc, _usd = [_ind.get(x, fl=_fl) for x in [_ind.default_exc, _ind.default_used]] # TODO: set/unset track sort_manager = False if is_dir_clear: if not op.exists(directory): i = 0 while i < 3 and not op.exists(directory): directory = op.split(directory)[0] i += 1 directory = "F:\Work\CODE\Projects\SortManager" if not op.exists(directory) else directory _set_time(1) _note.result(directory, None, "navigator", '', lambda x: _to_gp(x), end=' ', fl=_fl), _note.waiting(end=' ') dir_ = _hierarchy(directory, fl=_fl) # _dir = sort.file_order(this_dir) # TODO: ValueError: too many values to unpack (expected 2) dir_.insert(0, _init(op.split(directory)[0], fl=_fl)) else: sort_manager = True if r"F:\Work\CODE\Projects\SortManager\Sorted\System" in directory else False dir_ = [_init(x, fl=_fl) for x in directory] labels = ["🔝 toParent"] * is_dir_clear for i, x in enumerate(dir_): # Colorize if i != 0 or not is_dir_clear: if x.type == "folder": if _type_dir: if sort_manager: item = _f.paint(_dirs[x.name][2] + ' ' + x.name, _dirs[x.name][0]) labels.append(item if _color else _f.paint(item, _f.bold, total=True)) else: item = _f.paint(x.get_content_type(False) + ' ' + x.name, _f.bold) labels.append(item if _color else _f.paint(item, _f.bold, total=True)) else: labels.append(_f.paint(x.sign + ' ' + x.name, _f.bold)) else: color = str(_dirs[_fp.get(x.property, ["Unassigned"])[0]][0]) * _color labels.append(color + x.sign + _f.end + ' ' + x.name) """ Indexing items """ labels = _ind.files(labels, dir_, _usd, _f.grey)[0] labels, _exc = _ind.files(labels, dir_, _exc, _f.red) # TODO: ?+ labels = _ind.files(labels, dir_clear, invalid_ways, _f.red2) _set_time(1) return dir_, labels, _exc
def __notify(step): if step == 0: _note.status(tag=MODE, color=navi_color, pattern='.') if it == 0 else print() if is_dir_clear: _note.result(directory, None, "cur_dir", '', _to_gp, general_c=navi_color, init=[True, ''], fl=fl), _set_header(None) if _header else None _note.message_console("Select %s location: " % _f.paint(mod, navi_color + _f.underline, navi_color), '', c_pat='', color=navi_color, end='') else: _note.result(_obj.get("folder"), True, "cur_dir", 'Choice', _to_gp, general_c=navi_color, init=['', ''], end=' ', fl=fl), _note.waiting(end=' ') elif step == 1: [print("{} {}".format(_f.paint(_dpw(i, str, 2)[0] + '.', navi_color), x)) for i, x in enumerate(cur_labels)] else: if flag: _note.result(cur_dir[k].content, None, MODE, decore=_to_gp, fl=fl) elif flag is None: None if correct else _note.result(fin, False, MODE, init=False, fl=fl) else: _note.parameters({"Iterations": it, "Final Path": directory}, color=navi_color + _f.bold + _f.underline, end=' ') None if not shutdown else _note.process(MODE, False, color=_f.bg(navi_color), fl=_fl) None if not shutdown else _note.status('.', '.', color=navi_color)
def move(source, destination, public=False, branch_view=3, item_color=_f.blue, folder_color=_f.blue2, ignore_errors=False, mod="move", exc='', fl=_fl): """ Move file/folder to any destination by pathways """ success = False if not _catch_exception(source, exc, fl=fl) and not _catch_exception( destination, exc, fl=fl): _src, _dst = _init(source, fl=fl), _init(destination, fl=fl) create(_dst.content) if not _dst.exist and _src.exist else None # input(src) if not _src.exist: success, destination = None, '' else: new_source = _is_dup(source, destination, fl=fl) if new_source: source = rename(source, new_source, branch_view=1) item_color = _f.yellow if source: try: os.chdir(destination) shutil.move( source, destination) if mod == "move" else shutil.copy2( source, destination) success = True except Exception as e: print(["MV"], _f.paint( e, _f.red)) if not ignore_errors else None else: source = _src.content destination = new_source _note.result(source, success, _mode(), destination, lambda x: sp_path(x, branch_view), i_true=item_color, s_true=folder_color, init=[_src.sign, True]) if public else None return success
def files(out_list, check_list, indexed_list, color=_font.grey): """ Index items from <check_list> by <indexed_list> and return it in <out_list> with <color>""" index_list, special = [], [] if check_list: if not isinstance(check_list[0], str): check_list = [x.content for x in check_list] for indexed_path in indexed_list: if indexed_path in check_list: index_list.append(list(check_list).index(indexed_path)) special.append(indexed_path) return [ _font.paint(x, color, total=True) if i in index_list else x for i, x in enumerate(out_list) ], special
def create(path, _content="", _public=False): item = _init(path, fl=fl) success = False if item.kind == "path" and not item.exist: if item.type in ["folder", "ambiguous"]: try: os.makedirs(path) success = True except Exception as _e: print(_font.paint(_e, _font.red)) elif item.type == "file": if not os.path.exists(item.dir): create(item.dir) with codecs.open(path, "w", "utf-8") as my_file: my_file.write(_content) success = True else: success = None _r(path, success, "create") if _public else None return success
def create(path, content="", public=False): """ Create new file/folder by path """ item = _init(path, fl=_fl) success = False if item.kind == "path" and not item.exist: if item.type in ["folder", "ambiguous"]: try: os.makedirs(path) success = True except Exception as e: print(_f.paint(e, _f.red)) elif item.type == "file": if not os.path.exists(item.dir): create(item.dir) with codecs.open(path, "w", "utf-8") as my_file: my_file.write(content) success = True else: success = None _note.result(path, success, _mode()) if public else None return success
def _col_obj(val, colors, sign): """ Colorize item """ return _f.paint( str(sign + ' ' * (len(sign) > 0)) + str(decore(val)), colors[flag], c_end)
def _col_sign(name, color): """ Colorize symbol """ return _f.paint(_obj.get(name), _f.enhance(color))
def process(mode, flag, color=_f.beige, pat='.', fl=_fl): """ Write step of process in console """ color = color + _f.black if color in _f.backs else color res = ["finishing", "starting", "in process"] print("{} {}{}".format(_f.paint(mode.capitalize(), color), res[_init(flag, fl=fl).property], pat * 7))
def __colorize_val(x): return _f.paint(x, _f.grey2)
def _get_correct_input(directory, fin, cur_dir, mod, _exc): """ Convert user_input to command, tags and values """ # [False, True, None] == [Exit, GoNext, Refresh] || "cmd": (flag, value), || "cmd": func(*args), def __offset(x, check_list): print() if x in check_list else None def __set(value): return set(value) if isinstance(value, list) else {value} _set_time(0) """ Get cmd, tag, val """ cmd, tag, val = _console(fin) __offset(cmd, ["rename", "del", "move", "copy", "open", "get", "make"]) """ Init built-in vars """ global correct temp0, temp1 = False, False cmd = "sort" if mod == "sort" and cmd in ['', "sort"] and not val else cmd correct = True if fin == "rf" or cmd and cmd != "ref" else False # input([cmd, tag, val]) out = { "help": (None, ''), "undo": (None, ''), "fin": (False, "exit"), "": (False, ''), "make": (None, ''), "rename": (None, ''), "del": (False, []), "move": (False, []), "copy": (False, []), "sort": (False, "single"), "open": (None, ''), "ref": (None, ''), "type": (None, "switch_tp"), "color": (None, "switch_cl"), "header": (None, "switch_hd"), "ind": (None, ''), "fluency": (None, ''), "get": (None, ''), "cd": (True, 0), } do = { "help": (lambda x: input(">> ..")), "make": (lambda x: _fm.create(op.join(directory, x), '', True)), "del": (lambda x: _fm.delete(x, True)), "rename": (lambda x: _fm.rename(x, input("Enter new name: "), True, 2)), "open": (lambda x: _fm.open(x, True)), "get": (lambda x: _subs(x, temp0, temp1, public=True, fl=_fl)), "ind": (lambda x: _ind.append(op.join(_ind.dir_tmp, str(temp0)), x, public=True)), "fluency": (lambda x: _set_fluency(x)), } """ Init cmd, tag, val """ if cmd in out.keys(): if cmd in ["move", "copy"]: # TODO: if all are exc pathways, pathways_c, moved = [cur_dir[x] for x in val], [cur_dir[x].content for x in val], [] msg = [_f.paint("Selected:", _f.yellow) + _f.paint('(' + cmd + ')', _f.grey)] + [_obj.get("element") + ' ' + p for p in _ind.files(pathways_c, pathways_c, _exc, _f.red)[0]] [print(x) for x in msg] inter = __set(pathways[0].family) for i in range(1, len(pathways)): inter &= __set(pathways[i].family) for sup_dst in list(inter): if sup_dst in _dirs: _dst = _dirs[sup_dst] dst_name_colored = _f.paint(_init(_dst[1], fl=_fl).sign + ' ' + _dst[1], _dst[0], '') if _start("Is {0}{2}{1} the {0}destination{1}".format(_f.bold, _f.end, dst_name_colored), reverse=True, color=''): r_dst = _dst[1] break else: r_dst, msg = run([x[1] for x in _dirs.values()], 1, _f.yellow, cmd, False) print() for item in pathways: moved.append(op.join(r_dst, item.name)) _fm.move(item.content, r_dst, public=True, exc=_exc, mod=cmd) out.update({cmd: (False, moved)}) else: # TODO: optimize for not common function; help by key_work cmd: fl -> ++/ -- ? """ INIT <val> """ if cmd in ["fluency"]: val = [val] elif not val: val = [directory] else: val = [(cur_dir[x].content if isinstance(x, int) else x) for x in (val if isinstance(val, list) else [val])] """ INIT <cmd> """ """ "type", "color", "fluency", "header" """ _set_header(cmd, val) """ "ind" """ temp0 = _ind.used_tmp if cmd == "ind" and tag == "usd" else (_ind.exc_tmp if cmd == "ind" and tag == "exc" else temp0) """ "get" """ temp0, temp1 = (True, False) if cmd == "get" and tag == "dir" else ((False, True) if cmd == "get" and tag == "file" else (temp0, temp1)) """ "del" """ out.update({cmd: (False, [x for x in val if x != directory])}) if cmd == "del" else None """ "sort -rec" """ out.update({cmd: (False, "recursive")}) if cmd == "sort" and tag == "rec" else None """ "del - odd" """ if cmd == "del" and tag == "odd": val = [x.content for x in cur_dir if x.property == "~/empty"] if not val: _note.message_console("Nothing to delete ¯\_(ツ)_/¯ (or try to down fluency)", c_pat='', color=_f.grey) cmd, tag, val = "ref", '', '' """ Do by <cmd> """ [do.get(cmd)(x) for x in val] if cmd in do.keys() else None elif 0 <= val < len(cur_dir): if _fm._catch_exception(cur_dir[val].content, _exc, _f.grey): cmd = "ref" elif cur_dir[val].type == "file": cmd = "open" do.get("open")([directory] if not val else cur_dir[val].content) else: cmd = "cd" out.update({cmd: (True, val)}) else: cmd = "ref" __offset(cmd, ["del", "move", "copy"]), _set_time(1) return out.get(cmd)