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 get(index_file, mode="indexed", public=False, fl=_fl): """ Get indexed items from <data_path> """ data_links = False, [] try: _data = _init(index_file, fl=fl) os.chdir(_data.dir) data_links = _from_file(index_file).split('\r\n')[:-1:] except Exception as e: print(e) _mc(os.path.split(index_file)[1], "reading...") if public else None for link in data_links: _mc(link, 'was %s.' % mode, _init(link, fl=fl).sign, _font.grey) if public else None return data_links
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 close(path, public=False, fl=_fl): """ Close selected file/folder by path """ item = _init(path, fl=fl) success = False if item.type == "file": os.system("TASKKILL /F /IM %s" % _files_p.get(item.property)) success = True _note.result(path, success, _mode()) if public else None return success
def clean(index_file, public=False, fl=_fl): """ Clean <data_path> with indexed items """ success = False try: _data = _init(index_file, fl=fl) os.chdir(_data.dir) _to_file(index_file, '') success = True except Exception as e: print(e) _r(index_file, success, "clean") if public else None
def _set_header(cmd, val=None): def __colorize_val(x): return _f.paint(x, _f.grey2) if cmd in ["type", "color", "fluency", "header", None]: val = [0] if val is None or isinstance(val[0], str) else val not_gen = cmd is not None arr = '⇛ '* not_gen dict_header = { "header": ('🠶', " Header: %s%s" % (arr, __colorize_val(_init(not_gen ^ _header, fl=_fl).switch.upper()))), "type": ('📌', " Type: %s%s" % (arr, __colorize_val(_init(not_gen ^ _type_dir, fl=_fl).switch.upper()))), "color": ('👀', " Color: %s%s" % (arr, __colorize_val(_init(not_gen ^ _color, fl=_fl).switch.upper()))), "fluency": ('🚀', " Fluency: %s%s " % (arr, __colorize_val(_fl + val[0] * not_gen))), } if cmd is None: [_note.message_console(dict_header[x][1], c_pat=dict_header[x][0], color=_f.grey, c_pat_color=_f.grey2, end=_f.end + ' ') for x in ["type", "color", "header", "fluency"]] print() else: _note.message_console(dict_header[cmd][1], c_pat=dict_header[cmd][0], color=_f.grey, c_pat_color=_f.grey)
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 subs(path, folders=True, files=False, public=False, recursive=True, color=_beige, fl=_fl): def unite(main_dir, sub_list): return list(map(lambda x: os.path.join(main_dir, x), sub_list)) _s(pattern='.', color=color) if public else None dst, level = _init(path, fl=fl), 0 root = os.path.split(dst.content)[0] if dst.kind == 'file' else dst.content if root: result_files, result_folders = [], [root] if folders else [] for rootName, folderNames, fileNames in os.walk(root): if not recursive and level > 0: break if folders and recursive: result_folders.extend(unite(rootName, folderNames)) if files: result_files.extend(unite(rootName, fileNames)) level += 1 if public: [ print(_yellow, _init(x, fl=fl).sign, x, _end) for x in result_folders ] [print(_blue, _init(x, fl=fl).sign, x, _end) for x in result_files] _s(tag='.', pattern='.', color=color) if public else None if files and folders: return result_folders, result_files elif files: return [], result_files elif folders: return result_folders, [] else: return [], []
def duplicate(source, destination, fl=_fl): src = _init(source, fl=fl) if op.exists(op.join(destination, src.name)): # TODO: check (1)(2) ...; folders merger or inc index by input old, ext = sp_file(src.name) ext, res = ext if not ext else '.' + ext, re.findall("\d+", old) if res and str(old[-1:]).isdigit(): digit = int(res[-1]) + 1 new = _rld(old, digit - 1) else: digit = 1 new = old + "_%d" % digit while op.exists(op.join(destination, new + ext)) or op.exists(op.join(src.dir, new + ext)): new = _rld(new, digit) digit += 1 return op.join(src.dir, new + ext) else: return False
def delete(path, public=False, success=False, fl=_fl): """ Delete exist file/ folder by path """ if not _catch_exception(path): item = _init(path, fl=fl) if not item.exist: success = None else: if item.type == "file": os.remove(path) success = True elif item.type == "folder": shutil.rmtree(path, True) success = True else: pass _note.result(path, success, _mode(), init=[item.sign, True ]) if public else None return success
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 _get_sign(val, ind): """ Init sign """ return _init(val, fl=fl).sign if init[ind] is True else init[ind]
def result(item, flag, mode, sub='', decore=lambda x: x, init=None, general_c='', i_false=_f.red, i_true=_f.blue, i_none=_f.yellow, s_false=_f.red, s_true=_f.blue2, s_none=_f.yellow, end='\n', fl=_fl): """ Write result of process in console """ def _col_sign(name, color): """ Colorize symbol """ return _f.paint(_obj.get(name), _f.enhance(color)) def _col_obj(val, colors, sign): """ Colorize item """ return _f.paint( str(sign + ' ' * (len(sign) > 0)) + str(decore(val)), colors[flag], c_end) def _get_sign(val, ind): """ Init sign """ return _init(val, fl=fl).sign if init[ind] is True else init[ind] """ Download signs from sample """ flag, sign = _init(flag, fl=fl).property, [] for n, c in zip(["arrow", "arrow_r", "arrow_broken", "flag", "flag"], [i_true, i_true, i_false, i_true, i_none]): sign.append(_col_sign(n, c)) """ <init> init cases """ if init is None: init = (True, True) elif init is False: init = ('', '') """ <sub> init cases """ if sub or sub == 0: sub += ' ' else: init = (init[0], '') s_false, s_true, s_none = '', '', '' """ <general_c> init cases """ if general_c: c_items, c_subs, c_end = ['', '', ''], ['', '', ''], '' else: c_items, c_subs, c_end = [i_false, i_true, i_none], [s_false, s_true, s_none], _f.end """ Colorize items """ item = _col_obj(item, c_items, _get_sign(item, 0)) sub = _col_obj(sub, c_subs, _get_sign(sub, 1)) notification_dict = { "create": [ "{1}{0} already exists!", "{1}Created: {0}", "{1}Error occurred: {0}" ], "rename": [ "{0} " + sign[2] + " {1}", "{0} " + sign[0] + " {1}", "Not found: {0}" ], "delete": ["{1}Deleting {0} failed.", "{1}Deleted: {0}", "Not found: {0}"], "clean": ["{1}Cleaning {0} failed.", "{1}Cleaned: {0}", "Not found: {0}"], "sort": [ "{1}Sorting in {0} failed.", "🎩 {1}Sorted: {0} files ", "Sort directory: {0}" ], "move": [ "{1} " + sign[2] + " {0}", "{1} " + sign[1] + " {0}", "Not found: {0} {1}" ], "index": [sign[2] + " : {0}", sign[3] + " : {0}", sign[4] + " : {0}"], "open": ["Failed {1}opening: {0}", "{1}Opened: {0}", "{1}Opening... {0}"], "navigator": ["Incorrect {1}: {0}", "Current directory: {0}", "{1}➥ {0}"], "read": [ "Input file {0} not found", "Reading from: {0}", "{1}Error occurred: {0}" ], "write": [ "Output file {0} not found", "Writing to: {0}", "{1}Error occurred: {0}" ], "cur_dir": ["{1}{0} not found", "{1}Directory: {0}", "{1}{0}"] } print(general_c + notification_dict[mode][flag].format(item, sub) + c_end, end=end)
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 _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)