Beispiel #1
0
 def edit_file(self, file=None):
     """Calls execute_file with the current file and app='editor'"""
     if file is None:
         file = self.env.cf
     elif isinstance(file, str):
         file = File(os.path.expanduser(file))
     if file is None:
         return
     self.execute_file(file, app='editor')
Beispiel #2
0
 def execute(self):
     from ranger.fsobject import File
     line = parse(self.line)
     if not line.rest(1):
         return self.fm.notify('Syntax: rename <newname>', bad=True)
     self.fm.rename(self.fm.env.cf, line.rest(1))
     f = File(line.rest(1))
     self.fm.env.cwd.pointed_obj = f
     self.fm.env.cf = f
Beispiel #3
0
    def execute(self):
        import sys
        import tempfile
        from ranger.fsobject.file import File
        from ranger.ext.shell_escape import shell_escape as esc
        py3 = sys.version > "3"

        # Create and edit the file list
        filenames = [f.basename for f in self.fm.env.get_selection()]
        listfile = tempfile.NamedTemporaryFile()

        if py3:
            listfile.write("\n".join(filenames).encode("utf-8"))
        else:
            listfile.write("\n".join(filenames))
        listfile.flush()
        self.fm.execute_file([File(listfile.name)], app='editor')
        listfile.seek(0)
        if py3:
            new_filenames = listfile.read().decode("utf-8").split("\n")
        else:
            new_filenames = listfile.read().split("\n")
        listfile.close()
        if all(a == b for a, b in zip(filenames, new_filenames)):
            self.fm.notify("No renaming to be done!")
            return

        # Generate and execute script
        cmdfile = tempfile.NamedTemporaryFile()
        cmdfile.write(
            b"# This file will be executed when you close the editor.\n")
        cmdfile.write(
            b"# Please double-check everything, clear the file to abort.\n")
        if py3:
            cmdfile.write("\n".join("mv -vi " + esc(old) + " " + esc(new) \
             for old, new in zip(filenames, new_filenames) \
             if old != new).encode("utf-8"))
        else:
            cmdfile.write("\n".join("mv -vi " + esc(old) + " " + esc(new) \
             for old, new in zip(filenames, new_filenames) if old != new))
        cmdfile.flush()
        self.fm.execute_file([File(cmdfile.name)], app='editor')
        self.fm.run(['/bin/sh', cmdfile.name], flags='w')
        cmdfile.close()
Beispiel #4
0
 def execute(self):
     from ranger.fsobject import File
     from os.path import exists
     try:
         f = open(self.fm.confpath(self.copy_buffer_filename), 'r')
     except:
         return self.fm.notify("Cannot open file %s" % fname, bad=True)
     self.fm.env.copy = set(File(g) \
      for g in f.read().split("\n") if exists(g))
     f.close()
     self.fm.ui.redraw_main_column()
Beispiel #5
0
    def execute(self):
        from ranger.fsobject import File
        from os import access

        # yes, this is pathetic
        s = str(self.fm.env.cf)
        s1 = s.replace('-', '_')
        s2 = s.replace('_', '-')
        new_name = ''.join(
            [b if a != b else c for (a, b, c) in zip(s, s1, s2)])

        if access(new_name, os.F_OK):
            return

        self.fm.rename(self.fm.env.cf, new_name)
        f = File(new_name)
        self.fm.env.cwd.pointed_obj = f
        self.fm.env.cf = f
Beispiel #6
0
    def execute(self):
        from ranger.fsobject import File
        from os import access

        new_name = self.rest(1)

        if not new_name:
            return self.fm.notify('Syntax: rename <newname>', bad=True)

        if new_name == self.fm.thisfile.basename:
            return

        if access(new_name, os.F_OK):
            return self.fm.notify("Can't rename: file already exists!", bad=True)

        self.fm.rename(self.fm.thisfile, new_name)
        f = File(new_name)
        self.fm.thisdir.pointed_obj = f
        self.fm.thisfile = f
Beispiel #7
0
    def load_bit_by_bit(self):
        """
		Returns a generator which load a part of the directory
		in each iteration.
		"""

        self.loading = True
        self.load_if_outdated()

        try:
            if self.runnable:
                yield
                mypath = self.path

                self.mount_path = mount_path(mypath)

                hidden_filter = not self.settings.show_hidden \
                  and self.settings.hidden_filter
                filenames = [mypath + (mypath == '/' and fname or '/' + fname)\
                  for fname in os.listdir(mypath) if accept_file(
                   fname, mypath, hidden_filter, self.filter)]
                yield

                self.load_content_mtime = os.stat(mypath).st_mtime

                marked_paths = [obj.path for obj in self.marked_items]

                files = []
                disk_usage = 0
                for name in filenames:
                    try:
                        file_lstat = os_lstat(name)
                        if file_lstat.st_mode & 0o170000 == 0o120000:
                            file_stat = os_stat(name)
                        else:
                            file_stat = file_lstat
                        stats = (file_stat, file_lstat)
                        is_a_dir = file_stat.st_mode & 0o170000 == 0o040000
                    except:
                        stats = None
                        is_a_dir = False
                    if is_a_dir:
                        try:
                            item = self.fm.env.get_directory(name)
                            item.load_if_outdated()
                        except:
                            item = Directory(name,
                                             preload=stats,
                                             path_is_abs=True)
                            item.load()
                    else:
                        item = File(name, preload=stats, path_is_abs=True)
                        item.load()
                        disk_usage += item.size
                    files.append(item)
                    yield
                self.disk_usage = disk_usage

                self.filenames = filenames
                self.files = files

                self._clear_marked_items()
                for item in self.files:
                    if item.path in marked_paths:
                        item._mark(True)
                        self.marked_items.append(item)
                    else:
                        item._mark(False)

                self.sort()

                if files:
                    if self.pointed_obj is not None:
                        self.sync_index()
                    else:
                        self.move(to=0)
            else:
                self.filenames = None
                self.files = None

            self.cycle_list = None
            self.content_loaded = True
            self.last_update_time = time()
            self.correct_pointer()

        finally:
            self.loading = False
Beispiel #8
0
def raw_load_content(self):
    """
	The method which is used in a Directory object to load stuff.
	Keep this up to date!
	"""

    from os.path import join, isdir, basename
    from os import listdir
    import ranger.ext.mount_path

    self.loading = True
    self.load_if_outdated()

    try:
        if self.exists and self.runnable:
            # 0.003s:
            self.mount_path = ranger.ext.mount_path.mount_path(self.path)

            # 0.1s:
            filenames = []
            for fname in listdir(self.path):
                if not self.settings.show_hidden:
                    hfilter = self.settings.hidden_filter
                    if hfilter:
                        if isinstance(hfilter, str) and hfilter in fname:
                            continue
                        if hasattr(hfilter, 'search') and \
                         hfilter.search(fname):
                            continue
                if isinstance(self.filter, str) and self.filter \
                  and self.filter not in fname:
                    continue
                filenames.append(join(self.path, fname))
            # ---

            self.load_content_mtime = os.stat(self.path).st_mtime

            marked_paths = [obj.path for obj in self.marked_items]

            # 2.85s:
            files = []
            for name in filenames:
                if isdir(name):
                    try:
                        item = self.fm.env.get_directory(name)
                    except:
                        item = Directory(name)
                else:
                    item = File(name)
                item.load_if_outdated()
                files.append(item)

            # 0.2s
            self.disk_usage = sum(f.size for f in files if f.is_file)

            self.scroll_offset = 0
            self.filenames = filenames
            self.files = files

            self._clear_marked_items()
            for item in self.files:
                if item.path in marked_paths:
                    self.mark_item(item, True)
                else:
                    self.mark_item(item, False)

            self.sort()

            if len(self.files) > 0:
                if self.pointed_obj is not None:
                    self.sync_index()
                else:
                    self.move(to=0)
        else:
            self.filenames = None
            self.files = None

        self.cycle_list = None
        self.content_loaded = True
        self.determine_infostring()
        self.correct_pointer()

    finally:
        self.loading = False
Beispiel #9
0
def main():
    """initialize objects and run the filemanager"""
    import locale
    import os.path
    import ranger
    from ranger.core.shared import (EnvironmentAware, FileManagerAware,
                                    SettingsAware)
    from ranger.core.fm import FM

    try:
        locale.setlocale(locale.LC_ALL, '')
    except:
        print("Warning: Unable to set locale.  Expect encoding problems.")

    if not 'SHELL' in os.environ:
        os.environ['SHELL'] = 'bash'

    ranger.arg = arg = parse_arguments()
    if arg.copy_config is not None:
        fm = FM()
        fm.copy_config_files(arg.copy_config)
        return 1 if arg.fail_unless_cd else 0

    SettingsAware._setup(clean=arg.clean)

    targets = arg.targets or ['.']
    target = targets[0]
    if arg.targets:
        if target.startswith('file://'):
            target = target[7:]
        if not os.access(target, os.F_OK):
            print("File or directory doesn't exist: %s" % target)
            return 1
        elif os.path.isfile(target):

            def print_function(string):
                print(string)

            from ranger.core.runner import Runner
            from ranger.fsobject import File
            runner = Runner(logfunc=print_function)
            load_apps(runner, arg.clean)
            runner(files=[File(target)], mode=arg.mode, flags=arg.flags)
            return 1 if arg.fail_unless_cd else 0

    crash_traceback = None
    try:
        # Initialize objects
        from ranger.core.environment import Environment
        fm = FM()
        FileManagerAware.fm = fm
        EnvironmentAware.env = Environment(target)
        fm.tabs = dict((n+1, os.path.abspath(path)) for n, path \
          in enumerate(targets[:9]))
        load_settings(fm, arg.clean)
        if fm.env.username == 'root':
            fm.settings.preview_files = False
            fm.settings.use_preview_script = False
        if not arg.debug:
            from ranger.ext import curses_interrupt_handler
            curses_interrupt_handler.install_interrupt_handler()

        # Run the file manager
        fm.initialize()
        fm.ui.initialize()
        fm.loop()
    except Exception:
        import traceback
        crash_traceback = traceback.format_exc()
    except SystemExit as error:
        return error.args[0]
    finally:
        if crash_traceback:
            filepath = fm.env.cf.path if fm.env.cf else "None"
        try:
            fm.ui.destroy()
        except (AttributeError, NameError):
            pass
        if crash_traceback:
            print("Ranger version: %s, executed with python %s" %
                  (ranger.__version__, sys.version.split()[0]))
            print("Locale: %s" % '.'.join(str(s) for s in locale.getlocale()))
            print("Current file: %s" % filepath)
            print(crash_traceback)
            print("Ranger crashed.  " \
             "Please report this traceback at:")
            print("http://savannah.nongnu.org/bugs/?group=ranger&func=additem")
            return 1
        return 0