~allenap/maas/name-constraint-by-name-bug-984633

« back to all changes in this revision

Viewing changes to utilities/rewrite-future-imports

  • Committer: Tarmac
  • Author(s): Gavin Panella
  • Date: 2012-04-17 09:20:48 UTC
  • mfrom: (467.2.6 absolute-imports)
  • Revision ID: ed@carob-20120417092048-7ohy7zw732ofcqwc
[r=julian-edwards][bug=][author=allenap] Ensure that all imports are absolute.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python2.7
 
2
# Copyright 2012 Canonical Ltd.  This software is licensed under the
 
3
# GNU Affero General Public License version 3 (see the file LICENSE).
 
4
 
 
5
"""Ensure that __future__ import lines are populated correctly."""
 
6
 
 
7
from __future__ import (
 
8
    absolute_import,
 
9
    print_function,
 
10
    unicode_literals,
 
11
    )
 
12
 
 
13
__metaclass__ = type
 
14
 
 
15
import re
 
16
import sys
 
17
 
 
18
 
 
19
re_futures = re.compile(
 
20
    r"^(from __future__ import) [(](.*?)[)]", re.DOTALL | re.MULTILINE)
 
21
 
 
22
 
 
23
mandatory_future_imports = frozenset(
 
24
    ("absolute_import", "print_function", "unicode_literals"))
 
25
 
 
26
 
 
27
def replace(match):
 
28
    imports = set().union(
 
29
        (name.strip() for name in match.group(2).split(",")),
 
30
        mandatory_future_imports)
 
31
    imports.discard("")
 
32
    imports = "".join("    %s,\n" % name for name in sorted(imports))
 
33
    return "%s (\n%s    )" % (match.group(1), imports)
 
34
 
 
35
 
 
36
if __name__ == '__main__':
 
37
    for filename in sys.argv[1:]:
 
38
        with open(filename, "rb") as fd:
 
39
            source = fd.read()
 
40
        source = re_futures.sub(replace, source)
 
41
        with open(filename, "wb") as fd:
 
42
            fd.write(source)