Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
fiatjaf opened this issue Sep 23, 2013 · 5 comments

Comments

@fiatjaf
Copy link

fiatjaf commented Sep 23, 2013

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.

@gareth-rees
Copy link
Owner

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

@fiatjaf
Copy link
Author

fiatjaf commented Sep 23, 2013

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
Copy link
Author

fiatjaf commented Sep 23, 2013

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

@gareth-rees
Copy link
Owner

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

@fiatjaf
Copy link
Author

fiatjaf commented Sep 23, 2013

Oh, so it isn't that simple.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants