cpg2py 1.0.0__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.
cpg2py/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ from pathlib import Path
2
+ from csv import DictReader
3
+ from .cpg import _Graph
4
+ from .abc import *
5
+
6
+ def cpg_graph(node_csv: Path, edge_csv: Path) -> _Graph:
7
+ storage = Storage()
8
+ with open(node_csv, 'r') as n_file:
9
+ reader = DictReader(n_file, delimiter='\t')
10
+ for node_props in reader:
11
+ nid = node_props.get("id:int", None)
12
+ if nid is None: node_props.get("id")
13
+ if not storage.add_node(nid):
14
+ print(f"Node {nid} already exists in the graph")
15
+ if not storage.set_node_props(nid, node_props):
16
+ print(f"Failed to set properties for node {nid}")
17
+ with open(edge_csv, 'r') as f:
18
+ reader = DictReader(f, delimiter='\t')
19
+ for edge_props in reader:
20
+ f_nid = str(edge_props.get("start", None) )
21
+ if f_nid is None: f_nid = str(edge_props.get("start:str"))
22
+ t_nid = str(edge_props.get("end", None))
23
+ if t_nid is None: t_nid = str(edge_props.get("end:str"))
24
+ e_type = str(edge_props.get("type", None))
25
+ if e_type is None: e_type = str(edge_props.get("type:str"))
26
+ edge_id = (f_nid, t_nid, e_type)
27
+ if not storage.add_edge(edge_id):
28
+ print(f"Edge {f_nid} -> {t_nid} already exists in the graph")
29
+ if not storage.set_edge_props(edge_id, edge_props):
30
+ print(f"Failed to set properties for edge {edge_id}")
31
+ return _Graph(storage)
32
+
33
+
34
+ __all__ = ['cpg_graph', 'AbcGraphQuerier', 'AbcNodeQuerier', 'AbcEdgeQuerier', 'Storage']
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Yichao Xu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,261 @@
1
+ Metadata-Version: 2.2
2
+ Name: cpg2py
3
+ Version: 1.0.0
4
+ Summary: A graph-based data structure designed for querying CSV files in Joern format in Python
5
+ Home-page: https://github.com/YichaoXu/cpg2py
6
+ Author: Yichao Xu
7
+ Author-email: Yichao Xu <yxu166@jhu.edu>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2025 Yichao Xu
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+
30
+ Project-URL: Homepage, https://github.com/YichaoXu/cpg2py
31
+ Project-URL: Repository, https://github.com/YichaoXu/cpg2py
32
+ Keywords: Joern,CPG,Graph,CSV
33
+ Requires-Python: >=3.6
34
+ Description-Content-Type: text/markdown
35
+ License-File: LICENSE
36
+ Dynamic: author
37
+ Dynamic: home-page
38
+ Dynamic: requires-python
39
+
40
+ # **cpg2py: Graph-Based Query Engine for Joern CSV Files**
41
+
42
+ `cpg2py` is a Python library that provides a lightweight **graph-based query engine** for analyzing **Code Property Graphs (CPG)** extracted from Joern CSV files. The library offers an **abstract base class (ABC) architecture**, allowing users to extend and implement their own custom graph queries.
43
+
44
+ ---
45
+
46
+ ## **🚀 Features**
47
+
48
+ - **MultiDiGraph Representation**: A directed multi-graph with support for multiple edges between nodes.
49
+ - **CSV-Based Graph Construction**: Reads `nodes.csv` and `rels.csv` to construct a graph structure.
50
+ - **Extensible Abstract Base Classes (ABC)**:
51
+ - `AbcGraphQuerier` for implementing **custom graph queries**.
52
+ - `AbcNodeQuerier` for interacting with **nodes**.
53
+ - `AbcEdgeQuerier` for interacting with **edges**.
54
+ - **Built-in Query Mechanisms**:
55
+ - **Retrieve all edges**.
56
+ - **Get incoming (**``**) and outgoing (**``**) edges of a node**.
57
+ - **Find successors (**``**) and predecessors (**``**)**.
58
+ - **Traverse AST, Control Flow, and Data Flow Graphs**.
59
+
60
+ ---
61
+
62
+ ## **📚 Installation**
63
+
64
+ To install the package, use:
65
+
66
+ ```bash
67
+ pip install git+https://github.com/YichaoXu/cpg2py.git
68
+ ```
69
+
70
+ Or clone the pip repository:
71
+
72
+ ```bash
73
+ pip install cpg2py
74
+ ```
75
+
76
+ ---
77
+
78
+ ## **📂 File Structure**
79
+
80
+ - **`nodes.csv`** (Example):
81
+ ```csv
82
+ id:int labels:label type flags:string_array lineno:int code childnum:int funcid:int classname namespace endlineno:int name doccomment
83
+ 0 Filesystem Directory "input"
84
+ 1 Filesystem File "example.php"
85
+ 2 AST AST_TOPLEVEL TOPLEVEL_FILE 1 "" 25 "/input/example.php"
86
+
87
+ ````
88
+ - **`rels.csv`** (Example):
89
+ ```csv
90
+ start end type
91
+ 2 3 ENTRY
92
+ 2 4 EXIT
93
+ 6 7 ENTRY
94
+ 6 9 PARENT_OF
95
+ ````
96
+
97
+ ---
98
+
99
+ ## **📚 Usage**
100
+
101
+ ### **1️⃣ Load Graph from Joern CSVs**
102
+
103
+ ```python
104
+ from cpg2py import cpg_graph
105
+
106
+ # Load graph from CSV files
107
+ graph = cpg_graph("nodes.csv", "rels.csv")
108
+ ```
109
+
110
+ ---
111
+
112
+ ### **2️⃣ Query Nodes & Edges**
113
+
114
+ ```python
115
+ # Get a specific node
116
+ node = graph.node("2")
117
+ print(node.name, node.type) # Example output: "/tmp/example.php" AST_TOPLEVEL
118
+
119
+ # Get a specific edge
120
+ edge = graph.edge("2", "3", "ENTRY")
121
+ print(edge.type) # Output: ENTRY
122
+ ```
123
+
124
+ ---
125
+
126
+ ### **3️⃣ Get Node Connections**
127
+
128
+ ```python
129
+ # Get all outgoing edges from a node
130
+ outgoing_edges = graph.succ(node)
131
+ for out_node in outgoing_edges:
132
+ print(out_node.id, out_node.name)
133
+
134
+ # Get all incoming edges to a node
135
+ incoming_edges = graph.prev(node)
136
+ for in_node in incoming_edges:
137
+ print(in_node.id, in_node.name)
138
+ ```
139
+
140
+ ---
141
+
142
+ ### **4️⃣ AST and Flow Queries**
143
+
144
+ ```python
145
+ # Get top-level file node for a given node
146
+ top_file = graph.topfile_node("5")
147
+ print(top_file.name) # Output: "example.php"
148
+
149
+ # Get child nodes in the AST hierarchy
150
+ children = graph.children(node)
151
+ print([child.id for child in children])
152
+
153
+ # Get data flow successors
154
+ flow_successors = graph.flow_to(node)
155
+ print([succ.id for succ in flow_successors])
156
+ ```
157
+
158
+ ---
159
+
160
+ ## **🛠 Abstract Base Classes (ABC)**
161
+
162
+ The following abstract base classes (`ABC`) provide interfaces for extending **node**, **edge**, and **graph** querying behavior.
163
+
164
+ ---
165
+
166
+ ### **🔹 AbcNodeQuerier (Abstract Node Interface)**
167
+
168
+ This class defines how nodes interact with the graph storage.
169
+
170
+ ```python
171
+ from cpg2py.abc import AbcNodeQuerier
172
+
173
+ class MyNodeQuerier(AbcNodeQuerier):
174
+ def __init__(self, graph, nid):
175
+ super().__init__(graph, nid)
176
+
177
+ @property
178
+ def name(self):
179
+ return self.get_property("name")
180
+ ```
181
+
182
+ ---
183
+
184
+ ### **🔹 AbcEdgeQuerier (Abstract Edge Interface)**
185
+
186
+ Defines the querying mechanisms for edges in the graph.
187
+
188
+ ```python
189
+ from cpg2py.abc import AbcEdgeQuerier
190
+
191
+ class MyEdgeQuerier(AbcEdgeQuerier):
192
+ def __init__(self, graph, f_nid, t_nid, e_type):
193
+ super().__init__(graph, f_nid, t_nid, e_type)
194
+
195
+ @property
196
+ def type(self):
197
+ return self.get_property("type")
198
+ ```
199
+
200
+ ---
201
+
202
+ ### **🔹 AbcGraphQuerier (Abstract Graph Interface)**
203
+
204
+ This class provides an interface for implementing custom graph query mechanisms.
205
+
206
+ ```python
207
+ from cpg2py.abc import AbcGraphQuerier
208
+
209
+ class MyGraphQuerier(AbcGraphQuerier):
210
+ def node(self, nid: str):
211
+ return MyNodeQuerier(self.storage, nid)
212
+
213
+ def edge(self, fid, tid, eid):
214
+ return MyEdgeQuerier(self.storage, fid, tid, eid)
215
+ ```
216
+
217
+ ---
218
+
219
+ ## **🔍 Querying The Graph**
220
+
221
+ After implementing the abstract classes, you can perform advanced queries:
222
+
223
+ ```python
224
+ graph = MyGraphQuerier(storage)
225
+
226
+ # Query node properties
227
+ node = graph.node("5")
228
+ print(node.name) # Example Output: "main"
229
+
230
+ # Query edge properties
231
+ edge = graph.edge("5", "6", "FLOWS_TO")
232
+ print(edge.type) # Output: "FLOWS_TO"
233
+ ```
234
+
235
+ ---
236
+
237
+ ## **🐝 API Reference**
238
+
239
+ For a more detail APIs document please see our [APIs doc](docs/APIs.md)
240
+
241
+ - **Graph Functions**:
242
+ - `cpg_graph(node_csv, edge_csv)`: Loads graph from CSV files.
243
+ - `graph.node(nid)`: Retrieves a node by ID.
244
+ - `graph.edge(fid, tid, eid)`: Retrieves an edge.
245
+ - `graph.succ(node)`: Gets successor nodes.
246
+ - `graph.prev(node)`: Gets predecessor nodes.
247
+ - **Node Properties**:
248
+ - `.name`: Node name.
249
+ - `.type`: Node type.
250
+ - `.line_num`: Source code line number.
251
+ - **Edge Properties**:
252
+ - `.start`: Edge start node.
253
+ - `.end`: Edge end node.
254
+ - `.type`: Edge type.
255
+
256
+ ---
257
+
258
+ ## **🌟 License**
259
+
260
+ This project is licensed under the **MIT License**.
261
+
@@ -0,0 +1,6 @@
1
+ cpg2py/__init__.py,sha256=bjd1EjYmNa0N8DW4tSQg-YpzzkqgtBVR2FrgDZReY10,1557
2
+ cpg2py-1.0.0.dist-info/LICENSE,sha256=vTjbt7iL1hUilI8E87FoQerEDa9nbpeip26iA6bguHI,1066
3
+ cpg2py-1.0.0.dist-info/METADATA,sha256=ESCorHBwLXChyZNEH5MdekKZiD59VFc1g6IYs8-YsfM,7077
4
+ cpg2py-1.0.0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
5
+ cpg2py-1.0.0.dist-info/top_level.txt,sha256=xDY8faKh5Rczvsqb5Jt9Sq-Y7EOImh7jh-m1oVTnH5k,7
6
+ cpg2py-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ cpg2py