minipy icon indicating copy to clipboard operation
minipy copied to clipboard

Add option for minifying standalone modules (which will be called by other code)

Open fiatjaf opened this issue 11 years ago • 5 comments

Using regular --rename option, everything gets renamed, including top level functions and variables. This breaks the file if it is used as a module by other files.

There should be an option for preserving global functions/variables for these use cases.

fiatjaf avatar Sep 23 '13 14:09 fiatjaf

There's the --preserve command-line option, or you can make use of the __all__ list.

gareth-rees avatar Sep 23 '13 14:09 gareth-rees

I wrote a patch, but, knowing you'll find it dirty, I'll just paste here as a suggestion (or for discussion) for later development after your commentary:

def toplevel_names(tree):
    """
    Search tree for FunctionDef and Assign statements with indentation 
    level 0. Return the names of these variables and functions.
    """
    names = set()
    for elem in walk(tree):
        if type(elem) is Global:
            names.update(elem.names)
        if type(elem) is Assign and elem.col_offset == 0:
            names.update([target.id for target in elem.targets\
                                     if hasattr(target, 'id')])
        if type(elem) is FunctionDef and elem.col_offset == 0:
            names.add(elem.name)
    return names

This function is called when this option is selected:

p.add_option('--preservetoplevel', '-m',
             action='store_true', default=False,
             help="preserve top level object names (for use as imported module)"
                  "(implies --rename)")

Like this:

    if opts['rename'] or opts['preservetoplevel']:
        r = reserved_names_in_ast(tree)
        if opts['preserve']:
            r.update(opts['preserve'].split(','))
        if opts['preservetoplevel']:
            toplevel = toplevel_names(tree)
            r.update(toplevel)

fiatjaf avatar Sep 23 '13 14:09 fiatjaf

Whoa, I didn't thought of this simple solution! How do I use the __all__ list? Can I do this without modifying the code?

fiatjaf avatar Sep 23 '13 15:09 fiatjaf

No, you need to explicitly set up an __all__ list.

gareth-rees avatar Sep 23 '13 15:09 gareth-rees

Oh, so it isn't that simple.

fiatjaf avatar Sep 23 '13 15:09 fiatjaf