def delete_dir(self, directory): try: os.rmdir(directory) except Exception as e: if e[0] != errno.ENOTEMPTY: message.exception(e) raise FilectrlCancel("Exception occurred while directory deleting")
def main(self): try: unicode self.dst = self.dst.encode() except: pass try: import tarfile mode = self.tarmodes[self.tarmode] tar = tarfile.open(self.dst, "w|"+mode) except Exception as e: return message.exception(e) try: goal = sum(_get_file_length(self.src)) elapse = 1 for path in self.src: for f in self.generate(path): arcname = f.replace(os.path.commonprefix([f, self.src_dirname]), "") msg = "({0}/{1}): {2}".format(elapse, goal, arcname) self.update("Adding{0}".format(msg)) self.add_file(tar, f, arcname) self.notify("Added{0}".format(msg)) elapse += 1 finally: tar.close() try: if len(self.src) == 1: lst = os.lstat(self.src[0]) os.utime(self.dst, (lst.st_mtime, lst.st_mtime)) except Exception as e: message.exception(e)
def main(self): self.update("Reading...") try: mode = self.get_mode() import zipfile myzip = zipfile.ZipFile(self.dst, mode, compression=zipfile.ZIP_DEFLATED) except Exception as e: return message.exception(e) try: goal = sum(_get_file_length(self.src)) elapse = 1 for path in self.src: for f in self.generate(path): arcname = f.replace(os.path.commonprefix([f, self.src_dirname]), "") msg = "({0}/{1}): {2}".format(elapse, goal, arcname) self.update("Adding{0}".format(msg)) self.write_file(myzip, f, arcname) self.notify("Added{0}".format(msg)) elapse += 1 finally: myzip.close() if len(self.src) == 1: try: lst = os.lstat(self.src[0]) os.utime(self.dst, (lst.st_mtime, lst.st_mtime)) except Exception as e: message.exception(e)
def _spawn_shell(): """Spawn the shell registered in pyful.process.Process.shell""" shell = process.Process.shell[0] try: process.spawn(shell, shell) except Exception as e: message.exception(e)
def system(self, cmd): if self.background: try: proc = Popen(cmd, shell=True, executable=self.shell[0], close_fds=True, preexec_fn=os.setsid, stdout=PIPE, stderr=PIPE) message.puts("Spawn: {0} ({1})".format(cmd.strip(), proc.pid)) ProcessNotify(proc, cmd).start() except Exception as e: message.exception(e) else: try: widget.end_curses() os.system("clear") proc = Popen(cmd, shell=True, executable=self.shell[0], close_fds=True, preexec_fn=os.setsid) proc.wait() if not self.quick: util.wait_restore() message.puts("Spawn: {0} ({1})".format(cmd.strip(), proc.pid)) except KeyboardInterrupt as e: message.error("KeyboardInterrupt: {0}".format(cmd)) except Exception as e: message.exception(e) finally: widget.start_curses()
def link(src, dst): try: if os.path.isdir(dst): dst = os.path.join(dst, util.unix_basename(src)) os.link(src, dst) message.puts("Created hard links: {0} -> {1}".format(src, dst)) except Exception as e: message.exception(e)
def delete_file(self, f): try: os.remove(f) except Exception as e: message.exception(e) raise FilectrlCancel("Exception occurred while deleting") if not self.active: raise FilectrlCancel(self.title)
def write_file(self, myzip, source, arcname): try: myzip.write(source, os.path.join(self.wrap, arcname)) except Exception as e: message.exception(e) raise FilectrlCancel("Exception occurred while `zip'") if not self.active: raise FilectrlCancel(self.title)
def mvfocus(self): try: os.chdir(self.dir.path) except Exception as e: message.exception(e) self.dir.chdir(self.default_path) if self.layout == "Magnifier": self.magnifier()
def reload(self): try: os.chdir(self.path) self.diskread() self.sort() except Exception as e: message.exception(e) self.chdir(Workspace.default_path)
def _reload_rcfile(): """Reload Pyful.environs["RCFILE"]""" try: path = Pyful.environs["RCFILE"] util.loadfile(path) message.puts("Reloaded: {0}".format(path)) except Exception as e: message.exception(e)
def add_file(self, tar, source, arcname): try: tar.add(source, os.path.join(self.wrap, arcname), recursive=False) except Exception as e: message.exception(e) raise FilectrlCancel("Exception occurred while `tar'") if not self.active: raise FilectrlCancel(self.title)
def edit(self): grepoutputs = self.cursor_entry().text.split(":") fname = grepoutputs[0] lnum = grepoutputs[1] try: process.spawn("{0} +{1} {2}".format(Pyful.environs["EDITOR"], lnum, fname)) except Exception as e: message.exception(e)
def run(self): with self.lock: try: self.main() message.puts("Finished: {0}".format(self.title)) except FilectrlCancel as e: message.exception(e) finally: Filectrl.threads.remove(self)
def execute(self, word, action): import webbrowser if self.engine == "Google": word = word.replace(" ", "+") search = "http://www.google.com/search?&q={0}".format(word) else: pass try: webbrowser.open(search, new=2) except Exception as e: message.exception(e)
def copydir(self, pair): try: os.makedirs(pair[1]) except OSError as e: if e.errno != errno.EEXIST: message.exception(e) sst, dst = pair try: os.utime(dst, (sst.st_atime, sst.st_mtime)) os.chmod(dst, stat.S_IMODE(sst.st_mode)) except Exception as e: message.exception(e)
def _open_at_system(): """Open the file under cursor at the file association of system. * Linux distributions -> "xdg-open" * Cygwin -> "cygstart" """ try: if sys.platform == "cygwin": process.spawn("cygstart %f %&") else: process.spawn("xdg-open %f %&") except Exception as e: message.exception(e)
def open_listfile(self, path): self.list_title = "File:({0})".format(path) self.list = [] try: with open(path, "r") as f: for line in f: line = line.strip(os.linesep) if os.path.exists(line): line = re.sub("{0}?{1}".format(self.path, os.sep), "", line) self.list.append(line) except Exception as e: message.exception(e) self.reload()
def rename(src, dst): if os.path.exists(dst) and os.path.samefile(src, dst): return if os.path.exists(dst): ret = message.confirm( "{0}; Override? {{{1} -> {2}}}".format(os.strerror(errno.EEXIST), src, dst), ["Yes", "No", "Cancel"]) if "Yes" != ret: return try: os.renames(src, dst) message.puts("Renamed: {0} -> {1}".format(src, dst)) except Exception as e: message.exception(e)
def python(self, cmd): cmd = self.parsemacro(cmd) try: widget.end_curses() os.system("clear") exec(cmd) if not self.quick: util.wait_restore() message.puts("Eval: {0}".format(cmd)) except KeyboardInterrupt as e: message.error("KeyboardInterrupt: {0}".format(cmd)) except Exception as e: message.exception(e) finally: widget.start_curses()
def copy(self): try: if not os.path.isdir(util.unix_dirname(self.dst)): os.makedirs(util.unix_dirname(self.dst)) if os.path.isfile(self.dst): if not os.access(self.dst, os.W_OK): os.remove(self.dst) if os.path.islink(self.src): self.copysymlink(self.src, self.dst) else: self.copyfile(self.src, self.dst) shutil.copystat(self.src, self.dst) except Exception as e: message.exception(e) raise FilectrlCancel("Exception occurred while copying")
def chdir(self, path): parpath = util.unix_dirname(self.path) parfile = util.unix_basename(self.path) newpath = util.abspath(util.expanduser(path), self.path) if newpath == self.path: return self.list = None self.list_title = None if self.finder.active: self.finder.finish() self.mark_clear() try: os.chdir(newpath) except Exception as e: return message.exception(e) self.history.update(newpath) self.path = newpath self.diskread() self.sort() if self.path == parpath: self.setcursor(self.get_index(parfile)) else: self.setcursor(0)
def copy_external_attr(self, myzip, path): try: info = myzip.getinfo(path) except Exception as e: return message.exception(e) perm = info.external_attr >> 16 date = list(info.date_time) + [-1, -1, -1] path = util.force_decode(path) abspath = os.path.join(self.dstdir, path) try: if perm: os.chmod(abspath, perm) atime = mtime = time.mktime(date) os.utime(abspath, (atime, mtime)) except Exception as e: message.exception(e)
def main(self): self.update("Reading...") if not os.path.exists(self.dstdir): try: os.makedirs(self.dstdir) except OSError as e: return message.exception(e) for zippath in self.src: self.extract(zippath)
def move(self): try: if not os.path.isdir(util.unix_dirname(self.dst)): os.makedirs(util.unix_dirname(self.dst)) if os.path.isfile(self.dst): if not os.access(self.dst, os.W_OK): os.remove(self.dst) os.rename(self.src, self.dst) except Exception as e: if errno.EXDEV == e[0]: self.copy() try: os.remove(self.src) except Exception as e: message.exception(e) raise FilectrlCancel("Exception occurred while removing") else: message.exception(e) raise FilectrlCancel("Exception occurred while moving")
def extract(self, zippath): try: import zipfile myzip = zipfile.ZipFile(zippath, "r") except Exception as e: return message.exception(e) try: for info in myzip.infolist(): if not self.active: raise FilectrlCancel(self.title) try: self.extract_file(myzip, info) except Exception as e: message.exception(e) raise FilectrlCancel("Exception occurred while `unzip'") finally: for d in reversed(sorted(self.dirlist)): self.copy_external_attr(myzip, d) self.dirlist[:] = [] myzip.close()
def replace(pattern, repstr): filer = widgets.filer files = filer.dir.get_mark_files() renamed = [pattern.sub(r""+repstr, f) for f in files] msg = [] matched = [] for i in range(0, len(files)): if files[i] != renamed[i]: msg.append("{0} -> {1}".format(files[i], renamed[i])) matched.append((files[i], renamed[i])) if not matched: return message.error("No pattern matched for mark files: {0} ".format(pattern.pattern)) if "Start" != message.confirm("Replace:", ["Start", "Cancel"], msg): return ret = "" for member in matched: src, dst = member if os.path.exists(os.path.join(filer.dir.path, dst)): if ret == "No(all)": continue if ret != "Yes(all)": ret = message.confirm( "{0}; Override? {{{1} -> {2}}}".format(os.strerror(errno.EEXIST), src, dst), ["Yes", "No", "Yes(all)", "No(all)", "Cancel"]) if ret == "Yes" or ret == "Yes(all)": pass elif ret == "No" or ret == "No(all)": continue elif ret is None or ret == "Cancel": break try: os.renames(src, dst) message.puts("Renamed: {0} -> {1}".format(src, dst)) except Exception as e: message.exception(e) break filer.dir.mark_clear()
def loadfile(self, path): try: path = os.path.expanduser(path) with open(path, "r") as f: obj = json.load(f) except Exception as e: if e[0] != errno.ENOENT: message.exception(e) message.error("InformationLoadError: {0}".format(path)) return self.workspaces[:] = [] try: self.cursor = obj.get("FocusWorkspace", 0) data = obj.get("WorkspacesData", []) for i, wmap in enumerate(data): title = wmap.get("title", str(i+1)) ws = Workspace(title) ws.layout = wmap.get("layout", "Tile") ws.cursor = wmap.get("focus", 0) if "dirs" not in wmap: ws.create_dir(os.getenv("HOME")) ws.create_dir(os.getenv("HOME")) self.workspaces.append(ws) continue for dmap in wmap["dirs"]: path = dmap.get("path", os.getenv("HOME")) d = Directory(path, 1, 1, 1, 0) d.sort_kind = dmap.get("sort", "Name[^]") d.cursor = dmap.get("cursor", 0) d.scrolltop = dmap.get("scrolltop", 0) ws.dirs.append(d) self.workspaces.append(ws) except Exception as e: message.exception(e) self.default_init() if not 0 <= self.cursor < len(self.workspaces): self.cursor = 0 self.workspace.refresh()
def extract(self, source): mode = self.tarmodes.get(util.extname(source), "gz") try: import tarfile tar = tarfile.open(source, "r:"+mode) except Exception as e: message.exception(e) raise FilectrlCancel("Exception occurred while `untar'") try: for info in tar.getmembers(): if not self.active: raise FilectrlCancel(self.title) self.update("Extracting: {0}".format(info.name)) tar.extract(info, self.dstdir) self.notify("Extracted: {0}".format(info.name)) if info.isdir(): self.dirlist.append(info) finally: for dinfo in reversed(sorted(self.dirlist, key=lambda a: a.name)): dirpath = os.path.join(self.dstdir, dinfo.name) os.utime(dirpath, (dinfo.mtime, dinfo.mtime)) self.dirlist[:] = [] tar.close()
def _run_vim_replace(self, pattern): filer = widgets.filer patterns = re.split(r"(?<!\\)/", pattern) if len(patterns) > 1: pattern = util.U(patterns[0]) repl = patterns[1] else: pattern = util.U(pattern) repl = "" pattern = re.sub(r"\\/", "/", pattern) repl = re.sub(r"\\/", "/", repl) try: reg = re.compile(pattern) except re.error as e: return message.exception(e) filectrl.replace(reg, repl) filer.workspace.all_reload()