-
Notifications
You must be signed in to change notification settings - Fork 38
/
listperms.py
110 lines (89 loc) · 2.94 KB
/
listperms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env python
import logging
import os
import sys
from argparse import ArgumentParser
import django
from django.apps import apps
from django.contrib.auth import get_permission_codename
logger = logging.getLogger(__name__)
# stolen from django.contrib.auth.management.__init__
def _get_all_permissions(opts):
"""
Return (codename, name) for all permissions in the given opts.
"""
return [*_get_builtin_permissions(opts), *opts.permissions]
def _get_builtin_permissions(opts):
"""
Return (codename, name) for all autogenerated permissions.
By default, this is ('add', 'change', 'delete', 'view')
"""
perms = []
for action in opts.default_permissions:
perms.append(
(
get_permission_codename(action, opts),
'Can %s %s' % (action, opts.verbose_name_raw),
)
)
return perms
if __name__ == '__main__':
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
django.setup()
parser = ArgumentParser()
parser.add_argument(
'--validate',
action='store_true',
help='Throws an error if the generated permissions list does not match the current one',
)
parser.add_argument(
'--file',
default=os.path.join(
os.path.dirname(__file__), 'bundles', 'common', 'Permissions.ts'
),
help='The file to compare/store the generated results in',
)
parser.add_argument(
'-v',
'--verbose',
action='count',
default=0,
)
parsed = parser.parse_args(sys.argv[1:])
if parsed.verbose >= 2:
level = logging.DEBUG
elif parsed.verbose == 1:
level = logging.INFO
else:
level = logging.WARNING
logging.basicConfig(level=level)
tracker = apps.get_app_config('tracker')
perms = set()
for model in tracker.get_models():
perms |= {f'tracker.{p[0]}' for p in _get_all_permissions(model._meta)}
logger.debug('--PERMISSIONS LIST--')
logger.debug(perms)
perm_list = '\n | '.join(f"'{p}'" for p in sorted(perms))
result = f"""// autogenerated
export type Permission =
| {perm_list};
"""
if parsed.validate:
with open(parsed.file) as infile:
existing = infile.read()
if result != existing:
logger.debug('--EXPECTED--')
logger.debug(repr(result))
logger.debug('--ACTUAL--')
logger.debug(repr(existing))
logger.error(
'Existing permissions did not match generated permissions, re-run listperms.py before commit'
)
sys.exit(1)
logger.info(f'Permissions validated from {os.path.relpath(parsed.file)}')
else:
with open(parsed.file, 'w') as outfile:
outfile.write(result)
logger.info(
f'Wrote {len(perms)} permission(s) to {os.path.relpath(parsed.file)}'
)