Пример #1
0
def main():
    default_alias_file = os.path.expanduser("~/.aliases")
    parser = argparse.ArgumentParser(
        description="If no arguments are provided, display the available aliases"
    )
    parser.add_argument('--version', action='version', version=get_version())
    parser.add_argument("alias", default=None, nargs="?",
            help="Name of alias")
    parser.add_argument("directory", default=os.getcwd(), nargs="?",
            help="Directory to associate with alias. "
                "Default is current working directory")
    parser.add_argument("--remove", default=None, metavar="alias",
            help="Remove alias if it exists")
    parser.add_argument("--show", default=None, metavar="alias",
            help="Show the value of an alias if it exists")
    parser.add_argument("--dump-alias", action="store_true",
            help="Display a list of alias statements")
    parser.add_argument("--dump-unalias", action="store_true",
            help="Display a list of unalias statements")
    parser.add_argument("--alias-file", 
            default=default_alias_file,
            help="Default is %s" % default_alias_file)
    args = parser.parse_args()

    Aliases.FILE = args.alias_file

    if args.show:
        try:
            print Aliases[args.show]
        except KeyError:
            print "Error: Alias '%s' does not exist" % args.show
    elif args.remove:
        try:
            del Aliases[args.remove]
        except KeyError:
            print "Error: Alias '%s' does not exist" % args.remove
    elif args.alias:
        Aliases[args.alias] = args.directory
    elif args.dump_unalias:
        for alias in sorted(Aliases.aliases.items()):
            print "unalias %s;" % Aliases.quote(alias[0])
    elif args.dump_alias:
        for alias in sorted(Aliases.aliases.items()):
            print "alias %s=%s;" % (
                    Aliases.quote(alias[0]), 
                    Aliases.quote("cd %s" % alias[1]))
    else:
        for alias in sorted(Aliases.aliases.items()):
            print "%-10s" % alias[0], alias[1]
Пример #2
0
    def visit_Call(self, node):
        l0 = self.generic_visit(node)
        index_corres = dict()
        func = None
        for i, arg in enumerate(node.args):
            n = self.argument_index(arg)
            if n >= 0:
                func_aliases = self.aliases[node].state[
                    Aliases.access_path(node.func)]

                # expand argument if any
                func_aliases = reduce(
                    lambda x, y: x + (
                        self.all_functions
                        if (isinstance(y, ast.Name)
                            and self.argument_index(y) >= 0)
                        else [y]),
                    func_aliases,
                    list())

                for func_alias in func_aliases:
                    # special hook for binded functions
                    if isinstance(func_alias, ast.Call):
                        bound_name = func_alias.args[0].id
                        func_alias = self.global_declarations[bound_name]
                    func_alias = self.node_to_functioneffect[func_alias]
                    index_corres[n] = i
                    func = func_alias

        return lambda ctx: l0(ctx) + self.recursive_weight(
            func, index_corres[ctx.index], ctx.path) if (
            (ctx.index in index_corres) and ctx.global_dependencies) else 0
Пример #3
0
    def visit_Call(self, node):
        for i, arg in enumerate(node.args):
            n = self.argument_index(arg)
            if n >= 0:
                func_aliases = self.aliases[node].state[Aliases.access_path(
                    node.func)]

                # expand argument if any
                func_aliases = reduce(
                    lambda x, y: x + (self.all_functions
                                      if (isinstance(y, ast.Name) and self.
                                          argument_index(y) >= 0) else [y]),
                    func_aliases, list())

                for func_alias in func_aliases:
                    # special hook for binded functions
                    if isinstance(func_alias, ast.Call):
                        bound_name = func_alias.args[0].id
                        func_alias = self.global_declarations[bound_name]
                    func_alias = self.node_to_functioneffect[func_alias]
                    predecessors = self.result.predecessors(func_alias)
                    if self.current_function not in predecessors:
                        self.result.add_edge(self.current_function,
                                             func_alias,
                                             effective_parameters=[],
                                             formal_parameters=[])
                    edge = self.result.edge[self.current_function][func_alias]
                    edge["effective_parameters"].append(n)
                    edge["formal_parameters"].append(i)
        self.generic_visit(node)
Пример #4
0
    def visit_Call(self, node):
        l0 = self.generic_visit(node)
        index_corres = dict()
        func = None
        for i, arg in enumerate(node.args):
            n = self.argument_index(arg)
            if n >= 0:
                func_aliases = self.aliases[node].state[Aliases.access_path(
                    node.func)]

                # expand argument if any
                func_aliases = reduce(
                    lambda x, y: x + (self.all_functions
                                      if (isinstance(y, ast.Name) and self.
                                          argument_index(y) >= 0) else [y]),
                    func_aliases, list())

                for func_alias in func_aliases:
                    # special hook for binded functions
                    if isinstance(func_alias, ast.Call):
                        bound_name = func_alias.args[0].id
                        func_alias = self.global_declarations[bound_name]
                    func_alias = self.node_to_functioneffect[func_alias]
                    index_corres[n] = i
                    func = func_alias

        return lambda ctx: l0(ctx) + self.recursive_weight(
            func, index_corres[ctx.index], ctx.path) if (
                (ctx.index in index_corres) and ctx.global_dependencies) else 0
Пример #5
0
    def visit_Call(self, node):
        for i, arg in enumerate(node.args):
            n = self.argument_index(arg)
            if n >= 0:
                func_aliases = self.aliases[node].state[
                    Aliases.access_path(node.func)]

                # expand argument if any
                func_aliases = reduce(
                    lambda x, y: x + (
                        self.all_functions
                        if (isinstance(y, ast.Name)
                            and self.argument_index(y) >= 0)
                        else [y]),
                    func_aliases,
                    list())

                for func_alias in func_aliases:
                    # special hook for binded functions
                    if isinstance(func_alias, ast.Call):
                        bound_name = func_alias.args[0].id
                        func_alias = self.global_declarations[bound_name]
                    func_alias = self.node_to_functioneffect[func_alias]
                    predecessors = self.result.predecessors(func_alias)
                    if self.current_function not in predecessors:
                        self.result.add_edge(
                            self.current_function,
                            func_alias,
                            effective_parameters=[],
                            formal_parameters=[])
                    edge = self.result.edge[self.current_function][func_alias]
                    edge["effective_parameters"].append(n)
                    edge["formal_parameters"].append(i)
        self.generic_visit(node)
Пример #6
0
class PreProcess:
    def __init__(self):
        self.aliases = Aliases()

    def process(self, question):
        self.process_restructuring(question)

    def process_aliases(self, question):
        question.text = self.aliases.parse(question.text)

    def process_restructuring(self, question):
        self.restructure_question(question)

    def restructure_question(self, question):
        unstructured = question.text

        words = question.text.split()

        if words[0] in ("in", "on"):
            for idx in range(len(words)):
                if words[idx] in ("is", "was", "does", "do", "lies", "can"):
                    max_index = len(words)

                    if words[-1] in ("lie?", "live?", "flow?"):
                        max_index -= 1

                    if idx == 2:
                        res = " ".join(words[1:max_index])

                    else:
                        res = words[1] + " is " + " ".join(
                            words[2:idx]) + " of " + " ".join(
                                words[idx + 1:max_index])

                    question.text = res

        elif words[0] in ("list", "state") and len(words) > 1:
            question.text = "name " + " ".join(words[1:])

        if words[-1] == "flag?":
            question.text = " ".join(words[:-3]) + " " + "".join(
                list(words[-1])[:-1]) + " of " + "".join(list(words[-2])[:-1])

        self.process_aliases(question)

        if unstructured != question.text:
            self.restructure_question(question)
Пример #7
0
 def visit_Call(self, node):
     # try to get all aliases of the function, if possible
     # else use [] as a fallback
     ap = Aliases.access_path(node.func)
     func_aliases = self.aliases[node].state.get(ap, [])
     # expand argument if any
     func_aliases = reduce(
         lambda x, y: x + (self.all_functions
                           if isinstance(y, ast.Name) else [y]),
         func_aliases, list())
     for func_alias in func_aliases:
         # special hook for binded functions
         if isinstance(func_alias, ast.Call):
             bound_name = func_alias.args[0].id
             func_alias = self.global_declarations[bound_name]
         func_alias = self.node_to_functioneffect[func_alias]
         self.result.add_edge(self.current_function, func_alias)
     self.generic_visit(node)
Пример #8
0
class ParseProject(object):
    """ Parse an x2p project
    """
    def __init__(self, project_file, sdk=None, wsroot=None):
        self.xml = parsers.get_xml(project_file)
        self.aliases = Aliases(project_file, sdk=sdk, wsroot=wsroot)
        self.xml_tree = self.xml.parse()
        self.files = self._parse_files()
        self.configurations = self._parse_configurations()

    def _parse_files(self):
        files = []
        for file_element in self.xml_tree.iter(file_xpath):
            file_path = file_element.get(path_attr_str)
            file_path = self.aliases.expand(file_path)
            if not os.path.isabs(file_path):
                file_path = os.path.normpath(
                    os.path.join(self.xml.base_dir, file_path))
            if not os.path.isfile(file_path):
                print(
                    "WARN: File listed in project {} doesn't exist: {}".format(
                        self.xml.filename, file_path))
            files.append(file_path)
        return files

    def _parse_configurations(self):
        configurations_elements = self.xml_tree.findall(configurations_xpath)
        if len(configurations_elements) > 1:
            raise InvalidProjectElement(
                "Multiple <configurations> elements in {}".format(
                    self.xml.filename))
        elif len(configurations_elements) < 1:
            raise InvalidProjectElement(
                "No <configurations> elements found in {}".format(
                    self.xml.filename))

        configurations = {}
        for config in configurations_elements[0].findall(configuration_xpath):
            configuration = Configuration(config)
            configurations[configuration.name] = configuration
        return configurations

    def parse(self):
        return self.files, self.configurations
Пример #9
0
 def visit_Call(self, node):
     # try to get all aliases of the function, if possible
     # else use [] as a fallback
     ap = Aliases.access_path(node.func)
     func_aliases = self.aliases[node].state.get(ap, [])
     # expand argument if any
     func_aliases = reduce(
         lambda x, y: x + (self.all_functions
                           if isinstance(y, ast.Name) else [y]),
         func_aliases,
         list())
     for func_alias in func_aliases:
         # special hook for binded functions
         if isinstance(func_alias, ast.Call):
             bound_name = func_alias.args[0].id
             func_alias = self.global_declarations[bound_name]
         func_alias = self.node_to_functioneffect[func_alias]
         self.result.add_edge(self.current_function, func_alias)
     self.generic_visit(node)
Пример #10
0
 def __init__(self, workspace_file):
     self.workspace_xml = parsers.get_xml(workspace_file)
     self.aliases = Aliases(workspace_file)
     self.default_project = None
Пример #11
0
class ParseWorkspace(object):
    """Parse an x2w workspace"""
    def __init__(self, workspace_file):
        self.workspace_xml = parsers.get_xml(workspace_file)
        self.aliases = Aliases(workspace_file)
        self.default_project = None

    def __repr__(self):
        return self.workspace_xml

    def __call__(self):
        return self.workspace_xml

    def _join_workspace_path_with_relative_project_path(self, relative_project_path):
        return os.path.abspath(os.path.join(self.workspace_xml.base_dir, relative_project_path))

    def _get_absolute_project_path(self, project_xml):
        project_path = self._parse_project_path(project_xml)
        if not os.path.isabs(project_path):
            return self._join_workspace_path_with_relative_project_path(project_path)
        return project_path

    def _parse_project_path(self, element):
        if element is not None:
            return self.aliases.expand(element.get(path_attr_str))
        else:
            raise InvalidProjectElement("Project element has no name or path attribute")

    def _parse_project_attributes(self, element):
        if element is not None:
            name = element.get(name_attr_str)
            path = element.get(path_attr_str)
            return name, path
        else:
            raise InvalidProjectElement("Project element has no name or path attribute")

    def _get_project_id_from_path(self, element):
        project_path = self._parse_project_path(element)
        return os.path.splitext(os.path.basename(project_path))[0]

    def _parse_project_name(self, element):
        project_id = element.get(name_attr_str)
        if project_id is None:
            project_id = self._get_project_id_from_path(element)
        return project_id

    def _parse_dependent_projects(self, parsed_project_xpath):
        dependencies = []
        for dependency in parsed_project_xpath.findall(dependencies_xpath):
            dependencies.append(self._parse_project_name(dependency))
        return dependencies

    def _update_project_dependencies(self, parsed_project_xpath, projects):
        for project_xml in parsed_project_xpath:
            project_id = self._parse_project_name(project_xml)
            dependencies = self._parse_dependent_projects(project_xml)
            for dependency in dependencies:
                projects[project_id].dependencies.append(projects[dependency])

    def _parse_project(self, project_name, project_xml):
        project_file = self._get_absolute_project_path(project_xml)
        project = Project(project_name, project_file, sdk=self.aliases.sdk, wsroot=self.aliases.wsroot)
        return project

    @staticmethod
    def _project_is_default(element):
        return element.get(default_attr_str) == "yes"

    def _parse_projects_from_xml_source(self, parsed_project_xpath):
        projects = {}
        for project_xml in parsed_project_xpath:
            project_id = self._parse_project_name(project_xml)
            project = self._parse_project(project_id, project_xml)
            if self._project_is_default(project_xml):
                if self.default_project:
                    raise InvalidProjectElement((
                        "More than one default project in: {ws}.\n"
                        "Found: {new}\n"
                        "Already had: {old}\n"
                    ).format(ws=self.workspace_xml.filename, old=self.default_project.name, new=project.name))
                self.default_project = project
            projects[project_id] = project
        if not self.default_project:
            raise ParseError("Default project not found in workspace: {}".format(self.workspace_xml.filename))
        return projects

    def parse(self):
        # This is a 2 stage process: 1. Parse all projects. 2. determine dependent projects

        parsed_project_xpath = self.workspace_xml.parse().findall(project_xpath)
        projects = self._parse_projects_from_xml_source(parsed_project_xpath)
        self._update_project_dependencies(parsed_project_xpath, projects)
        return projects
Пример #12
0
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        msg = ctx.message.content[1:]
        words = msg.split(' ')
        cmd = words[0]
        args = words[1:]
        aliased_command = session.query(Alias).filter(
            Alias.server_id == ctx.guild.id, Alias.alias == cmd).one_or_none()
        if not (aliased_command is None):
            new_msg = ' '.join([aliased_command.command] + args)
            ctx.message.content = new_msg
            await client.get_command(aliased_command.command).invoke(ctx)
        elif '*' in msg:
            # This was just someone using italics
            return
        else:
            await ctx.send(f"Unrecognized command: '{cmd}'")
    else:
        raise error


client.add_cog(Quotes(client))
client.add_cog(ModRoles(client))
client.add_cog(Mutes(client))
client.add_cog(Aliases(client))
Пример #13
0
 def __init__(self, project_file, sdk=None, wsroot=None):
     self.xml = parsers.get_xml(project_file)
     self.aliases = Aliases(project_file, sdk=sdk, wsroot=wsroot)
     self.xml_tree = self.xml.parse()
     self.files = self._parse_files()
     self.configurations = self._parse_configurations()
Пример #14
0
 def __init__(self):
     self.aliases = Aliases()