PyCG 0.0.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
PyCG/__init__.py ADDED
File without changes
PyCG/__main__.py ADDED
@@ -0,0 +1,89 @@
1
+ import argparse
2
+ import json
3
+
4
+ from pycg import formats
5
+ from pycg.pycg import CallGraphGenerator
6
+ from pycg.utils.constants import CALL_GRAPH_OP, KEY_ERR_OP
7
+
8
+
9
+ def main():
10
+ parser = argparse.ArgumentParser()
11
+ parser.add_argument("entry_point", nargs="*", help="Entry points to be processed")
12
+ parser.add_argument(
13
+ "--package", help="Package containing the code to be analyzed", default=None
14
+ )
15
+ parser.add_argument(
16
+ "--fasten",
17
+ help="Produce call graph using the FASTEN format",
18
+ action="store_true",
19
+ default=False,
20
+ )
21
+ parser.add_argument("--product", help="Package name", default="")
22
+ parser.add_argument(
23
+ "--forge", help="Source the product was downloaded from", default=""
24
+ )
25
+ parser.add_argument("--version", help="Version of the product", default="")
26
+ parser.add_argument(
27
+ "--timestamp", help="Timestamp of the package's version", default=0
28
+ )
29
+ parser.add_argument(
30
+ "--max-iter",
31
+ type=int,
32
+ help=(
33
+ "Maximum number of iterations through source code. "
34
+ "If not specified a fix-point iteration will be performed."
35
+ ),
36
+ default=-1,
37
+ )
38
+ parser.add_argument(
39
+ "--operation",
40
+ type=str,
41
+ choices=[CALL_GRAPH_OP, KEY_ERR_OP],
42
+ help=(
43
+ "Operation to perform. Choose "
44
+ + CALL_GRAPH_OP
45
+ + " for call graph generation (default) or "
46
+ + KEY_ERR_OP
47
+ + " for key error detection on dictionaries."
48
+ ),
49
+ default=CALL_GRAPH_OP,
50
+ )
51
+
52
+ parser.add_argument(
53
+ "--as-graph-output", help="Output for the assignment graph", default=None
54
+ )
55
+ parser.add_argument("-o", "--output", help="Output path", default=None)
56
+
57
+ args = parser.parse_args()
58
+
59
+ cg = CallGraphGenerator(
60
+ args.entry_point, args.package, args.max_iter, args.operation
61
+ )
62
+ cg.analyze()
63
+
64
+ if args.operation == CALL_GRAPH_OP:
65
+ if args.fasten:
66
+ formatter = formats.Fasten(
67
+ cg, args.package, args.product, args.forge, args.version, args.timestamp
68
+ )
69
+ else:
70
+ formatter = formats.Simple(cg)
71
+ output = formatter.generate()
72
+ else:
73
+ output = cg.output_key_errs()
74
+
75
+ as_formatter = formats.AsGraph(cg)
76
+
77
+ if args.output:
78
+ with open(args.output, "w+") as f:
79
+ f.write(json.dumps(output))
80
+ else:
81
+ print(json.dumps(output))
82
+
83
+ if args.as_graph_output:
84
+ with open(args.as_graph_output, "w+") as f:
85
+ f.write(json.dumps(as_formatter.generate()))
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
@@ -0,0 +1,23 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ from .as_graph import AsGraph # noqa: F401
22
+ from .fasten import Fasten # noqa: F401
23
+ from .simple import Simple # noqa: F401
@@ -0,0 +1,33 @@
1
+ #
2
+ # Copyright (c) 2021 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ from .base import BaseFormatter
22
+
23
+
24
+ class AsGraph(BaseFormatter):
25
+ def __init__(self, cg_generator):
26
+ self.cg_generator = cg_generator
27
+
28
+ def generate(self):
29
+ graph = self.cg_generator.get_as_graph()
30
+ output = {}
31
+ for key, defi in graph:
32
+ output[key] = list(defi.get_name_pointer().get().copy())
33
+ return output
PyCG/formats/base.py ADDED
@@ -0,0 +1,23 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ class BaseFormatter:
22
+ def generate(self):
23
+ raise NotImplementedError("generate method not implemented in child class")
PyCG/formats/fasten.py ADDED
@@ -0,0 +1,273 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ import os
22
+
23
+ from pkg_resources import Requirement
24
+
25
+ from pycg import utils
26
+
27
+ from .base import BaseFormatter
28
+
29
+
30
+ class Fasten(BaseFormatter):
31
+ def __init__(self, cg_generator, package, product, forge, version, timestamp):
32
+ self.cg_generator = cg_generator
33
+ self.internal_mods = self.cg_generator.output_internal_mods() or {}
34
+ self.external_mods = self.cg_generator.output_external_mods() or {}
35
+ self.classes = self.cg_generator.output_classes() or {}
36
+ self.edges = self.cg_generator.output_edges() or []
37
+ self.functions = self.cg_generator.output_functions() or []
38
+ self.unique = 0
39
+ self.namespace_map = {}
40
+ self.package = package
41
+ self.product = product
42
+ self.forge = forge
43
+ self.version = version
44
+ self.timestamp = timestamp
45
+
46
+ def get_unique_and_increment(self):
47
+ unique = self.unique
48
+ self.unique += 1
49
+ return unique
50
+
51
+ def to_uri(self, modname, name=""):
52
+ cleared = name
53
+ if name:
54
+ if name == modname:
55
+ cleared = ""
56
+ else:
57
+ if not name.startswith(modname + "."):
58
+ raise Exception("name should start with modname", name, modname)
59
+
60
+ cleared = name[(len(modname) + 1) :]
61
+
62
+ suffix = ""
63
+ if name in self.functions:
64
+ suffix = "()"
65
+
66
+ return "/{}/{}{}".format(modname.replace("-", "_"), cleared, suffix)
67
+
68
+ def to_external_uri(self, modname, name=""):
69
+ if modname == utils.constants.BUILTIN_NAME:
70
+ name = name[len(modname) + 1 :]
71
+ modname = ".builtin"
72
+
73
+ return "//{}//{}".format(modname.replace("-", "_"), name)
74
+
75
+ def find_dependencies(self, package_path):
76
+ res = []
77
+ if not package_path:
78
+ return res
79
+ requirements_path = os.path.join(package_path, "requirements.txt")
80
+
81
+ if not os.path.exists(requirements_path):
82
+ return res
83
+
84
+ with open(requirements_path, "r") as f:
85
+ lines = [_l.strip() for _l in f.readlines()]
86
+
87
+ for line in lines:
88
+ if not line:
89
+ continue
90
+
91
+ try:
92
+ req = Requirement.parse(line)
93
+ except ValueError:
94
+ # The specific line in the requirements.txt
95
+ # does not follow the Requirements File Format
96
+ continue
97
+
98
+ specs = req.specs
99
+
100
+ constraints = []
101
+
102
+ def add_range(begin, end):
103
+ if begin and end:
104
+ if begin[1] and end[1]:
105
+ constraints.append("[{}..{}]".format(begin[0], end[0]))
106
+ elif begin[1]:
107
+ constraints.append("[{}..{})".format(begin[0], end[0]))
108
+ elif end[1]:
109
+ constraints.append("({}..{}]".format(begin[0], end[0]))
110
+ else:
111
+ constraints.append("({}..{})".format(begin[0], end[0]))
112
+ elif begin:
113
+ if begin[1]:
114
+ constraints.append("[{}..]".format(begin[0]))
115
+ else:
116
+ constraints.append("({}..]".format(begin[0]))
117
+ elif end:
118
+ if end[1]:
119
+ constraints.append("[..{}]".format(end[0]))
120
+ else:
121
+ constraints.append("[..{})".format(end[0]))
122
+
123
+ begin = None
124
+ end = None
125
+ for key, val in sorted(specs, key=lambda x: x[1]):
126
+ # if begin, then it is already in a range
127
+ if key == "==":
128
+ if begin and end:
129
+ add_range(begin, end)
130
+ begin = None
131
+ end = None
132
+ if not begin:
133
+ constraints.append("[{}]".format(val))
134
+
135
+ if key == ">":
136
+ if end:
137
+ add_range(begin, end)
138
+ end = None
139
+ begin = None
140
+ if not begin:
141
+ begin = (val, False)
142
+ if key == ">=":
143
+ if end:
144
+ add_range(begin, end)
145
+ begin = None
146
+ end = None
147
+ if not begin:
148
+ begin = (val, True)
149
+
150
+ if key == "<":
151
+ end = (val, False)
152
+ if key == "<=":
153
+ end = (val, True)
154
+ add_range(begin, end)
155
+
156
+ res.append({
157
+ "forge": "PyPI", "product": req.name, "constraints": constraints
158
+ })
159
+
160
+ return res
161
+
162
+ def get_internal_modules(self):
163
+ mods = {}
164
+
165
+ for modname, module in self.internal_mods.items():
166
+ name = self.to_uri(modname)
167
+ filename = module["filename"]
168
+ namespaces = module["methods"]
169
+
170
+ mods[name] = {"sourceFile": filename, "namespaces": {}}
171
+
172
+ for namespace, info in namespaces.items():
173
+ namespace_uri = self.to_uri(modname, info["name"])
174
+
175
+ unique = self.get_unique_and_increment()
176
+ mods[name]["namespaces"][unique] = dict(
177
+ namespace=namespace_uri,
178
+ metadata=dict(first=info["first"], last=info["last"]),
179
+ )
180
+ self.namespace_map[namespace_uri] = unique
181
+ mods = self.add_superclasses(mods)
182
+
183
+ return mods
184
+
185
+ def add_superclasses(self, mods):
186
+ for cls_name, cls in self.classes.items():
187
+ cls_uri = self.namespace_map.get(self.to_uri(cls["module"], cls_name))
188
+ mods[self.to_uri(cls["module"])]["namespaces"][cls_uri]["metadata"][
189
+ "superClasses"
190
+ ] = []
191
+ for parent in cls["mro"]:
192
+ if parent == cls_name:
193
+ continue
194
+
195
+ if self.classes.get(parent):
196
+ parent_uri = self.to_uri(self.classes[parent]["module"], parent)
197
+ else:
198
+ parent_mod = parent.split(".")[0]
199
+ parent_uri = self.to_external_uri(parent_mod, parent)
200
+
201
+ mods[self.to_uri(cls["module"])]["namespaces"][cls_uri]["metadata"][
202
+ "superClasses"
203
+ ].append(parent_uri)
204
+
205
+ return mods
206
+
207
+ def create_namespaces_map(self):
208
+ namespaces_maps = [{}, {}]
209
+ for res, hmap in zip(namespaces_maps, [self.internal_mods, self.external_mods]):
210
+ for mod in hmap:
211
+ for namespace in hmap[mod]["methods"]:
212
+ res[namespace] = mod
213
+
214
+ return namespaces_maps
215
+
216
+ def get_external_modules(self):
217
+ mods = {}
218
+ for modname, module in self.external_mods.items():
219
+ name = self.to_external_uri(modname).split("/")[2]
220
+ namespaces = module["methods"]
221
+
222
+ mods[name] = {"sourceFile": "", "namespaces": {}}
223
+
224
+ for namespace, info in namespaces.items():
225
+ # We avoid saving the external module as external method
226
+ if info["name"] != modname:
227
+ namespace_uri = self.to_external_uri(modname, info["name"])
228
+
229
+ unique = self.get_unique_and_increment()
230
+ mods[name]["namespaces"][str(unique)] = dict(
231
+ namespace=namespace_uri, metadata={}
232
+ )
233
+ self.namespace_map[namespace_uri] = unique
234
+ return mods
235
+
236
+ def get_graph(self):
237
+ graph = {"internalCalls": [], "externalCalls": [], "resolvedCalls": []}
238
+
239
+ internal, external = self.create_namespaces_map()
240
+
241
+ for src, dst in self.edges:
242
+ uris = []
243
+ for node in [src, dst]:
244
+ if node in internal:
245
+ mod = internal[node]
246
+ uri = self.to_uri(mod, node)
247
+ uris.append(self.namespace_map.get(uri, uri))
248
+ elif node in external:
249
+ mod = external[node]
250
+ uris.append(self.namespace_map.get(self.to_external_uri(mod, node)))
251
+
252
+ if len(uris) == 2:
253
+ if dst in external:
254
+ graph["externalCalls"].append([str(uris[0]), str(uris[1]), {}])
255
+ else:
256
+ graph["internalCalls"].append([str(uris[0]), str(uris[1]), {}])
257
+ return graph
258
+
259
+ def generate(self):
260
+ return {
261
+ "product": self.product,
262
+ "forge": self.forge,
263
+ "generator": "PyCG",
264
+ "depset": self.find_dependencies(self.package),
265
+ "version": self.version,
266
+ "timestamp": self.timestamp,
267
+ "modules": {
268
+ "internal": self.get_internal_modules(),
269
+ "external": self.get_external_modules(),
270
+ },
271
+ "graph": self.get_graph(),
272
+ "nodes": self.get_unique_and_increment(),
273
+ }
PyCG/formats/simple.py ADDED
@@ -0,0 +1,33 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ from .base import BaseFormatter
22
+
23
+
24
+ class Simple(BaseFormatter):
25
+ def __init__(self, cg_generator):
26
+ self.cg_generator = cg_generator
27
+
28
+ def generate(self):
29
+ output = self.cg_generator.output()
30
+ output_cg = {}
31
+ for node in output:
32
+ output_cg[node] = list(output[node])
33
+ return output_cg
File without changes
@@ -0,0 +1,59 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ class CallGraph(object):
22
+ def __init__(self):
23
+ self.cg = {}
24
+ self.modnames = {}
25
+
26
+ def add_node(self, name, modname=""):
27
+ if not isinstance(name, str):
28
+ raise CallGraphError("Only string node names allowed")
29
+ if not name:
30
+ raise CallGraphError("Empty node name")
31
+
32
+ if name not in self.cg:
33
+ self.cg[name] = set()
34
+ self.modnames[name] = modname
35
+
36
+ if name in self.cg and not self.modnames[name]:
37
+ self.modnames[name] = modname
38
+
39
+ def add_edge(self, src, dest):
40
+ self.add_node(src)
41
+ self.add_node(dest)
42
+ self.cg[src].add(dest)
43
+
44
+ def get(self):
45
+ return self.cg
46
+
47
+ def get_edges(self):
48
+ output = []
49
+ for src in self.cg:
50
+ for dst in self.cg[src]:
51
+ output.append([src, dst])
52
+ return output
53
+
54
+ def get_modules(self):
55
+ return self.modnames
56
+
57
+
58
+ class CallGraphError(Exception):
59
+ pass
@@ -0,0 +1,78 @@
1
+ #
2
+ # Copyright (c) 2020 Vitalis Salis.
3
+ #
4
+ # Licensed to the Apache Software Foundation (ASF) under one
5
+ # or more contributor license agreements. See the NOTICE file
6
+ # distributed with this work for additional information
7
+ # regarding copyright ownership. The ASF licenses this file
8
+ # to you under the Apache License, Version 2.0 (the
9
+ # "License"); you may not use this file except in compliance
10
+ # with the License. You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing,
15
+ # software distributed under the License is distributed on an
16
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17
+ # KIND, either express or implied. See the License for the
18
+ # specific language governing permissions and limitations
19
+ # under the License.
20
+ #
21
+ class ClassManager:
22
+ def __init__(self):
23
+ self.names = {}
24
+
25
+ def get(self, name):
26
+ if name in self.names:
27
+ return self.names[name]
28
+
29
+ def create(self, name, module):
30
+ if name not in self.names:
31
+ cls = ClassNode(name, module)
32
+ self.names[name] = cls
33
+ return self.names[name]
34
+
35
+ def get_classes(self):
36
+ return self.names
37
+
38
+
39
+ class ClassNode:
40
+ def __init__(self, ns, module):
41
+ self.ns = ns
42
+ self.module = module
43
+ self.mro = [ns]
44
+
45
+ def add_parent(self, parent):
46
+ if isinstance(parent, str):
47
+ self.mro.append(parent)
48
+ elif isinstance(parent, list):
49
+ for item in parent:
50
+ self.mro.append(item)
51
+ self.fix_mro()
52
+
53
+ def fix_mro(self):
54
+ new_mro = []
55
+ for idx, item in enumerate(self.mro):
56
+ if self.mro[idx + 1 :].count(item) > 0:
57
+ continue
58
+ new_mro.append(item)
59
+ self.mro = new_mro
60
+
61
+ def get_mro(self):
62
+ return self.mro
63
+
64
+ def get_module(self):
65
+ return self.module
66
+
67
+ def compute_mro(self):
68
+ res = []
69
+ self.mro.reverse()
70
+ for parent in self.mro:
71
+ if parent not in res:
72
+ res.append(parent)
73
+
74
+ res.reverse()
75
+ self.mro = res
76
+
77
+ def clear_mro(self):
78
+ self.mro = [self.ns]