codegraphcontext-rust 0.5.5__cp310-cp310-win_amd64.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.
Files changed (101) hide show
  1. codegraphcontext/__init__.py +2 -0
  2. codegraphcontext/__main__.py +5 -0
  3. codegraphcontext/_cgc_rust.cp310-win_amd64.pyd +0 -0
  4. codegraphcontext/cli/__init__.py +1 -0
  5. codegraphcontext/cli/cli_helpers.py +774 -0
  6. codegraphcontext/cli/config_manager.py +1051 -0
  7. codegraphcontext/cli/main.py +2386 -0
  8. codegraphcontext/cli/registry_commands.py +404 -0
  9. codegraphcontext/cli/setup_macos.py +93 -0
  10. codegraphcontext/cli/setup_wizard.py +991 -0
  11. codegraphcontext/cli/visualizer.py +50 -0
  12. codegraphcontext/core/__init__.py +165 -0
  13. codegraphcontext/core/bundle_registry.py +181 -0
  14. codegraphcontext/core/cgc_bundle.py +858 -0
  15. codegraphcontext/core/cgcignore.py +118 -0
  16. codegraphcontext/core/database.py +273 -0
  17. codegraphcontext/core/database_falkordb.py +480 -0
  18. codegraphcontext/core/database_falkordb_remote.py +199 -0
  19. codegraphcontext/core/database_kuzu.py +636 -0
  20. codegraphcontext/core/falkor_worker.py +132 -0
  21. codegraphcontext/core/jobs.py +132 -0
  22. codegraphcontext/core/watcher.py +260 -0
  23. codegraphcontext/prompts.py +125 -0
  24. codegraphcontext/server.py +471 -0
  25. codegraphcontext/tool_definitions.py +220 -0
  26. codegraphcontext/tools/__init__.py +0 -0
  27. codegraphcontext/tools/advanced_language_query_tool.py +103 -0
  28. codegraphcontext/tools/code_finder.py +1160 -0
  29. codegraphcontext/tools/graph_builder.py +337 -0
  30. codegraphcontext/tools/handlers/analysis_handlers.py +114 -0
  31. codegraphcontext/tools/handlers/indexing_handlers.py +116 -0
  32. codegraphcontext/tools/handlers/management_handlers.py +339 -0
  33. codegraphcontext/tools/handlers/query_handlers.py +83 -0
  34. codegraphcontext/tools/handlers/watcher_handlers.py +83 -0
  35. codegraphcontext/tools/indexing/__init__.py +1 -0
  36. codegraphcontext/tools/indexing/constants.py +25 -0
  37. codegraphcontext/tools/indexing/discovery.py +64 -0
  38. codegraphcontext/tools/indexing/engine.py +109 -0
  39. codegraphcontext/tools/indexing/persistence/__init__.py +3 -0
  40. codegraphcontext/tools/indexing/persistence/parquet_loader.py +643 -0
  41. codegraphcontext/tools/indexing/persistence/writer.py +1114 -0
  42. codegraphcontext/tools/indexing/pipeline.py +171 -0
  43. codegraphcontext/tools/indexing/pre_scan.py +105 -0
  44. codegraphcontext/tools/indexing/resolution/__init__.py +8 -0
  45. codegraphcontext/tools/indexing/resolution/calls.py +253 -0
  46. codegraphcontext/tools/indexing/resolution/inheritance.py +91 -0
  47. codegraphcontext/tools/indexing/sanitize.py +41 -0
  48. codegraphcontext/tools/indexing/schema.py +79 -0
  49. codegraphcontext/tools/indexing/schema_contract.py +44 -0
  50. codegraphcontext/tools/indexing/scip_pipeline.py +140 -0
  51. codegraphcontext/tools/languages/c.py +563 -0
  52. codegraphcontext/tools/languages/cpp.py +616 -0
  53. codegraphcontext/tools/languages/csharp.py +551 -0
  54. codegraphcontext/tools/languages/dart.py +378 -0
  55. codegraphcontext/tools/languages/elixir.py +460 -0
  56. codegraphcontext/tools/languages/go.py +499 -0
  57. codegraphcontext/tools/languages/haskell.py +426 -0
  58. codegraphcontext/tools/languages/java.py +500 -0
  59. codegraphcontext/tools/languages/javascript.py +589 -0
  60. codegraphcontext/tools/languages/kotlin.py +640 -0
  61. codegraphcontext/tools/languages/perl.py +260 -0
  62. codegraphcontext/tools/languages/php.py +519 -0
  63. codegraphcontext/tools/languages/python.py +576 -0
  64. codegraphcontext/tools/languages/ruby.py +537 -0
  65. codegraphcontext/tools/languages/rust.py +295 -0
  66. codegraphcontext/tools/languages/scala.py +519 -0
  67. codegraphcontext/tools/languages/swift.py +491 -0
  68. codegraphcontext/tools/languages/typescript.py +575 -0
  69. codegraphcontext/tools/languages/typescriptjsx.py +151 -0
  70. codegraphcontext/tools/package_resolver.py +472 -0
  71. codegraphcontext/tools/query_tool_languages/c_toolkit.py +5 -0
  72. codegraphcontext/tools/query_tool_languages/cpp_toolkit.py +87 -0
  73. codegraphcontext/tools/query_tool_languages/csharp_toolkit.py +5 -0
  74. codegraphcontext/tools/query_tool_languages/dart_toolkit.py +5 -0
  75. codegraphcontext/tools/query_tool_languages/go_toolkit.py +5 -0
  76. codegraphcontext/tools/query_tool_languages/haskell_toolkit.py +5 -0
  77. codegraphcontext/tools/query_tool_languages/java_toolkit.py +5 -0
  78. codegraphcontext/tools/query_tool_languages/javascript_toolkit.py +5 -0
  79. codegraphcontext/tools/query_tool_languages/perl_toolkit.py +5 -0
  80. codegraphcontext/tools/query_tool_languages/python_toolkit.py +5 -0
  81. codegraphcontext/tools/query_tool_languages/ruby_toolkit.py +5 -0
  82. codegraphcontext/tools/query_tool_languages/rust_toolkit.py +5 -0
  83. codegraphcontext/tools/query_tool_languages/scala_toolkit.py +5 -0
  84. codegraphcontext/tools/query_tool_languages/swift_toolkit.py +5 -0
  85. codegraphcontext/tools/query_tool_languages/typescript_toolkit.py +5 -0
  86. codegraphcontext/tools/scip_indexer.py +467 -0
  87. codegraphcontext/tools/scip_pb2.py +2455 -0
  88. codegraphcontext/tools/system.py +133 -0
  89. codegraphcontext/tools/tree_sitter_parser.py +103 -0
  90. codegraphcontext/utils/debug_log.py +90 -0
  91. codegraphcontext/utils/path_ignore.py +55 -0
  92. codegraphcontext/utils/repo_path.py +27 -0
  93. codegraphcontext/utils/tree_sitter_manager.py +285 -0
  94. codegraphcontext/utils/visualize_graph.py +0 -0
  95. codegraphcontext/viz/server.py +282 -0
  96. codegraphcontext_rust-0.5.5.dist-info/METADATA +537 -0
  97. codegraphcontext_rust-0.5.5.dist-info/RECORD +101 -0
  98. codegraphcontext_rust-0.5.5.dist-info/WHEEL +4 -0
  99. codegraphcontext_rust-0.5.5.dist-info/entry_points.txt +3 -0
  100. codegraphcontext_rust-0.5.5.dist-info/licenses/LICENSE +21 -0
  101. codegraphcontext_rust-0.5.5.dist-info/sboms/cgc-python.cyclonedx.json +2333 -0
@@ -0,0 +1,118 @@
1
+ from pathlib import Path
2
+ from typing import Iterable, Optional, Tuple
3
+ from pathspec import PathSpec
4
+
5
+
6
+ def _resolve_explicit_path(ignore_root: Path, explicit_path: Optional[str]) -> Optional[Path]:
7
+ """Resolve an explicit .cgcignore path relative to *ignore_root*."""
8
+ if not explicit_path:
9
+ return None
10
+
11
+ candidate = Path(explicit_path)
12
+ if not candidate.is_absolute():
13
+ candidate = (ignore_root / candidate).resolve()
14
+ return candidate
15
+
16
+ def parse_cgcignore_lines(lines: Iterable[str]) -> list[str]:
17
+ """Return valid ignore patterns from raw .cgcignore lines.
18
+
19
+ Valid patterns are non-empty lines that do not start with '#'.
20
+ """
21
+ patterns: list[str] = []
22
+ for raw_line in lines:
23
+ line = raw_line.strip()
24
+ if not line or line.startswith("#"):
25
+ continue
26
+ patterns.append(line)
27
+ return patterns
28
+
29
+
30
+ def find_cgcignore(ignore_root: Path, explicit_path: Optional[str] = None) -> Optional[Path]:
31
+ """Find a repository-local .cgcignore, with explicit path fallback."""
32
+
33
+ # Search parent folders only within the current git worktree. If the
34
+ # indexed path is outside a git repo (e.g. /tmp test dirs), avoid crawling
35
+ # up to filesystem-wide locations like /tmp/.cgcignore.
36
+ git_root: Optional[Path] = None
37
+ probe = ignore_root
38
+ while True:
39
+ if (probe / ".git").exists():
40
+ git_root = probe
41
+ break
42
+ if probe.parent == probe:
43
+ break
44
+ probe = probe.parent
45
+
46
+ curr = ignore_root
47
+ while True:
48
+ candidate = curr / ".cgcignore"
49
+ if candidate.exists():
50
+ return candidate
51
+
52
+ if git_root is None:
53
+ return None
54
+
55
+ if curr == git_root:
56
+ break
57
+
58
+ curr = curr.parent
59
+
60
+ explicit_candidate = _resolve_explicit_path(ignore_root, explicit_path)
61
+ if explicit_candidate and explicit_candidate.exists():
62
+ return explicit_candidate
63
+ return None
64
+
65
+ def ensure_default_cgcignore(path: Path, default_patterns: list[str]) -> None:
66
+ """Create a .cgcignore file with default patterns when it does not exist."""
67
+ path.parent.mkdir(parents=True, exist_ok=True)
68
+ content = "# Auto-generated by CodeGraphContext\n"
69
+ content += "# Default ignore patterns for binary/media files\n"
70
+ content += "# Add your own patterns below\n\n"
71
+ content += "\n".join(default_patterns) + "\n"
72
+ path.write_text(content, encoding="utf-8")
73
+
74
+
75
+ def read_cgcignore_patterns(path: Path, default_patterns: list[str]) -> list[str]:
76
+ """Read .cgcignore patterns and merge them with defaults.
77
+
78
+ Empty lines and comment lines are ignored.
79
+ """
80
+ if not path.exists():
81
+ return list(default_patterns)
82
+
83
+ user_patterns = parse_cgcignore_lines(path.read_text(encoding="utf-8").splitlines())
84
+ # User patterns first so explicit repo rules take precedence.
85
+ return user_patterns + list(default_patterns)
86
+
87
+ def build_ignore_spec(
88
+ ignore_root: Path,
89
+ default_patterns: list[str],
90
+ explicit_path: Optional[str] = None,
91
+ ) -> Tuple[PathSpec, Optional[Path]]:
92
+ """Build PathSpec using merged default + user .cgcignore patterns.
93
+
94
+ Returns the compiled spec and the discovered/created .cgcignore path.
95
+ """
96
+ local_cgcignore_path = find_cgcignore(ignore_root, explicit_path=None)
97
+ explicit_cgcignore_path = _resolve_explicit_path(ignore_root, explicit_path)
98
+
99
+ if local_cgcignore_path is None:
100
+ local_cgcignore_path = ignore_root / ".cgcignore"
101
+ ensure_default_cgcignore(local_cgcignore_path, default_patterns)
102
+
103
+ merged_user_patterns: list[str] = []
104
+ merged_user_patterns.extend(
105
+ parse_cgcignore_lines(local_cgcignore_path.read_text(encoding="utf-8").splitlines())
106
+ )
107
+
108
+ if (
109
+ explicit_cgcignore_path
110
+ and explicit_cgcignore_path.exists()
111
+ and explicit_cgcignore_path != local_cgcignore_path
112
+ ):
113
+ merged_user_patterns.extend(
114
+ parse_cgcignore_lines(explicit_cgcignore_path.read_text(encoding="utf-8").splitlines())
115
+ )
116
+
117
+ all_patterns = merged_user_patterns + list(default_patterns)
118
+ return PathSpec.from_lines("gitwildmatch", all_patterns), local_cgcignore_path
@@ -0,0 +1,273 @@
1
+ # src/codegraphcontext/core/database.py
2
+ """
3
+ This module provides a thread-safe singleton manager for the Neo4j database connection.
4
+ """
5
+ import os
6
+ import re
7
+ import threading
8
+ from typing import Optional, Tuple
9
+ from neo4j import GraphDatabase, Driver
10
+
11
+ from codegraphcontext.utils.debug_log import debug_log, info_logger, error_logger, warning_logger
12
+
13
+ class Neo4jDriverWrapper:
14
+ """
15
+ A simple wrapper around the Neo4j Driver to inject a database name into session() calls.
16
+ """
17
+ def __init__(self, driver: Driver, database: str = None):
18
+ self._driver = driver
19
+ self._database = database
20
+
21
+ def session(self, **kwargs):
22
+ """Proxy method to get a session from the underlying driver."""
23
+ if self._database and 'database' not in kwargs:
24
+ kwargs["database"] = self._database
25
+ return self._driver.session(**kwargs)
26
+
27
+ def close(self):
28
+ """Proxy method to close the underlying driver."""
29
+ self._driver.close()
30
+
31
+ class DatabaseManager:
32
+ """
33
+ Manages the Neo4j database driver as a singleton to ensure only one
34
+ connection pool is created and shared across the application.
35
+
36
+ This pattern is crucial for performance and resource management in a
37
+ multi-threaded or asynchronous application.
38
+ """
39
+ _instance = None
40
+ _driver: Optional[Driver] = None
41
+ _lock = threading.Lock() # Lock to ensure thread-safe initialization.
42
+
43
+ def __new__(cls):
44
+ """Standard singleton pattern implementation."""
45
+ if cls._instance is None:
46
+ with cls._lock:
47
+ # Double-check locking to prevent race conditions.
48
+ if cls._instance is None:
49
+ cls._instance = super(DatabaseManager, cls).__new__(cls)
50
+ return cls._instance
51
+
52
+ def __init__(self):
53
+ """
54
+ Initializes the manager by reading credentials from environment variables.
55
+ The `_initialized` flag prevents re-initialization on subsequent calls.
56
+ """
57
+ if hasattr(self, '_initialized'):
58
+ return
59
+
60
+ self.neo4j_uri = os.getenv('NEO4J_URI')
61
+ self.neo4j_username = os.getenv('NEO4J_USERNAME', 'neo4j')
62
+ self.neo4j_password = os.getenv('NEO4J_PASSWORD')
63
+ self.neo4j_database = os.getenv('NEO4J_DATABASE') # Optional, if not set, will use default database configured in Neo4j
64
+ self._initialized = True
65
+
66
+ def get_driver(self) -> Driver:
67
+ """
68
+ Gets the Neo4j driver instance, creating it if it doesn't exist.
69
+ This method is thread-safe.
70
+
71
+ Raises:
72
+ ValueError: If Neo4j credentials are not set in environment variables.
73
+
74
+ Returns:
75
+ The a wrapper for Neo4j Driver instance.
76
+ """
77
+ if self._driver is None:
78
+ with self._lock:
79
+ if self._driver is None:
80
+ # Ensure all necessary credentials are provided.
81
+ if not all([self.neo4j_uri, self.neo4j_username, self.neo4j_password]):
82
+ raise ValueError(
83
+ "Neo4j credentials must be set via environment variables:\n"
84
+ "- NEO4J_URI\n"
85
+ "- NEO4J_USERNAME\n"
86
+ "- NEO4J_PASSWORD"
87
+ )
88
+
89
+ #validating the config before creating the driver/attempting connection
90
+ is_valid, validation_error = self.validate_config(
91
+ self.neo4j_uri,
92
+ self.neo4j_username,
93
+ self.neo4j_password
94
+ )
95
+
96
+ if not is_valid:
97
+ error_logger(f"Configuration validation failed: {validation_error}")
98
+ raise ValueError(validation_error)
99
+
100
+ info_logger(f"Creating Neo4j driver connection to {self.neo4j_uri}")
101
+ self._driver = GraphDatabase.driver(
102
+ self.neo4j_uri,
103
+ auth=(self.neo4j_username, self.neo4j_password)
104
+ )
105
+ # Test the connection immediately to fail fast if credentials are wrong.
106
+ try:
107
+ with self._driver.session() as session:
108
+ session.run("RETURN 1").consume()
109
+ info_logger("Neo4j connection established successfully")
110
+ except Exception as e:
111
+ # Use detailed error messages from test_connection
112
+ _, detailed_error = self.test_connection(
113
+ self.neo4j_uri,
114
+ self.neo4j_username,
115
+ self.neo4j_password
116
+ )
117
+ error_logger(f"Failed to connect to Neo4j: {e}")
118
+ if self._driver:
119
+ self._driver.close()
120
+ self._driver = None
121
+ raise
122
+ return Neo4jDriverWrapper(self._driver, database=self.neo4j_database)
123
+
124
+ def close_driver(self):
125
+ """Closes the Neo4j driver connection if it exists."""
126
+ if self._driver is not None:
127
+ with self._lock:
128
+ if self._driver is not None:
129
+ info_logger("Closing Neo4j driver")
130
+ self._driver.close()
131
+ self._driver = None
132
+
133
+ def is_connected(self) -> bool:
134
+ """Checks if the database connection is currently active."""
135
+ if self._driver is None:
136
+ return False
137
+ try:
138
+ session_kwargs = {}
139
+ if self.neo4j_database:
140
+ session_kwargs['database'] = self.neo4j_database
141
+ with self._driver.session(**session_kwargs) as session:
142
+ session.run("RETURN 1").consume()
143
+ return True
144
+ except Exception:
145
+ return False
146
+
147
+ def get_backend_type(self) -> str:
148
+ """Returns the database backend type."""
149
+ return 'neo4j'
150
+
151
+
152
+ @staticmethod
153
+ def validate_config(uri: str, username: str, password: str) -> Tuple[bool, Optional[str]]:
154
+ """
155
+ Validates Neo4j configuration parameters.
156
+
157
+ Returns:
158
+ Tuple[bool, Optional[str]]: (is_valid, error_message)
159
+ """
160
+ # Validate URI format
161
+ # Modified regex to make port optional "(:\\d+)?"
162
+ uri_pattern = r'^(neo4j|neo4j\+s|neo4j\+ssc|bolt|bolt\+s|bolt\+ssc)://[^:]+(:\d+)?$'
163
+ if not re.match(uri_pattern, uri):
164
+ return False, (
165
+ "Invalid Neo4j URI format.\n"
166
+ "Expected format: neo4j://host:port or bolt://host:port\n"
167
+ "Example: neo4j://localhost:7687\n"
168
+ "Common mistake: Missing 'neo4j://' or 'bolt://' prefix"
169
+ )
170
+
171
+ # Validate username
172
+ if not username or len(username.strip()) == 0:
173
+ return False, (
174
+ "Username cannot be empty.\n"
175
+ "Default Neo4j username is 'neo4j'"
176
+ )
177
+
178
+ # Validate password
179
+ if not password or len(password.strip()) == 0:
180
+ return False, (
181
+ "Password cannot be empty.\n"
182
+ "Tip: If you just set up Neo4j, use the password you configured during setup"
183
+ )
184
+
185
+ return True, None
186
+
187
+ @staticmethod
188
+ def test_connection(uri: str, username: str, password: str, database: str=None) -> Tuple[bool, Optional[str]]:
189
+ """
190
+ Tests the Neo4j database connection.
191
+
192
+ Returns:
193
+ Tuple[bool, Optional[str]]: (is_connected, error_message)
194
+ """
195
+ try:
196
+ from neo4j import GraphDatabase
197
+ import socket
198
+
199
+ # First, test if the host is reachable
200
+ try:
201
+ # Extract host and port from URI
202
+ host_port = uri.split('://')[1]
203
+ if ':' in host_port:
204
+ host = host_port.split(':')[0]
205
+ port = int(host_port.split(':')[1])
206
+ else:
207
+ host = host_port
208
+ port = 7687 # Default Neo4j port
209
+
210
+ # Test socket connection
211
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
212
+ sock.settimeout(5)
213
+ result = sock.connect_ex((host, port))
214
+ sock.close()
215
+
216
+ if result != 0:
217
+ return False, (
218
+ f"Cannot reach Neo4j server at {host}:{port}\n"
219
+ "Troubleshooting:\n"
220
+ " • Is Neo4j running? Check with: docker ps (for Docker)\n"
221
+ " • Is the port correct? Default is 7687\n"
222
+ " • Is there a firewall blocking the connection?\n"
223
+ f" • Try: docker compose up -d (if using Docker)"
224
+ )
225
+ except Exception as e:
226
+ return False, f"Error parsing URI or checking connectivity: {str(e)}"
227
+
228
+ # Now test Neo4j authentication
229
+ driver = GraphDatabase.driver(uri, auth=(username, password))
230
+
231
+ session_kwargs = {}
232
+ if database:
233
+ session_kwargs['database'] = database # Pass database to session if provided
234
+ with driver.session(**session_kwargs) as session:
235
+ result = session.run("RETURN 'Connection successful' as status")
236
+ result.single()
237
+
238
+ driver.close()
239
+ return True, None
240
+
241
+ except Exception as e:
242
+ error_msg = str(e).lower()
243
+
244
+ # Provide specific error messages for common issues
245
+ if "authentication" in error_msg or "unauthorized" in error_msg:
246
+ return False, (
247
+ "Authentication failed - Invalid username or password\n"
248
+ "Troubleshooting:\n"
249
+ " • Default username is 'neo4j'\n"
250
+ " • Did you change the password during initial setup?\n"
251
+ " • If you forgot the password, you may need to reset Neo4j:\n"
252
+ " - Stop: docker compose down\n"
253
+ " - Remove data: docker volume rm <volume_name>\n"
254
+ " - Restart: docker compose up -d"
255
+ )
256
+ elif "serviceunAvailable" in error_msg or "failed to establish connection" in error_msg:
257
+ return False, (
258
+ "Neo4j service is not available\n"
259
+ "Troubleshooting:\n"
260
+ " • Is Neo4j running? Check: docker ps\n"
261
+ " • Start Neo4j: docker compose up -d\n"
262
+ " • Check logs: docker compose logs neo4j\n"
263
+ " • Wait 30-60 seconds after starting for Neo4j to initialize"
264
+ )
265
+ elif "unable to retrieve routing information" in error_msg:
266
+ return False, (
267
+ "Cannot connect to Neo4j routing\n"
268
+ "Troubleshooting:\n"
269
+ " • Try using 'bolt://' instead of 'neo4j://' in the URI\n"
270
+ " • Example: bolt://localhost:7687"
271
+ )
272
+ else:
273
+ return False, f"Connection failed: {str(e)}"