Ejemplo n.º 1
0
 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")
Ejemplo n.º 2
0
 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)
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
 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()
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
0
 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)
Ejemplo n.º 8
0
 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)
Ejemplo n.º 9
0
 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()
Ejemplo n.º 10
0
 def reload(self):
     try:
         os.chdir(self.path)
         self.diskread()
         self.sort()
     except Exception as e:
         message.exception(e)
         self.chdir(Workspace.default_path)
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
 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)
Ejemplo n.º 13
0
 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)
Ejemplo n.º 14
0
 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)
Ejemplo n.º 15
0
 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)
Ejemplo n.º 16
0
 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)
Ejemplo n.º 17
0
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)
Ejemplo n.º 18
0
 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()
Ejemplo n.º 19
0
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)
Ejemplo n.º 20
0
 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()
Ejemplo n.º 21
0
 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")
Ejemplo n.º 22
0
    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)
Ejemplo n.º 23
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)
Ejemplo n.º 24
0
 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)
Ejemplo n.º 25
0
 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")
Ejemplo n.º 26
0
 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()
Ejemplo n.º 27
0
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()
Ejemplo n.º 28
0
 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()
Ejemplo n.º 29
0
 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()
Ejemplo n.º 30
0
 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()