예제 #1
0
    def create(context, resolver, *tokens, **kwargs):
        if context is None:
            context = HotwireContext()
        accept_partial = (('accept_partial' in kwargs) and kwargs['accept_partial'])
        components = []
        undoable = None
        idempotent = True
        prev = None
        pipeline_input_type = 'unknown'
        pipeline_input_optional = 'unknown'
        pipeline_output_type = None
        prev_locality = None
        pipeline_singlevalue = None
        pipeline_type_validates = True
        pushback = []
        tokens = list(tokens)
        def pull_token():
            if pushback:
                return pushback.pop(0)
            else:
                return tokens.pop(0)            
        while tokens or pushback:
            builtin_token = pull_token()
            _logger.debug("token = %r", builtin_token)    
                
            def forcetoken(t):
                # Allow passing plain strings for convenience from Python.
                # Treat them as quoted.
                if isinstance(t, basestring):
                    return ParsedToken(t, -1, quoted=True)
                return t
            
            builtin_token = forcetoken(builtin_token)

            # Attempt to determine which builtin we're using
            if isinstance(builtin_token, Builtin):
                b = builtin_token
                cmdargs = []
            # If we're parsing without a resolver, assume we're using sys
            elif isinstance(builtin_token, ParsedToken):
                try:
                    b = BuiltinRegistry.getInstance()[builtin_token.text]
                    cmdargs = []
                except KeyError, e:
                    if resolver:
                        (b, cmdargs) = resolver.resolve(builtin_token.text, context)
                        _logger.debug("resolved: %r to %r %r", builtin_token.text, b, cmdargs)
                        if not b:
                            raise PipelineParseException(_('No matches for %s') % (builtin_token.text,))
                    else:
                        b = BuiltinRegistry.getInstance()['sys']
                        cmdargs = [ParsedToken(builtin_token.text, builtin_token.start, end=builtin_token.end)]
            elif builtin_token in (hotwire.script.PIPE, hotwire.script.REDIR_IN, hotwire.script.REDIR_OUT, hotwire.script.REDIR_OUT_APPEND):
                raise PipelineParseException(_("Unexpected token %d") % (builtin_token,))
예제 #2
0
파일: command.py 프로젝트: zsx/hotwire
    def create(context, resolver, *tokens, **kwargs):
        if context is None:
            context = HotwireContext()
        accept_partial = (('accept_partial' in kwargs) and kwargs['accept_partial'])
        components = []
        undoable = None
        idempotent = True
        prev = None
        pipeline_input_type = 'unknown'
        pipeline_input_optional = 'unknown'
        pipeline_output_type = None
        prev_locality = None
        pipeline_singlevalue = None
        pipeline_type_validates = True
        pushback = []
        tokens = list(tokens)
        def pull_token():
            if pushback:
                return pushback.pop(0)
            else:
                return tokens.pop(0)            
        while tokens or pushback:
            builtin_token = pull_token()
            _logger.debug("token = %r", builtin_token)    
                
            def forcetoken(t):
                # Allow passing plain strings for convenience from Python.
                # Treat them as quoted.
                if isinstance(t, basestring):
                    return ParsedToken(t, -1, quoted=True)
                return t
            
            builtin_token = forcetoken(builtin_token)

            # Attempt to determine which builtin we're using
            if isinstance(builtin_token, Builtin):
                b = builtin_token
                cmdargs = []
            # If we're parsing without a resolver, assume we're using sys
            elif isinstance(builtin_token, ParsedToken):
                try:
                    b = BuiltinRegistry.getInstance()[builtin_token.text]
                    cmdargs = []
                except KeyError, e:
                    if resolver:
                        (b, cmdargs) = resolver.resolve(builtin_token.text, context)
                        _logger.debug("resolved: %r to %r %r", builtin_token.text, b, cmdargs)
                        if not b:
                            raise PipelineParseException(_('No matches for %s') % (gobject.markup_escape_text(builtin_token.text),))
                    else:
                        b = BuiltinRegistry.getInstance()['sys']
                        cmdargs = [ParsedToken(builtin_token.text, builtin_token.start, end=builtin_token.end)]
            elif builtin_token in (hotwire.script.PIPE, hotwire.script.REDIR_IN, hotwire.script.REDIR_OUT, hotwire.script.REDIR_OUT_APPEND):
                raise PipelineParseException(_("Unexpected token %d") % (builtin_token,))
예제 #3
0
 def completions(self, text, cwd, context=None):
     for builtin in BuiltinRegistry.getInstance():
         compl = self._match(builtin.name, text, builtin)
         if compl: yield compl
         for alias in builtin.aliases:
             compl = self._match(alias, text, builtin)
             if compl: yield compl
예제 #4
0
 def completions(self, text, cwd, context=None):
     for builtin in BuiltinRegistry.getInstance():
         compl = self._match(builtin.name, text, builtin)
         if compl: yield compl
         for alias in builtin.aliases:
             compl = self._match(alias, text, builtin)
             if compl: yield compl
예제 #5
0
 def execute(self, context, args, options=[]):
     regexp = args[0]
     if len(args) == 2:
         path = args[1]
     else:
         path = context.cwd
     regexp = args[0]
     comp_regexp = re.compile(
         regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
     walk_builtin = BuiltinRegistry.getInstance()['walk']
     newctx = HotwireContext(context.cwd)
     for fobj in walk_builtin.execute(newctx, [path]):
         fp = None
         try:
             fp = open_text_file(fobj.path)
             for i, line in enumerate(fp):
                 match = comp_regexp.search(line)
                 if match:
                     yield FileStringMatch(fobj.path, line[:-1], i,
                                           match.start(), match.end())
             fp.close()
         except OSError, e:
             pass
         except UnicodeDecodeError, e:
             pass
예제 #6
0
파일: help.py 프로젝트: searene/PLDetector
 def __help_items(self, items):
     builtins = BuiltinRegistry.getInstance()        
     for name in items:
         builtin = builtins[name]
         self.__append_builtin_base_help(builtin)
         self.__append_builtin_aliases(builtin)
         self.__append_builtin_arghelp(builtin)
         self.__append_builtin_doc(builtin)
예제 #7
0
파일: help.py 프로젝트: searene/PLDetector
    def __help_all(self):
        pbcache = PixbufCache.getInstance()        
        self._buf.insert_markup('Hotwire <i>%s</i>\n\n' % (__version__,))
        self._buf.insert_markup(_('Documentation on the web: '))
        self._buf.insert_markup(' ')
        self.append_link(_('Tutorial'), 'http://code.google.com/p/hotwire-shell/wiki/GettingStarted0700')
        self._buf.insert_markup(' ')
        external_pixbuf = pbcache.get('external.png', size=10)
        self._buf.insert_pixbuf(self._buf.get_end_iter(), external_pixbuf)         
        self._buf.insert_markup('\n\n')

        registry = BuiltinRegistry.getInstance()
        for (setname,builtins) in zip((_('User'), _('Standard'), _('System')), map(list, [registry.user_set, registry.hotwire_set, registry.system_set])):
            if len(builtins) == 0:
                continue 
            self._buf.insert_markup('<larger>%s:</larger>\n' % (_('%s Builtin Commands' % (setname,)),))
            builtins.sort(lambda a,b: cmp(a.name, b.name))
            for builtin in builtins:
                self.__append_builtin_base_help(builtin)
                self.__append_builtin_aliases(builtin)
                self.__append_builtin_arghelp(builtin)            
                self.__append_builtin_doc(builtin)
            self._buf.insert_markup('\n')

        self._buf.insert_markup('<larger>%s:</larger>\n' % (_('Languages'),))
        langreg = PipelineLanguageRegistry.getInstance()
        hotwire_lang = langreg['62270c40-a94a-44dd-aaa0-689f882acf34']
        python_lang = langreg['da3343a0-8bce-46ed-a463-2d17ab09d9b4']
        self.__append_language(hotwire_lang)
        self.__append_language(python_lang) 
        languages = list(langreg)       
        languages.sort(lambda a,b: cmp(a.langname, b.langname))
        for language in languages:
            if language in [hotwire_lang, python_lang]:
                continue
            self.__append_language(language)           
            
        self._buf.insert_markup('\n<larger>%s:</larger>\n' % (_('Aliases'),))
        aliases = list(AliasRegistry.getInstance())
        aliases.sort(lambda a,b: cmp(a.name,b.name))
        for alias in aliases:
            self._buf.insert_markup('  <b>%s</b> - %s\n' % tuple(map(gobject.markup_escape_text, (alias.name, alias.target))))
예제 #8
0
 def execute(self, context, args, options=[]):       
     regexp = args[0]
     if len(args) == 2:
         path = args[1]
     else:
         path = context.cwd
     regexp = args[0]
     comp_regexp = re.compile(regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
     walk_builtin = BuiltinRegistry.getInstance()['walk']
     newctx = HotwireContext(context.cwd)
     for fobj in walk_builtin.execute(newctx, [path]):
         fp = None
         try:
             fp = open_text_file(fobj.path) 
             for i,line in enumerate(fp):
                 match = comp_regexp.search(line)
                 if match:
                     yield FileStringMatch(fobj.path, line[:-1], i, match.start(), match.end())
             fp.close()
         except OSError as e:
             pass
         except UnicodeDecodeError as e:
             pass
예제 #9
0
 def _expand_verb_completion(self, completion):
     target = completion.target
     if isinstance(target, File):
         return (BuiltinRegistry.getInstance()['sys'], [target.path])
예제 #10
0
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from hotwire.builtin import Builtin, BuiltinRegistry, OutputStreamSchema

if '_' not in globals(): globals()['_'] = lambda x: x

class CurrentBuiltin(Builtin):
    __doc__ = _("""Returns objects generated by currently visible command.""")
    def __init__(self):
        super(CurrentBuiltin, self).__init__('current', aliases=['cur'],
                                             idempotent=True,
                                             argspec=None,
                                             output=OutputStreamSchema('any'),
                                             threaded=False)

    def execute(self, context, args):
        meta = context.current_output_metadata
        current = context.snapshot_current_output()
        if current is None:
            return
        if meta.single:
            yield current
        else:
            for obj in current:
                yield obj
BuiltinRegistry.getInstance().register_hotwire(CurrentBuiltin())
예제 #11
0
                             options=[['-i', '--ignore-case']])

    def execute(self, context, args, options=[]):
        regexp = args[0]
        if len(args) == 2:
            path = args[1]
        else:
            path = context.cwd
        regexp = args[0]
        comp_regexp = re.compile(
            regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
        walk_builtin = BuiltinRegistry.getInstance()['walk']
        newctx = HotwireContext(context.cwd)
        for fobj in walk_builtin.execute(newctx, [path]):
            fp = None
            try:
                fp = open_text_file(fobj.path)
                for i, line in enumerate(fp):
                    match = comp_regexp.search(line)
                    if match:
                        yield FileStringMatch(fobj.path, line[:-1], i,
                                              match.start(), match.end())
                fp.close()
            except OSError, e:
                pass
            except UnicodeDecodeError, e:
                pass


BuiltinRegistry.getInstance().register_hotwire(FSearchBuiltin())
예제 #12
0
파일: edit.py 프로젝트: zsx/hotwire
from hotwire.builtin import Builtin, BuiltinRegistry, MultiArgSpec
from hotwire.fs import FilePath
from hotwire.sysdep.fs import Filesystem


class EditBuiltin(Builtin):
    __doc__ = _("""Launch the text editor.""")

    _ws_re = re.compile(r"\s+")

    def __init__(self):
        super(EditBuiltin, self).__init__(
            "edit",
            aliases=["ed"],
            argspec=MultiArgSpec("paths", min=1),
            nodisplay=True,
            idempotent=True,
            threaded=False,
        )

    def execute(self, context, args):
        from hotwire_ui.adaptors.editors import EditorRegistry

        prefeditor = EditorRegistry.getInstance().get_preferred()
        prefeditor.run_many(context.cwd, *args)
        return []


BuiltinRegistry.getInstance().register_hotwire(EditBuiltin())
예제 #13
0
    PYMAP_CONTENT = '''
import os,sys,re
def execute(context, input):
  for it in input:
    yield %s'''

    def __init__(self):
        super(PyMapBuiltin,
              self).__init__('py-map',
                             argspec=(ArgSpec('expression'), ),
                             input=InputStreamSchema('any', optional=True),
                             output=OutputStreamSchema('any'))

    def execute(self, context, args, options=[]):
        buf = self.PYMAP_CONTENT % (args[0], )
        code = compile(buf, '<input>', 'exec')
        locals = {}
        exec(code, locals)
        execute = locals['execute']
        custom_out = execute(context, context.input)
        if custom_out is None:
            return
        if hasattr(custom_out, '__iter__'):
            for o in custom_out:
                yield o
        else:
            yield custom_out


BuiltinRegistry.getInstance().register_hotwire(PyMapBuiltin())
예제 #14
0
    def __init__(self):
        super(SelectionBuiltin, self).__init__(
            'selection',
            aliases=['sel'],
            argspec=(ArgSpec('index', opt=True), ),
            threaded=False,
            output=OutputStreamSchema(
                'any',
                typefunc=lambda hotwire: hotwire.get_current_output_type()))

    def execute(self, context, args):
        current = context.hotwire.snapshot_current_selected_output()
        if len(args) == 0:
            if current is None:
                return
            for obj in current.value:
                yield obj
        elif len(args) == 1:
            idx = int(args[0])
            for i, obj in enumerate(current.value):
                if i == idx:
                    yield obj
                    return
            raise ValueError(_("Index %d out of range") % (idx, ))
        elif len(args) > 2:
            raise ValueError(_("Too many arguments specified"))


BuiltinRegistry.getInstance().register_hotwire(SelectionBuiltin())
예제 #15
0
                             options=[['-a', '--append'], ['-p', '--pickle'],
                                      ['-n', '--newline']])

    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 []


BuiltinRegistry.getInstance().register_hotwire(WriteBuiltin())
예제 #16
0
    def __init__(self):
        super(FSearchBuiltin, self).__init__('fsearch',
                                             output=FileStringMatch,
                                             argspec=('regexp', ArgSpec('directory', opt=True)),                                             
                                             options=[['-i', '--ignore-case']])

    def execute(self, context, args, options=[]):       
        regexp = args[0]
        if len(args) == 2:
            path = args[1]
        else:
            path = context.cwd
        regexp = args[0]
        comp_regexp = re.compile(regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
        walk_builtin = BuiltinRegistry.getInstance()['walk']
        newctx = HotwireContext(context.cwd)
        for fobj in walk_builtin.execute(newctx, [path]):
            fp = None
            try:
                fp = open_text_file(fobj.path) 
                for i,line in enumerate(fp):
                    match = comp_regexp.search(line)
                    if match:
                        yield FileStringMatch(fobj.path, line[:-1], i, match.start(), match.end())
                fp.close()
            except OSError as e:
                pass
            except UnicodeDecodeError as e:
                pass
BuiltinRegistry.getInstance().register_hotwire(FSearchBuiltin())
예제 #17
0
    def create(context, resolver, *tokens, **kwargs):
        if context is None:
            context = HotwireContext()
        accept_partial = (('accept_partial' in kwargs) and kwargs['accept_partial'])
        components = []
        undoable = None
        idempotent = True
        prev = None
        pipeline_input_type = 'unknown'
        pipeline_input_optional = 'unknown'
        pipeline_output_type = None
        prev_locality = None
        pipeline_singlevalue = None
        pipeline_type_validates = True
        pushback = []
        tokens = list(tokens)
        def pull_token():
            if pushback:
                return pushback.pop(0)
            else:
                return tokens.pop(0)            
        while tokens or pushback:
            builtin_token = pull_token()
            _logger.debug("token = %r", builtin_token)    
                
            def forcetoken(t):
                # Allow passing plain strings for convenience from Python.
                # Treat them as quoted.
                if isinstance(t, str):
                    return ParsedToken(t, -1, quoted=True)
                return t
            
            builtin_token = forcetoken(builtin_token)

            # Attempt to determine which builtin we're using
            if isinstance(builtin_token, Builtin):
                b = builtin_token
                cmdargs = []
            # If we're parsing without a resolver, assume we're using sys
            elif isinstance(builtin_token, ParsedToken):
                try:
                    b = BuiltinRegistry.getInstance()[builtin_token.text]
                    cmdargs = []
                except KeyError as e:
                    if resolver:
                        (b, cmdargs) = resolver.resolve(builtin_token.text, context)
                        _logger.debug("resolved: %r to %r %r", builtin_token.text, b, cmdargs)
                        if not b:
                            raise PipelineParseException(_('No matches for %s') % (builtin_token.text,))
                    else:
                        b = BuiltinRegistry.getInstance()['sys']
                        cmdargs = [ParsedToken(builtin_token.text, builtin_token.start, end=builtin_token.end)]
            elif builtin_token in (hotwire.script.PIPE, hotwire.script.REDIR_IN, hotwire.script.REDIR_OUT, hotwire.script.REDIR_OUT_APPEND):
                raise PipelineParseException(_("Unexpected token %d") % (builtin_token,))
            else:
                _logger.error("unknown in parse stream: %r", builtin_token)
                assert False
                
            _logger.debug("target builtin is %r", b)
                
            # We maintain the set of all tokens we processed in the command so that the completion system can use them.
            alltokens = [builtin_token]
            cmdargs = list(map(forcetoken, cmdargs))
            alltokens.extend(cmdargs)
                
            in_redir = None
            out_redir = None

            # Pull from the stream to get all the arguments
            while tokens:
                cmdarg = forcetoken(pull_token())
                if cmdarg == hotwire.script.PIPE:
                    break
                elif cmdarg == hotwire.script.REDIR_IN:
                    if not tokens:
                        raise PipelineParseException(_('Must specify target for input redirection'))
                    in_redir_token = pull_token()
                    in_redir = in_redir_token.text
                    alltokens.append(in_redir_token)
                elif cmdarg == hotwire.script.REDIR_OUT:
                    if not tokens:
                        raise PipelineParseException(_('Must specify target for output redirection'))                   
                    out_redir_token = pull_token()
                    out_redir = out_redir_token.text                     
                    alltokens.append(out_redir_token)               
                else:
                    alltokens.append(cmdarg)
                    cmdargs.append(cmdarg)         

            builtin_opts = b.options

            options = []
            expanded_cmdargs = []
            options_ended = False
            raise_on_invalid_options = not (b.options_passthrough or accept_partial)
            _logger.debug("raise: %r valid options %r, argument/option pool: %r", raise_on_invalid_options,
                          builtin_opts, cmdargs)
            for token in cmdargs:
                arg = CommandArgument(token.text, quoted=token.quoted)
                if token.text == '--':
                    options_ended = True
                elif options_ended:
                    expanded_cmdargs.append(arg)
                else:      
                    argopts = Pipeline.__parse_option_or_arg(builtin_opts, token.text, 
                                                             raise_on_invalid=raise_on_invalid_options)
                    if argopts:
                        options.extend(argopts)
                    else:
                        expanded_cmdargs.append(arg)
                        
            argspec = b.argspec
            if argspec is False or accept_partial:
                # If we don't have an argspec, don't do any checking
                pass
            elif argspec is None:
                if len(expanded_cmdargs) > 0:
                    raise PipelineParseException(_('Command %s takes no arguments, %d given') % (b.name, len(expanded_cmdargs)))
            elif isinstance(argspec, MultiArgSpec):
                if len(expanded_cmdargs) < argspec.min:
                    raise PipelineParseException(_("Command %s requires %d args, %d given") % (b.name,
                                                                                               argspec.min,
                                                                                               len(expanded_cmdargs)))  
            elif isinstance(argspec, tuple):
                mincount = 0
                for o in argspec:
                    if not o.opt: 
                        mincount += 1
                if len(expanded_cmdargs) > len(argspec):
                    raise PipelineParseException(_("Command %s takes at most %d args, %d given") % (b.name,
                                                                                                    len(argspec),
                                                                                                    len(expanded_cmdargs)))
                if len(expanded_cmdargs) < mincount:
                    raise PipelineParseException(_("Command %s requires %d args, %d given") % (b.name,
                                                                                               mincount,
                                                                                               len(expanded_cmdargs)))                
            cmdtokens = [builtin_token]
            cmdtokens.extend(cmdargs)
            cmd = Command(b, expanded_cmdargs, options, context, tokens=alltokens, in_redir=in_redir, out_redir=out_redir)
            components.append(cmd)
            if (not in_redir) and prev:
                cmd.set_input(prev.output)
            if pipeline_output_type:
                cmd.set_input_type(pipeline_output_type)
            input_accepts_type = cmd.builtin.input_type
            input_optional = cmd.builtin.input_is_optional
            if pipeline_input_optional == 'unknown':
                pipeline_input_optional = input_optional
            _logger.debug("Validating input %s vs prev %s", input_accepts_type, pipeline_output_type)

            if prev and not pipeline_output_type:
                raise PipelineParseException(_("Command %s yields no output for pipe") % \
                                             (prev.builtin.name))
            if (not prev) and input_accepts_type and not (input_optional): 
                raise PipelineParseException(_("Command %s requires input of type %s") % \
                                             (cmd.builtin.name, input_accepts_type))
            if input_accepts_type and prev \
                   and not Pipeline.streamtype_is_assignable(pipeline_output_type, input_accepts_type, input_optional):
                raise PipelineParseException(_("Command %s yields '%s' but %s accepts '%s'") % \
                                             (prev.builtin.name, pipeline_output_type, cmd.builtin.name, input_accepts_type))
            if (not input_optional) and (not input_accepts_type) and pipeline_output_type:
                raise PipelineParseException(_("Command %s takes no input but type '%s' given") % \
                                             (cmd.builtin.name, pipeline_output_type))
            locality = cmd.builtin.locality
            if prev_locality and locality and (locality != prev_locality):
                raise PipelineParseException(_("Command %s locality conflict with '%s'") % \
                                             (cmd.builtin.name, prev.builtin.name))
            prev_locality = locality
                
            if out_redir:
                prev = None
            else:
                prev = cmd
            if pipeline_input_type == 'unknown':
                pipeline_input_type = input_accepts_type
                
            if pipeline_singlevalue is None or (pipeline_singlevalue):
                pipeline_singlevalue = cmd.builtin.singlevalue

            if cmd.builtin.output_type != 'identity':
                if context and cmd.builtin.output_typefunc:
                    pipeline_output_type = cmd.builtin.output_typefunc(context)
                    _logger.debug("retrieved type %r from typefunc", pipeline_output_type)
                else:
                    pipeline_output_type = cmd.builtin.output_type

            if undoable is None:
                undoable = cmd.builtin.undoable
            elif not cmd.builtin.undoable:
                undoable = False

            if not cmd.builtin.idempotent:
                idempotent = False
                
        if len(components) == 0:
            raise PipelineParseException(_("Empty pipeline"))

        if undoable is None:
            undoable = False
        pipeline = Pipeline(components,
                            input_type=pipeline_input_type,
                            input_optional=pipeline_input_optional,
                            output_type=pipeline_output_type,
                            locality=prev_locality,
                            undoable=undoable,
                            idempotent=idempotent,
                            singlevalue=pipeline_singlevalue)
        _logger.debug("Parsed pipeline %s (%d components, input %s, output %s)",
                      pipeline, len(components),
                      pipeline.get_input_type(),
                      pipeline.get_output_type())
        return pipeline 
예제 #18
0
            if name.startswith('_'):
                continue
            name_repr[name] = str(type(member))
        return self.encode(name_repr)


class JsonBuiltin(Builtin):
    __doc__ = _("""Convert object stream to JSON.""")

    def __init__(self):
        super(JsonBuiltin, self).__init__(
            'json',
            output=str,  # 'any'
            input=InputStreamSchema('any'),
            idempotent=True,
            argspec=None)

    def execute(self, context, args, options=[]):
        out = StringIO()
        for o in context.input:
            simplejson.dump(o, out, indent=2, cls=LossyObjectJSONDumper)
        # Should support binary streaming
        for line in StringIO(out.getvalue()):
            if line.endswith('\n'):
                yield line[0:-1]
            else:
                yield line


BuiltinRegistry.getInstance().register_hotwire(JsonBuiltin())
예제 #19
0
class PathBuiltin(Builtin):
    __doc__ = _("""Display or modify the external program execution path.""")
    def __init__(self):
        super(PathBuiltin, self).__init__('path',
                                          output=str,
                                          argspec=(ArgSpec('path', opt=True),),
                                          options=[['-a', '--prefix'], ['-s', '--suffix'], ['-d', '--del']],
                                          threaded=False)

    def execute(self, context, args, options=[]):
        curval = os.environ['PATH']
        if len(args) == 0:
            return curval
        if len(options) > 1:
            raise ValueError(_("At most one option can be specified"))
        arg = args[0]
        elts = curval.split(os.pathsep)
        if '-d' in options:
            if arg not in elts:
                raise ValueError(_("Not in path: %s") % (arg,))
            elts.remove(arg)
        elif '-a' in options:
            elts.insert(0, arg)
        elif '-s' in options:
            elts.append(arg)
        else: 
            assert False
        os.environ['PATH'] = os.pathsep.join(elts)    
        return os.environ['PATH']
BuiltinRegistry.getInstance().register_hotwire(PathBuiltin())
예제 #20
0
from hotwire.builtin import Builtin, BuiltinRegistry, MultiArgSpec
from hotwire.externals.singletonmixin import Singleton
from hotwire.sysdep.fs import Filesystem


class HotSudoBuiltin(Builtin):
    __doc__ = _("""Run a command as root.""")

    def __init__(self):
        super(HotSudoBuiltin, self).__init__('sudo',
                                             nodisplay=True,
                                             argspec=MultiArgSpec('args'),
                                             options_passthrough=True)

    def execute(self, context, args, options=[]):
        subproc_args = {}
        if context.gtk_event_time:
            env = dict(os.environ)
            env['DESKTOP_STARTUP_ID'] = 'hotwire%d_TIME%d' % (
                os.getpid(),
                context.gtk_event_time,
            )
            subproc_args['env'] = env
        argv = ['hotwire-sudo']
        argv.extend(args)
        subprocess.Popen(argv, cwd=context.cwd, **subproc_args)
        return []


BuiltinRegistry.getInstance().register_hotwire(HotSudoBuiltin())
예제 #21
0
        super(LossyObjectJSONDumper, self).__init__(*args, **kwargs)
        
    def default(self, o):
        name_repr = {}
        for name,member in sorted(inspect.getmembers(o), lambda a,b: locale.strcoll(a[0],b[0])):
            if name.startswith('_'):
                continue
            name_repr[name] = str(type(member))
        return self.encode(name_repr)

class JsonBuiltin(Builtin):
    __doc__ = _("""Convert object stream to JSON.""")
    def __init__(self):
        super(JsonBuiltin, self).__init__('json',
                                          output=str, # 'any'
                                          input=InputStreamSchema('any'),
                                          idempotent=True,
                                          argspec=None)

    def execute(self, context, args, options=[]):
        out = StringIO()
        for o in context.input:
            simplejson.dump(o, out, indent=2, cls=LossyObjectJSONDumper)
        # Should support binary streaming            
        for line in StringIO(out.getvalue()):
            if line.endswith('\n'):
                yield line[0:-1]
            else:
                yield line
BuiltinRegistry.getInstance().register_hotwire(JsonBuiltin())
예제 #22
0
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from hotwire.builtin import Builtin, BuiltinRegistry, MultiArgSpec

class TermBuiltin(Builtin):
    __doc__ = _("""Execute a system command in a new terminal.""")
    def __init__(self):
        super(TermBuiltin, self).__init__('term',
                                          nodisplay=True,
                                          argspec=MultiArgSpec('args'),
                                          options_passthrough=True,
                                          threaded=False)

    def execute(self, context, args):
        if len(args) > 0 and args[0] == '-e':
            autoclose = True
            args = args[1:]
        else:
            autoclose = False
        context.hotwire.open_term(context.cwd, context.pipeline, args, window=True, autoclose=autoclose)
        return []
        
BuiltinRegistry.getInstance().register_hotwire(TermBuiltin())
예제 #23
0
# The above copyright notice and this permission notice shall be included in all 
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import re

from hotwire.builtin import Builtin, BuiltinRegistry, InputStreamSchema

class NewlineBuiltin(Builtin):
    __doc__ = _("""Convert output to a string, and add a newline if necessary.""")
    def __init__(self):
        super(NewlineBuiltin, self).__init__('newline',
                                             input=InputStreamSchema('any'),
                                             output=str,
                                             argspec=None)

    def execute(self, context, args, options=[]):
        for arg in context.input:
            if not isinstance(arg, str):
                arg = str(arg) 
            if not arg.endswith('\n'):
                arg += '\n'
            yield arg
BuiltinRegistry.getInstance().register_hotwire(NewlineBuiltin())
예제 #24
0
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import re

from hotwire.builtin import Builtin, BuiltinRegistry, InputStreamSchema

class StringifyBuiltin(Builtin):
    __doc__ = _("""Convert output to a string.""")
    def __init__(self):
        super(StringifyBuiltin, self).__init__('stringify',
                                               input=InputStreamSchema('any'),
                                               output=str,
                                               argspec=None)

    def execute(self, context, args, options=[]):
        if len(args) != 0:
            raise ValueError(_("Too many arguments specified"))
        for arg in context.input:
            if not isinstance(arg, basestring):
                yield str(arg)
            else:
                yield arg
BuiltinRegistry.getInstance().register_hotwire(StringifyBuiltin())
예제 #25
0
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from hotwire.builtin import Builtin, BuiltinRegistry, OutputStreamSchema


class HistoryBuiltin(Builtin):
    def __init__(self):
        super(HistoryBuiltin, self).__init__('history', output=str)

    def execute(self, context, args):
        return context.hotwire.get_history()


BuiltinRegistry.getInstance().register_hotwire(HistoryBuiltin())
예제 #26
0
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import re

from hotwire.builtin import Builtin, BuiltinRegistry, InputStreamSchema


class NewlineBuiltin(Builtin):
    __doc__ = _(
        """Convert output to a string, and add a newline if necessary.""")

    def __init__(self):
        super(NewlineBuiltin, self).__init__('newline',
                                             input=InputStreamSchema('any'),
                                             output=str,
                                             argspec=None)

    def execute(self, context, args, options=[]):
        for arg in context.input:
            if not isinstance(arg, str):
                arg = str(arg)
            if not arg.endswith('\n'):
                arg += '\n'
            yield arg


BuiltinRegistry.getInstance().register_hotwire(NewlineBuiltin())
예제 #27
0

class HttpGetBuiltin(Builtin):
    __doc__ = _("""Perform a HTTP GET.""")

    def __init__(self):
        super(HttpGetBuiltin,
              self).__init__('http-get',
                             output=HTTPResponse,
                             input=None,
                             singlevalue=True,
                             argspec=(ArgSpec('host'), ArgSpec('path',
                                                               opt=True)))

    def execute(self, context, args, options=[]):
        if len(args) == 1:
            host = args[0]
            path = '/'
        elif len(args) == 2:
            host = args[0]
            path = args[1]
        else:
            assert False
        conn = httplib.HTTPConnection(host)
        conn.request('GET', path)
        response = conn.getresponse()
        return response


BuiltinRegistry.getInstance().register_hotwire(HttpGetBuiltin())
예제 #28
0
        super(WriteBuiltin, self).__init__('write',
                                           input=InputStreamSchema('any', optional=False),
                                           argspec=MultiArgSpec('paths', min=1),
                                           options=[['-a', '--append'],['-p', '--pickle'],
                                                    ['-n', '--newline']])

    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 []

BuiltinRegistry.getInstance().register_hotwire(WriteBuiltin())
예제 #29
0
from http.client import HTTPResponse
from io import StringIO

from hotwire.fs import FilePath

from hotwire.builtin import Builtin, BuiltinRegistry, InputStreamSchema, ArgSpec

class HttpGetBuiltin(Builtin):
    __doc__ = _("""Perform a HTTP GET.""")
    def __init__(self):
        super(HttpGetBuiltin, self).__init__('http-get',
                                             output=HTTPResponse,
                                             input=None,
                                             singlevalue=True,                                             
                                             argspec=(ArgSpec('host'), ArgSpec('path', opt=True)))

    def execute(self, context, args, options=[]):       
        if len(args) == 1:
            host = args[0]
            path = '/'
        elif len(args) == 2:
            host = args[0]
            path = args[1]
        else:
            assert False         
        conn = http.client.HTTPConnection(host)
        conn.request('GET', path)
        response = conn.getresponse() 
        return response
BuiltinRegistry.getInstance().register_hotwire(HttpGetBuiltin())
예제 #30
0
 def execute(self, context, args):
     builtins = BuiltinRegistry.getInstance()        
     yield HelpItem([builtins[x] for x in args])
예제 #31
0
import hotwire.fs
from hotwire.fs import FilePath

from hotwire.builtin import Builtin, BuiltinRegistry, MultiArgSpec
from hotwire.builtins.fileop import FileOpBuiltin


class MkdirBuiltin(FileOpBuiltin):
    __doc__ = _("""Create directories.""")

    def __init__(self):
        super(MkdirBuiltin, self).__init__('mkdir',
                                           hasstatus=True,
                                           argspec=MultiArgSpec('paths',
                                                                min=1))

    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)

        return []


BuiltinRegistry.getInstance().register_hotwire(MkdirBuiltin())
예제 #32
0
class SelectionBuiltin(Builtin):
    __doc__ = _("""With no arguments, returns currently selected objects.
Single integer argument selects object at that index.""")
    def __init__(self):
        super(SelectionBuiltin, self).__init__('selection', 
                                               aliases=['sel'],
                                               argspec=(ArgSpec('index', opt=True),),
                                               threaded=False,
                                               output=OutputStreamSchema('any', 
                                                                         typefunc=lambda hotwire: hotwire.get_current_output_type()))

    def execute(self, context, args):
        current = context.hotwire.snapshot_current_selected_output()        
        if len(args) == 0:
            if current is None:
                return
            for obj in current.value:
                yield obj
        elif len(args) == 1:
            idx = int(args[0])
            for i,obj in enumerate(current.value):
                if i == idx:
                    yield obj
                    return
            raise ValueError(_("Index %d out of range") % (idx,))
        elif len(args) > 2:
            raise ValueError(_("Too many arguments specified"))            
    
BuiltinRegistry.getInstance().register_hotwire(SelectionBuiltin())
예제 #33
0
    def execute(self, context, args):
        signum = signal.SIGTERM
        sigidx = -1
        for i,arg in enumerate(args):
            if not arg.startswith('-'):
                continue
            optval = arg[1:]
            if optval in _sigsym_to_value:
                signum = _sigsym_to_value[optval]
                sigidx = i
                break
            else:
                optnum = int(optval)
                if optnum in _sigvalue_to_sym:
                    signum = optnum
                    sigidx = i
                    break
                else:
                    raise ValueError("Invalid signal number: %d", optnum)
        if sigidx >= 0:
            del args[sigidx]
        for arg in map(int, args):
            os.kill(arg, signum)
        if context.input is not None:
            for arg in context.input:
                os.kill(arg.pid, signum)
        return []
        
BuiltinRegistry.getInstance().register_hotwire(KillBuiltin())
예제 #34
0
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import re

from hotwire.builtin import Builtin, BuiltinRegistry, InputStreamSchema


class StringifyBuiltin(Builtin):
    __doc__ = _("""Convert output to a string.""")

    def __init__(self):
        super(StringifyBuiltin, self).__init__('stringify',
                                               input=InputStreamSchema('any'),
                                               output=str,
                                               argspec=None)

    def execute(self, context, args, options=[]):
        if len(args) != 0:
            raise ValueError(_("Too many arguments specified"))
        for arg in context.input:
            if not isinstance(arg, str):
                yield str(arg)
            else:
                yield arg


BuiltinRegistry.getInstance().register_hotwire(StringifyBuiltin())
예제 #35
0
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import os, sys, re

from hotwire.builtin import Builtin, BuiltinRegistry, InputStreamSchema, ArgSpec


class ReplaceBuiltin(Builtin):
    __doc__ = _(
        """Replace input objects by regular expression, matching on a property (or repr)"""
    )

    def __init__(self):
        super(ReplaceBuiltin, self).__init__('replace',
                                             input=InputStreamSchema('any'),
                                             output='identity',
                                             argspec=(ArgSpec('regexp'),
                                                      ArgSpec('replacement')))

    def execute(self, context, args, options=[]):
        regexp = args[0]
        replacement = args[1]
        stringify = '-s' in options
        compiled_re = re.compile(
            regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
        for arg in context.input:
            yield compiled_re.sub(regexp, replacement, arg)


BuiltinRegistry.getInstance().register_hotwire(ReplaceBuiltin())
예제 #36
0
            prop = args[1]
        else:
            prop = None
        regexp = args[0]
        target_prop = prop
        invert = '-v' in options
        stringify = '-s' in options
        compiled_re = re.compile(regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
        for arg in context.input:
            if target_prop is not None:
                target_propvalue = getattr(arg, target_prop)
            else:
                target_propvalue = arg
            if not isinstance(target_propvalue, str):
                if not stringify:
                    raise ValueError(_("Value not a string: %r" % (target_propvalue,)))
                else:
                    target_propvalue = repr(target_propvalue)
            elif not isinstance(target_propvalue, str):
                target_propvalue = str(target_propvalue, 'utf-8')                
                        
            match = compiled_re.search(target_propvalue)
            if invert:
                match = not match
            if match:
                if isinstance(arg, str):
                    yield StringMatch(target_propvalue, match)
                else:
                    yield arg
BuiltinRegistry.getInstance().register_hotwire(FilterBuiltin())
예제 #37
0
    def execute(self, context, args, options=[]):     
        if len(args) == 1:
            target_prop = args[0]
        else:
            target_prop = None
        count_obj = '-c' in options
        order_unique_items = []
        unique_items = {}
        for arg in context.input:
            if target_prop is not None:
                value = getattr(arg, target_prop)
            else:
                value = arg
            if value in unique_items:
                if count_obj:
                    unique_items[value] += 1
                continue
            unique_items[value] = 1
            if count_obj:
                # keep order while counting
                order_unique_items.append(value)
            else:
                yield value
        if count_obj:
            for item in order_unique_items:
                yield (unique_items[item], item)
                        

BuiltinRegistry.getInstance().register_hotwire(UniqBuiltin())
예제 #38
0
    def create(context, resolver, *tokens, **kwargs):
        if context is None:
            context = HotwireContext()
        accept_partial = (('accept_partial' in kwargs)
                          and kwargs['accept_partial'])
        components = []
        undoable = None
        idempotent = True
        prev = None
        pipeline_input_type = 'unknown'
        pipeline_input_optional = 'unknown'
        pipeline_output_type = None
        prev_locality = None
        pipeline_singlevalue = None
        pipeline_type_validates = True
        pushback = []
        tokens = list(tokens)

        def pull_token():
            if pushback:
                return pushback.pop(0)
            else:
                return tokens.pop(0)

        while tokens or pushback:
            builtin_token = pull_token()
            _logger.debug("token = %r", builtin_token)

            def forcetoken(t):
                # Allow passing plain strings for convenience from Python.
                # Treat them as quoted.
                if isinstance(t, str):
                    return ParsedToken(t, -1, quoted=True)
                return t

            builtin_token = forcetoken(builtin_token)

            # Attempt to determine which builtin we're using
            if isinstance(builtin_token, Builtin):
                b = builtin_token
                cmdargs = []
            # If we're parsing without a resolver, assume we're using sys
            elif isinstance(builtin_token, ParsedToken):
                try:
                    b = BuiltinRegistry.getInstance()[builtin_token.text]
                    cmdargs = []
                except KeyError as e:
                    if resolver:
                        (b,
                         cmdargs) = resolver.resolve(builtin_token.text,
                                                     context)
                        _logger.debug("resolved: %r to %r %r",
                                      builtin_token.text, b, cmdargs)
                        if not b:
                            raise PipelineParseException(
                                _('No matches for %s') %
                                (builtin_token.text, ))
                    else:
                        b = BuiltinRegistry.getInstance()['sys']
                        cmdargs = [
                            ParsedToken(builtin_token.text,
                                        builtin_token.start,
                                        end=builtin_token.end)
                        ]
            elif builtin_token in (hotwire.script.PIPE,
                                   hotwire.script.REDIR_IN,
                                   hotwire.script.REDIR_OUT,
                                   hotwire.script.REDIR_OUT_APPEND):
                raise PipelineParseException(
                    _("Unexpected token %d") % (builtin_token, ))
            else:
                _logger.error("unknown in parse stream: %r", builtin_token)
                assert False

            _logger.debug("target builtin is %r", b)

            # We maintain the set of all tokens we processed in the command so that the completion system can use them.
            alltokens = [builtin_token]
            cmdargs = list(map(forcetoken, cmdargs))
            alltokens.extend(cmdargs)

            in_redir = None
            out_redir = None

            # Pull from the stream to get all the arguments
            while tokens:
                cmdarg = forcetoken(pull_token())
                if cmdarg == hotwire.script.PIPE:
                    break
                elif cmdarg == hotwire.script.REDIR_IN:
                    if not tokens:
                        raise PipelineParseException(
                            _('Must specify target for input redirection'))
                    in_redir_token = pull_token()
                    in_redir = in_redir_token.text
                    alltokens.append(in_redir_token)
                elif cmdarg == hotwire.script.REDIR_OUT:
                    if not tokens:
                        raise PipelineParseException(
                            _('Must specify target for output redirection'))
                    out_redir_token = pull_token()
                    out_redir = out_redir_token.text
                    alltokens.append(out_redir_token)
                else:
                    alltokens.append(cmdarg)
                    cmdargs.append(cmdarg)

            builtin_opts = b.options

            options = []
            expanded_cmdargs = []
            options_ended = False
            raise_on_invalid_options = not (b.options_passthrough
                                            or accept_partial)
            _logger.debug(
                "raise: %r valid options %r, argument/option pool: %r",
                raise_on_invalid_options, builtin_opts, cmdargs)
            for token in cmdargs:
                arg = CommandArgument(token.text, quoted=token.quoted)
                if token.text == '--':
                    options_ended = True
                elif options_ended:
                    expanded_cmdargs.append(arg)
                else:
                    argopts = Pipeline.__parse_option_or_arg(
                        builtin_opts,
                        token.text,
                        raise_on_invalid=raise_on_invalid_options)
                    if argopts:
                        options.extend(argopts)
                    else:
                        expanded_cmdargs.append(arg)

            argspec = b.argspec
            if argspec is False or accept_partial:
                # If we don't have an argspec, don't do any checking
                pass
            elif argspec is None:
                if len(expanded_cmdargs) > 0:
                    raise PipelineParseException(
                        _('Command %s takes no arguments, %d given') %
                        (b.name, len(expanded_cmdargs)))
            elif isinstance(argspec, MultiArgSpec):
                if len(expanded_cmdargs) < argspec.min:
                    raise PipelineParseException(
                        _("Command %s requires %d args, %d given") %
                        (b.name, argspec.min, len(expanded_cmdargs)))
            elif isinstance(argspec, tuple):
                mincount = 0
                for o in argspec:
                    if not o.opt:
                        mincount += 1
                if len(expanded_cmdargs) > len(argspec):
                    raise PipelineParseException(
                        _("Command %s takes at most %d args, %d given") %
                        (b.name, len(argspec), len(expanded_cmdargs)))
                if len(expanded_cmdargs) < mincount:
                    raise PipelineParseException(
                        _("Command %s requires %d args, %d given") %
                        (b.name, mincount, len(expanded_cmdargs)))
            cmdtokens = [builtin_token]
            cmdtokens.extend(cmdargs)
            cmd = Command(b,
                          expanded_cmdargs,
                          options,
                          context,
                          tokens=alltokens,
                          in_redir=in_redir,
                          out_redir=out_redir)
            components.append(cmd)
            if (not in_redir) and prev:
                cmd.set_input(prev.output)
            if pipeline_output_type:
                cmd.set_input_type(pipeline_output_type)
            input_accepts_type = cmd.builtin.input_type
            input_optional = cmd.builtin.input_is_optional
            if pipeline_input_optional == 'unknown':
                pipeline_input_optional = input_optional
            _logger.debug("Validating input %s vs prev %s", input_accepts_type,
                          pipeline_output_type)

            if prev and not pipeline_output_type:
                raise PipelineParseException(_("Command %s yields no output for pipe") % \
                                             (prev.builtin.name))
            if (not prev) and input_accepts_type and not (input_optional):
                raise PipelineParseException(_("Command %s requires input of type %s") % \
                                             (cmd.builtin.name, input_accepts_type))
            if input_accepts_type and prev \
                   and not Pipeline.streamtype_is_assignable(pipeline_output_type, input_accepts_type, input_optional):
                raise PipelineParseException(_("Command %s yields '%s' but %s accepts '%s'") % \
                                             (prev.builtin.name, pipeline_output_type, cmd.builtin.name, input_accepts_type))
            if (not input_optional) and (
                    not input_accepts_type) and pipeline_output_type:
                raise PipelineParseException(_("Command %s takes no input but type '%s' given") % \
                                             (cmd.builtin.name, pipeline_output_type))
            locality = cmd.builtin.locality
            if prev_locality and locality and (locality != prev_locality):
                raise PipelineParseException(_("Command %s locality conflict with '%s'") % \
                                             (cmd.builtin.name, prev.builtin.name))
            prev_locality = locality

            if out_redir:
                prev = None
            else:
                prev = cmd
            if pipeline_input_type == 'unknown':
                pipeline_input_type = input_accepts_type

            if pipeline_singlevalue is None or (pipeline_singlevalue):
                pipeline_singlevalue = cmd.builtin.singlevalue

            if cmd.builtin.output_type != 'identity':
                if context and cmd.builtin.output_typefunc:
                    pipeline_output_type = cmd.builtin.output_typefunc(context)
                    _logger.debug("retrieved type %r from typefunc",
                                  pipeline_output_type)
                else:
                    pipeline_output_type = cmd.builtin.output_type

            if undoable is None:
                undoable = cmd.builtin.undoable
            elif not cmd.builtin.undoable:
                undoable = False

            if not cmd.builtin.idempotent:
                idempotent = False

        if len(components) == 0:
            raise PipelineParseException(_("Empty pipeline"))

        if undoable is None:
            undoable = False
        pipeline = Pipeline(components,
                            input_type=pipeline_input_type,
                            input_optional=pipeline_input_optional,
                            output_type=pipeline_output_type,
                            locality=prev_locality,
                            undoable=undoable,
                            idempotent=idempotent,
                            singlevalue=pipeline_singlevalue)
        _logger.debug(
            "Parsed pipeline %s (%d components, input %s, output %s)",
            pipeline, len(components), pipeline.get_input_type(),
            pipeline.get_output_type())
        return pipeline
예제 #39
0
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import os,sys,re,os.path, stat,subprocess

from hotwire.builtin import Builtin, BuiltinRegistry, MultiArgSpec
from hotwire.fs import FilePath
from hotwire.sysdep.fs import Filesystem

class ViewBuiltin(Builtin):
    __doc__ = _("""Launch the text viewer.""")
    
    def __init__(self):
        super(ViewBuiltin, self).__init__('view',
                                          nodisplay=True,
                                          argspec=MultiArgSpec('paths', min=1),
                                          idempotent=True,
                                          threaded=False)
 
    def execute(self, context, args):
        from hotwire_ui.adaptors.editors import EditorRegistry
        prefeditor = EditorRegistry.getInstance().get_preferred()
        prefeditor.run_many_readonly(context.cwd, *args)
        return []
BuiltinRegistry.getInstance().register_hotwire(ViewBuiltin())
예제 #40
0
파일: help.py 프로젝트: zsx/hotwire
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from hotwire.builtin import Builtin, BuiltinRegistry, ArgSpec

from hotwire.completion import BuiltinCompleter

class HelpItem(object):
    def __init__(self, items):
        self.items = items

class HelpBuiltin(Builtin):
    __doc__ = _("""Display help.""")
    def __init__(self):
        super(HelpBuiltin, self).__init__('help',
                                          output=HelpItem,
                                          argspec=(ArgSpec('builtin', opt=True),))

    def get_completer(self, context, args, i):
        return BuiltinCompleter()

    def execute(self, context, args):    
        yield HelpItem(args)
            
    
BuiltinRegistry.getInstance().register_hotwire(HelpBuiltin())
예제 #41
0
# The above copyright notice and this permission notice shall be included in all 
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import os,sys,re

from hotwire.builtin import Builtin, BuiltinRegistry, InputStreamSchema, ArgSpec

class ReplaceBuiltin(Builtin):
    __doc__ = _("""Replace input objects by regular expression, matching on a property (or repr)""")
    def __init__(self):
        super(ReplaceBuiltin, self).__init__('replace',
                                            input=InputStreamSchema('any'),
                                            output='identity',
                                            argspec=(ArgSpec('regexp'), ArgSpec('replacement')))

    def execute(self, context, args, options=[]):
        regexp = args[0]
        replacement = args[1]
        stringify = '-s' in options
        compiled_re = re.compile(regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
        for arg in context.input:
            yield compiled_re.sub(regexp,replacement,arg)
BuiltinRegistry.getInstance().register_hotwire(ReplaceBuiltin())
예제 #42
0
    def execute(self, context, args, options=[]):
        if len(args) == 1:
            target_prop = args[0]
        else:
            target_prop = None
        count_obj = '-c' in options
        order_unique_items = []
        unique_items = {}
        for arg in context.input:
            if target_prop is not None:
                value = getattr(arg, target_prop)
            else:
                value = arg
            if value in unique_items:
                if count_obj:
                    unique_items[value] += 1
                continue
            unique_items[value] = 1
            if count_obj:
                # keep order while counting
                order_unique_items.append(value)
            else:
                yield value
        if count_obj:
            for item in order_unique_items:
                yield (unique_items[item], item)


BuiltinRegistry.getInstance().register_hotwire(UniqBuiltin())
예제 #43
0
파일: command.py 프로젝트: zsx/hotwire
 def _expand_verb_completion(self, completion):
     target = completion.target
     if isinstance(target, File):
         return (BuiltinRegistry.getInstance()['sys'], [target.path])       
예제 #44
0
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import os, sys, re, os.path, stat, subprocess

from hotwire.builtin import Builtin, BuiltinRegistry, MultiArgSpec
from hotwire.fs import FilePath
from hotwire.sysdep.fs import Filesystem


class EditBuiltin(Builtin):
    __doc__ = _("""Launch the text editor.""")

    _ws_re = re.compile(r'\s+')

    def __init__(self):
        super(EditBuiltin, self).__init__('edit',
                                          aliases=['ed'],
                                          argspec=MultiArgSpec('paths', min=1),
                                          nodisplay=True,
                                          idempotent=True,
                                          threaded=False)

    def execute(self, context, args):
        from hotwire_ui.adaptors.editors import EditorRegistry
        prefeditor = EditorRegistry.getInstance().get_preferred()
        prefeditor.run_many(context.cwd, *args)
        return []


BuiltinRegistry.getInstance().register_hotwire(EditBuiltin())
예제 #45
0
파일: sudo.py 프로젝트: zsx/hotwire
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import os, sys, subprocess

from hotwire.builtin import Builtin, BuiltinRegistry, MultiArgSpec
from hotwire.externals.singletonmixin import Singleton
from hotwire.sysdep.fs import Filesystem


class HotSudoBuiltin(Builtin):
    __doc__ = _("""Run a command as root.""")

    def __init__(self):
        super(HotSudoBuiltin, self).__init__(
            "sudo", nodisplay=True, argspec=MultiArgSpec("args"), options_passthrough=True
        )

    def execute(self, context, args, options=[]):
        subproc_args = {}
        if context.gtk_event_time:
            env = dict(os.environ)
            env["DESKTOP_STARTUP_ID"] = "hotwire%d_TIME%d" % (os.getpid(), context.gtk_event_time)
            subproc_args["env"] = env
        argv = ["hotwire-sudo"]
        argv.extend(args)
        subprocess.Popen(argv, cwd=context.cwd, **subproc_args)
        return []


BuiltinRegistry.getInstance().register_hotwire(HotSudoBuiltin())