Ejemplo n.º 1
0
    def execute(self, context, args):
        target = FilePath(args[-1], context.cwd)
        try:
            target_is_dir = stat.S_ISDIR(os.stat(target).st_mode)
            target_exists = True
        except OSError as e:
            target_is_dir = False
            target_exists = False

        sources = args[:-1]
        if (not target_is_dir) and len(sources) > 1:
            raise ValueError(_("Can't move multiple items to non-directory"))

        sources_total = len(sources)
        self._status_notify(context, sources_total, 0)

        if target_is_dir:
            for i, source in enumerate(sources):
                target_path = FilePath(unix_basename(source), target)
                shutil.move(FilePath(source, context.cwd), target_path)
                self._status_notify(context, sources_total, i + 1)
        else:
            shutil.move(FilePath(sources[0], context.cwd), target)
            self._status_notify(context, sources_total, 1)

        return []
Ejemplo n.º 2
0
class MvBuiltin(FileOpBuiltin):
    __doc__ = _("""Rename initial arguments to destination.""")

    def __init__(self):
        super(MvBuiltin, self).__init__('mv',
                                        aliases=['move'],
                                        hasstatus=True,
                                        argspec=MultiArgSpec('paths', min=2))

    def execute(self, context, args):
        target = FilePath(args[-1], context.cwd)
        try:
            target_is_dir = stat.S_ISDIR(os.stat(target).st_mode)
            target_exists = True
        except OSError, e:
            target_is_dir = False
            target_exists = False

        sources = args[:-1]
        if (not target_is_dir) and len(sources) > 1:
            raise ValueError(_("Can't move multiple items to non-directory"))

        sources_total = len(sources)
        self._status_notify(context, sources_total, 0)

        if target_is_dir:
            for i, source in enumerate(sources):
                target_path = FilePath(unix_basename(source), target)
                shutil.move(FilePath(source, context.cwd), target_path)
                self._status_notify(context, sources_total, i + 1)
        else:
            shutil.move(FilePath(sources[0], context.cwd), target)
            self._status_notify(context, sources_total, 1)

        return []
Ejemplo n.º 3
0
def ls(context, *args):
    _("""List contents of a directory.""")
    show_all = '-a' in context.options
    long_fmt = '-l' in context.options
    process_input = '-i' in context.options
    fs = Filesystem.getInstance()

    if process_input and input is not None:
        args = list(args)
        args.extend(context.input)

    if len(args) == 0:
        for x in fs.ls_dir(context.cwd, show_all):
            yield x
    elif len(args) == 1:
        path = FilePath(args[0], context.cwd)
        fobj = fs.get_file_sync(path)
        if fobj.is_directory:
            for x in fs.ls_dir(path, show_all):
                yield x
        else:
            yield fobj
            return
    else:
        # Generate list of sorted File objects from arguments
        for x in sorted(
                xmap(lambda arg: fs.get_file_sync(FilePath(arg, context.cwd)),
                     args), lambda a, b: locale.strcoll(a.path, b.path)):
            yield x
Ejemplo n.º 4
0
 def __init__(self, builtin, args, options, hotwire, tokens=None, in_redir=None, out_redir=None, 
               out_append=False):
     super(Command, self).__init__()
     self.builtin = builtin
     self.context = CommandContext(hotwire)
     # The concept of multiple object streams is dead. 
     #for schema in self.builtin.get_aux_outputs():
     #    self.context.attach_auxstream(CommandAuxStream(self, schema))
     if self.builtin.hasmeta:
         def on_meta(*args):
             dispatcher.send('metadata', self, *args)
         self.context.set_metadata_handler(on_meta)
     self.input = None
     self.output = CommandQueue()
     self.map_fn = lambda x: x
     self.args = args
     self.context.options = options
     self.in_redir = in_redir and FilePath(os.path.expanduser(in_redir), self.context.cwd)
     self.out_redir = out_redir and FilePath(os.path.expanduser(out_redir), self.context.cwd)
     self.out_append = out_append
     
     self.__thread = None
     self.__executing_sync = None
     self._cancelled = False
     self.__tokens = tokens
Ejemplo n.º 5
0
    def execute(self, context, args):
        assert len(args) > 0
        target = FilePath(args[-1], context.cwd)
        try:
            target_is_dir = stat.S_ISDIR(os.stat(target).st_mode)
            target_exists = True
        except OSError as e:
            target_is_dir = False
            target_exists = False

        sources = args[:-1]
        assert len(sources) > 0
        if (not target_is_dir) and len(sources) > 1:
            raise ValueError(_("Can't copy multiple items to non-directory"))
        sources_total = len(sources)
        self._status_notify(context, sources_total, 0)

        if target_is_dir:
            for i, source in enumerate(sources):
                hotwire.fs.copy_file_or_dir(FilePath(source, context.cwd),
                                            target, True)
                self._status_notify(context, sources_total, i + 1)
        else:
            hotwire.fs.copy_file_or_dir(FilePath(sources[0], context.cwd),
                                        target, False)
            self._status_notify(context, sources_total, 1)

        return []
Ejemplo n.º 6
0
 def completions(self, text, cwd):
     expanded = path_expanduser(text)
     fullpath = FilePath(expanded, cwd)
     try:
         isdir = stat.S_ISDIR(os.stat(fullpath).st_mode)
     except OSError, e:
         isdir = False
Ejemplo n.º 7
0
 def completions(self, text, cwd, context=None):
     bc = BuiltinCompleter()
     for completion in bc.completions(text, cwd, context=context):
         yield completion
     aliases = AliasRegistry.getInstance()
     for alias in aliases:
         compl = self._match(alias.name, text, alias)
         if compl: yield compl
     textpath = FilePath(text, cwd)
     expanded_textpath = path_expanduser(textpath)
     (text_dpath, text_prefix) = os.path.split(expanded_textpath)
     if text.find('/') >= 0 or text.startswith('.' + os.sep):
         pc = PathCompleter()
         for completion in pc.completions(text, cwd):
             fobj = completion.target
             if fobj.is_directory or fobj.is_executable:
                 yield completion
     else:
         fs = Filesystem.getInstance()
         for dpath in fs.get_path_generator():
             if not os.access(dpath, os.X_OK):
                 continue
             for fpath in iterd_sorted(dpath):
                 fname = unix_basename(fpath)
                 if not fname.startswith(text_prefix):
                     continue
                 fobj = fs.get_file_sync(fpath)
                 if fobj.is_executable:
                     yield _mkfile_completion(text, fpath, fobj)
Ejemplo n.º 8
0
 def execute(self, context, args):
     target = FilePath(args[-1], context.cwd)
     try:
         target_is_dir = stat.S_ISDIR(os.stat(target).st_mode)
         target_exists = True
     except OSError, e:
         target_is_dir = False
         target_exists = False
Ejemplo n.º 9
0
 def execute(self, context, args):
     sources_total = len(args)
     for i, arg in enumerate(args):
         arg_path = FilePath(arg, context.cwd)
         try:
             os.makedirs(arg_path)
         except OSError, e:
             pass
         self._status_notify(context, sources_total, i + 1)
Ejemplo n.º 10
0
 def executable_on_path(self, execname):
     for dpath in self.get_path_generator():
         epath = FilePath(execname, dpath)
         try:
             fobj = self.get_file_sync(epath)
         except FileStatError, e:
             continue
         if fobj.is_executable:
             return epath
Ejemplo n.º 11
0
 def completions(self, text, cwd):
     expanded = path_expanduser(text)        
     fullpath = FilePath(expanded, cwd)
     try:
         isdir = stat.S_ISDIR(os.stat(fullpath).st_mode)
     except OSError as e:
         isdir = False
     fs = Filesystem.getInstance()
     if isdir and fullpath.endswith('/'):
         for fpath in iterd_sorted(fullpath, fpath=True):
             yield _mkfile_completion(text, fpath)
         return
     (src_dpath, src_prefix) = os.path.split(fullpath)
     try:
         for fpath in iterd_sorted(src_dpath, fpath=True):
             fname = unix_basename(fpath)
             if fname.startswith(src_prefix):
                 try:
                     yield _mkfile_completion(text, fpath)
                 except OSError as e:
                     pass
     except OSError as e:
         pass
Ejemplo n.º 12
0
 def completions(self, text, cwd):
     expanded = path_expanduser(text)
     fullpath = FilePath(expanded, cwd)
     try:
         isdir = stat.S_ISDIR(os.stat(fullpath).st_mode)
     except OSError as e:
         isdir = False
     fs = Filesystem.getInstance()
     if isdir and fullpath.endswith('/'):
         for fpath in iterd_sorted(fullpath, fpath=True):
             yield _mkfile_completion(text, fpath)
         return
     (src_dpath, src_prefix) = os.path.split(fullpath)
     try:
         for fpath in iterd_sorted(src_dpath, fpath=True):
             fname = unix_basename(fpath)
             if fname.startswith(src_prefix):
                 try:
                     yield _mkfile_completion(text, fpath)
                 except OSError as e:
                     pass
     except OSError as e:
         pass
Ejemplo n.º 13
0
class CpBuiltin(FileOpBuiltin):
    __doc__ = _("""Copy sources to destination.""")

    def __init__(self):
        super(CpBuiltin, self).__init__('cp',
                                        aliases=['copy'],
                                        hasstatus=True,
                                        argspec=MultiArgSpec('files', min=2))

    def execute(self, context, args):
        assert len(args) > 0
        target = FilePath(args[-1], context.cwd)
        try:
            target_is_dir = stat.S_ISDIR(os.stat(target).st_mode)
            target_exists = True
        except OSError, e:
            target_is_dir = False
            target_exists = False

        sources = args[:-1]
        assert len(sources) > 0
        if (not target_is_dir) and len(sources) > 1:
            raise ValueError(_("Can't copy multiple items to non-directory"))
        sources_total = len(sources)
        self._status_notify(context, sources_total, 0)

        if target_is_dir:
            for i, source in enumerate(sources):
                hotwire.fs.copy_file_or_dir(FilePath(source, context.cwd),
                                            target, True)
                self._status_notify(context, sources_total, i + 1)
        else:
            hotwire.fs.copy_file_or_dir(FilePath(sources[0], context.cwd),
                                        target, False)
            self._status_notify(context, sources_total, 1)

        return []
Ejemplo n.º 14
0
def sechash(context, *files):
    _("""Create a secure hash (default SHA1) from objects or file arguments."""
      )
    alg = ('-5' in context.options) and md5 or sha
    fs = Filesystem.getInstance()
    if (not files) and context.input:
        for val in context.input:
            valstr = str(val)
            hashval = alg.new()
            hashval.update(valstr)
            yield hashval.hexdigest()
    for arg in files:
        fpath = FilePath(arg, context.cwd)
        stream = open(fpath)
        hashval = alg.new()
        buf = stream.read(4096)
        while buf:
            hashval.update(buf)
            buf = stream.read(4096)
        stream.close()
        yield hashval.hexdigest()
Ejemplo n.º 15
0
 def execute(self, context, args, options=[]):
     if len(args) == 0 and context.input is None:
         raise ValueError(_("Must specify at least one file"))
     mkfile = lambda arg: FilePath(arg, context.cwd)
     sources = map(mkfile, args)
     if context.input is not None:
         sources.extend(imap(lambda f: f.path, context.input))
     sources_total = len(sources)
     undo_targets = []
     self._status_notify(context, sources_total, 0)
     fs = Filesystem.getInstance()
     recursive = '-r' in options
     force = '-f' in options
     if '-u' in options:
         for i, arg in enumerate(sources):
             if recursive:
                 shutil.rmtree(arg, ignore_errors=force)
             else:
                 try:
                     os.unlink(arg)
                 except:
                     if not force:
                         raise
             self._status_notify(context, sources_total, i + 1)
         return []
     else:
         try:
             for i, arg in enumerate(sources):
                 try:
                     fs.move_to_trash(arg)
                 except:
                     if not force:
                         raise
                 undo_targets.append(arg)
                 self._status_notify(context, sources_total, i + 1)
                 self._note_modified_paths(context, sources)
         finally:
             context.push_undo(lambda: fs.undo_trashed(undo_targets))
     return []
Ejemplo n.º 16
0
 def execute(self, context, args, options=[]):
     open_mode = ('-a' in options) and 'a+' or 'w'
     do_pickle = '-p' in options
     with_newline = '-n' in options
     if do_pickle:
         open_mode = 'wb'
     if not context.input:
         return
     streams = map(
         lambda x: open_text_file(FilePath(x, context.cwd), open_mode),
         args)
     if not do_pickle:
         for arg in context.input:
             for stream in streams:
                 stream.write('%s' % (unicode(arg), ))
                 if with_newline:
                     stream.write('\n')
     else:
         # Kind of annoying pickle makes you do this.
         arglist = list(context.input)
         for stream in streams:
             pickle.dump(arglist, stream)
     map(lambda x: x.close(), streams)
     return []
Ejemplo n.º 17
0
def cat(context, *files):
    _("""Yield content lines from file path arguments.""")
    for f in files:
        fpath = FilePath(f, context.cwd)
        for line in open_text_file(fpath):
            yield line
Ejemplo n.º 18
0
def open(context, args):
    _("""Open a file using default program.""")
    fs = Filesystem.getInstance()
    for arg in args:
        fs.launch_open_file(FilePath(arg, context.cwd), context.cwd)