This is page 1 of 14. Use http://codebase.md/shashankss1205/codegraphcontext?page={x} to view the full context.
# Directory Structure
```
├── .github
│ └── workflows
│ ├── e2e-tests.yml
│ ├── post_discord_invite.yml
│ ├── test.yml
│ └── update-contributors.yml
├── .gitignore
├── CONTRIBUTING.md
├── contributors.md
├── docs
│ ├── docs
│ │ ├── architecture.md
│ │ ├── cli.md
│ │ ├── contributing_languages.md
│ │ ├── contributing.md
│ │ ├── cookbook.md
│ │ ├── core.md
│ │ ├── future_work.md
│ │ ├── images
│ │ │ ├── 1.png
│ │ │ ├── 11.png
│ │ │ ├── 12.png
│ │ │ ├── 13.png
│ │ │ ├── 14.png
│ │ │ ├── 16.png
│ │ │ ├── 19.png
│ │ │ ├── 2.png
│ │ │ ├── 20.png
│ │ │ ├── 21.png
│ │ │ ├── 22.png
│ │ │ ├── 23.png
│ │ │ ├── 24.png
│ │ │ ├── 26.png
│ │ │ ├── 28.png
│ │ │ ├── 29.png
│ │ │ ├── 3.png
│ │ │ ├── 30.png
│ │ │ ├── 31.png
│ │ │ ├── 32.png
│ │ │ ├── 33.png
│ │ │ ├── 34.png
│ │ │ ├── 35.png
│ │ │ ├── 36.png
│ │ │ ├── 38.png
│ │ │ ├── 39.png
│ │ │ ├── 4.png
│ │ │ ├── 40.png
│ │ │ ├── 41.png
│ │ │ ├── 42.png
│ │ │ ├── 43.png
│ │ │ ├── 44.png
│ │ │ ├── 5.png
│ │ │ ├── 6.png
│ │ │ ├── 7.png
│ │ │ ├── 8.png
│ │ │ ├── 9.png
│ │ │ ├── Indexing.gif
│ │ │ ├── tool_images
│ │ │ │ ├── 1.png
│ │ │ │ ├── 2.png
│ │ │ │ └── 3.png
│ │ │ └── Usecase.gif
│ │ ├── index.md
│ │ ├── installation.md
│ │ ├── license.md
│ │ ├── server.md
│ │ ├── tools.md
│ │ ├── troubleshooting.md
│ │ └── use_cases.md
│ ├── mkdocs.yml
│ └── site
│ ├── 404.html
│ ├── architecture
│ │ └── index.html
│ ├── assets
│ │ ├── images
│ │ │ └── favicon.png
│ │ ├── javascripts
│ │ │ ├── bundle.f55a23d4.min.js
│ │ │ ├── bundle.f55a23d4.min.js.map
│ │ │ ├── lunr
│ │ │ │ ├── min
│ │ │ │ │ ├── lunr.ar.min.js
│ │ │ │ │ ├── lunr.da.min.js
│ │ │ │ │ ├── lunr.de.min.js
│ │ │ │ │ ├── lunr.du.min.js
│ │ │ │ │ ├── lunr.el.min.js
│ │ │ │ │ ├── lunr.es.min.js
│ │ │ │ │ ├── lunr.fi.min.js
│ │ │ │ │ ├── lunr.fr.min.js
│ │ │ │ │ ├── lunr.he.min.js
│ │ │ │ │ ├── lunr.hi.min.js
│ │ │ │ │ ├── lunr.hu.min.js
│ │ │ │ │ ├── lunr.hy.min.js
│ │ │ │ │ ├── lunr.it.min.js
│ │ │ │ │ ├── lunr.ja.min.js
│ │ │ │ │ ├── lunr.jp.min.js
│ │ │ │ │ ├── lunr.kn.min.js
│ │ │ │ │ ├── lunr.ko.min.js
│ │ │ │ │ ├── lunr.multi.min.js
│ │ │ │ │ ├── lunr.nl.min.js
│ │ │ │ │ ├── lunr.no.min.js
│ │ │ │ │ ├── lunr.pt.min.js
│ │ │ │ │ ├── lunr.ro.min.js
│ │ │ │ │ ├── lunr.ru.min.js
│ │ │ │ │ ├── lunr.sa.min.js
│ │ │ │ │ ├── lunr.stemmer.support.min.js
│ │ │ │ │ ├── lunr.sv.min.js
│ │ │ │ │ ├── lunr.ta.min.js
│ │ │ │ │ ├── lunr.te.min.js
│ │ │ │ │ ├── lunr.th.min.js
│ │ │ │ │ ├── lunr.tr.min.js
│ │ │ │ │ ├── lunr.vi.min.js
│ │ │ │ │ └── lunr.zh.min.js
│ │ │ │ ├── tinyseg.js
│ │ │ │ └── wordcut.js
│ │ │ └── workers
│ │ │ ├── search.973d3a69.min.js
│ │ │ └── search.973d3a69.min.js.map
│ │ └── stylesheets
│ │ ├── main.2a3383ac.min.css
│ │ ├── main.2a3383ac.min.css.map
│ │ ├── palette.06af60db.min.css
│ │ └── palette.06af60db.min.css.map
│ ├── cli
│ │ └── index.html
│ ├── contributing
│ │ └── index.html
│ ├── contributing_languages
│ │ └── index.html
│ ├── cookbook
│ │ └── index.html
│ ├── core
│ │ └── index.html
│ ├── future_work
│ │ └── index.html
│ ├── images
│ │ ├── 1.png
│ │ ├── 11.png
│ │ ├── 12.png
│ │ ├── 13.png
│ │ ├── 14.png
│ │ ├── 16.png
│ │ ├── 19.png
│ │ ├── 2.png
│ │ ├── 20.png
│ │ ├── 21.png
│ │ ├── 22.png
│ │ ├── 23.png
│ │ ├── 24.png
│ │ ├── 26.png
│ │ ├── 28.png
│ │ ├── 29.png
│ │ ├── 3.png
│ │ ├── 30.png
│ │ ├── 31.png
│ │ ├── 32.png
│ │ ├── 33.png
│ │ ├── 34.png
│ │ ├── 35.png
│ │ ├── 36.png
│ │ ├── 38.png
│ │ ├── 39.png
│ │ ├── 4.png
│ │ ├── 40.png
│ │ ├── 41.png
│ │ ├── 42.png
│ │ ├── 43.png
│ │ ├── 44.png
│ │ ├── 5.png
│ │ ├── 6.png
│ │ ├── 7.png
│ │ ├── 8.png
│ │ ├── 9.png
│ │ ├── Indexing.gif
│ │ ├── tool_images
│ │ │ ├── 1.png
│ │ │ ├── 2.png
│ │ │ └── 3.png
│ │ └── Usecase.gif
│ ├── index.html
│ ├── installation
│ │ └── index.html
│ ├── license
│ │ └── index.html
│ ├── search
│ │ └── search_index.json
│ ├── server
│ │ └── index.html
│ ├── sitemap.xml
│ ├── sitemap.xml.gz
│ ├── tools
│ │ └── index.html
│ ├── troubleshooting
│ │ └── index.html
│ └── use_cases
│ └── index.html
├── images
│ ├── 1.png
│ ├── 11.png
│ ├── 12.png
│ ├── 13.png
│ ├── 14.png
│ ├── 16.png
│ ├── 19.png
│ ├── 2.png
│ ├── 20.png
│ ├── 21.png
│ ├── 22.png
│ ├── 23.png
│ ├── 24.png
│ ├── 26.png
│ ├── 28.png
│ ├── 29.png
│ ├── 3.png
│ ├── 30.png
│ ├── 31.png
│ ├── 32.png
│ ├── 33.png
│ ├── 34.png
│ ├── 35.png
│ ├── 36.png
│ ├── 38.png
│ ├── 39.png
│ ├── 4.png
│ ├── 40.png
│ ├── 41.png
│ ├── 42.png
│ ├── 43.png
│ ├── 44.png
│ ├── 5.png
│ ├── 6.png
│ ├── 7.png
│ ├── 8.png
│ ├── 9.png
│ ├── Indexing.gif
│ ├── tool_images
│ │ ├── 1.png
│ │ ├── 2.png
│ │ └── 3.png
│ └── Usecase.gif
├── LICENSE
├── MANIFEST.in
├── organizer
│ ├── CONTRIBUTING_LANGUAGES.md
│ ├── cookbook.md
│ ├── docs.md
│ ├── language_specific_nodes.md
│ ├── Tools_Exploration.md
│ └── troubleshoot.md
├── package-lock.json
├── pyproject.toml
├── README.md
├── scripts
│ ├── generate_lang_contributors.py
│ └── post_install_fix.sh
├── SECURITY.md
├── src
│ └── codegraphcontext
│ ├── __init__.py
│ ├── __main__.py
│ ├── cli
│ │ ├── __init__.py
│ │ ├── cli_helpers.py
│ │ ├── main.py
│ │ ├── setup_macos.py
│ │ └── setup_wizard.py
│ ├── core
│ │ ├── __init__.py
│ │ ├── database.py
│ │ ├── jobs.py
│ │ └── watcher.py
│ ├── prompts.py
│ ├── server.py
│ ├── tools
│ │ ├── __init__.py
│ │ ├── advanced_language_query_tool.py
│ │ ├── code_finder.py
│ │ ├── graph_builder.py
│ │ ├── languages
│ │ │ ├── c.py
│ │ │ ├── cpp.py
│ │ │ ├── go.py
│ │ │ ├── java.py
│ │ │ ├── javascript.py
│ │ │ ├── python.py
│ │ │ ├── ruby.py
│ │ │ ├── rust.py
│ │ │ └── typescript.py
│ │ ├── package_resolver.py
│ │ ├── query_tool_languages
│ │ │ ├── c_toolkit.py
│ │ │ ├── cpp_toolkit.py
│ │ │ ├── go_toolkit.py
│ │ │ ├── java_toolkit.py
│ │ │ ├── javascript_toolkit.py
│ │ │ ├── python_toolkit.py
│ │ │ ├── ruby_toolkit.py
│ │ │ ├── rust_toolkit.py
│ │ │ └── typescript_toolkit.py
│ │ └── system.py
│ └── utils
│ └── debug_log.py
├── tests
│ ├── __init__.py
│ ├── conftest.py
│ ├── sample_project
│ │ ├── advanced_calls.py
│ │ ├── advanced_classes.py
│ │ ├── advanced_classes2.py
│ │ ├── advanced_functions.py
│ │ ├── advanced_imports.py
│ │ ├── async_features.py
│ │ ├── callbacks_decorators.py
│ │ ├── circular1.py
│ │ ├── circular2.py
│ │ ├── class_instantiation.py
│ │ ├── cli_and_dunder.py
│ │ ├── complex_classes.py
│ │ ├── comprehensions_generators.py
│ │ ├── context_managers.py
│ │ ├── control_flow.py
│ │ ├── datatypes.py
│ │ ├── dynamic_dispatch.py
│ │ ├── dynamic_imports.py
│ │ ├── edge_cases
│ │ │ ├── comments_only.py
│ │ │ ├── docstring_only.py
│ │ │ ├── empty.py
│ │ │ ├── hardcoded_secrets.py
│ │ │ ├── long_functions.py
│ │ │ └── syntax_error.py
│ │ ├── function_chains.py
│ │ ├── generators.py
│ │ ├── import_reexports.py
│ │ ├── mapping_calls.py
│ │ ├── module_a.py
│ │ ├── module_b.py
│ │ ├── module_c
│ │ │ ├── __init__.py
│ │ │ ├── submodule1.py
│ │ │ └── submodule2.py
│ │ ├── namespace_pkg
│ │ │ └── ns_module.py
│ │ ├── pattern_matching.py
│ │ └── typing_examples.py
│ ├── sample_project_c
│ │ ├── cgc_sample
│ │ ├── include
│ │ │ ├── config.h
│ │ │ ├── math
│ │ │ │ └── vec.h
│ │ │ ├── module.h
│ │ │ ├── platform.h
│ │ │ └── util.h
│ │ ├── Makefile
│ │ ├── README.md
│ │ └── src
│ │ ├── main.c
│ │ ├── math
│ │ │ └── vec.c
│ │ ├── module.c
│ │ └── util.c
│ ├── sample_project_cpp
│ │ ├── class_features.cpp
│ │ ├── classes.cpp
│ │ ├── control_flow.cpp
│ │ ├── edge_cases.cpp
│ │ ├── enum_struct_union.cpp
│ │ ├── exceptions.cpp
│ │ ├── file_io.cpp
│ │ ├── function_chain.cpp
│ │ ├── function_chain.h
│ │ ├── function_types.cpp
│ │ ├── main.cpp
│ │ ├── main.exe
│ │ ├── namespaces.cpp
│ │ ├── raii_example.cpp
│ │ ├── README.md
│ │ ├── sample_project.exe
│ │ ├── stl_usage.cpp
│ │ ├── templates.cpp
│ │ └── types_variable_assignments.cpp
│ ├── sample_project_go
│ │ ├── advanced_types.go
│ │ ├── basic_functions.go
│ │ ├── embedded_composition.go
│ │ ├── error_handling.go
│ │ ├── generics.go
│ │ ├── go.mod
│ │ ├── goroutines_channels.go
│ │ ├── interfaces.go
│ │ ├── packages_imports.go
│ │ ├── README.md
│ │ ├── structs_methods.go
│ │ └── util
│ │ └── helpers.go
│ ├── sample_project_java
│ │ ├── out
│ │ │ └── com
│ │ │ └── example
│ │ │ └── app
│ │ │ ├── annotations
│ │ │ │ └── Logged.class
│ │ │ ├── Main.class
│ │ │ ├── misc
│ │ │ │ ├── Outer.class
│ │ │ │ └── Outer$Inner.class
│ │ │ ├── model
│ │ │ │ ├── Role.class
│ │ │ │ └── User.class
│ │ │ ├── service
│ │ │ │ ├── AbstractGreeter.class
│ │ │ │ ├── GreetingService.class
│ │ │ │ └── impl
│ │ │ │ └── GreetingServiceImpl.class
│ │ │ └── util
│ │ │ ├── CollectionUtils.class
│ │ │ └── IOHelper.class
│ │ ├── README.md
│ │ ├── sources.txt
│ │ └── src
│ │ └── com
│ │ └── example
│ │ └── app
│ │ ├── annotations
│ │ │ └── Logged.java
│ │ ├── Main.java
│ │ ├── misc
│ │ │ └── Outer.java
│ │ ├── model
│ │ │ ├── Role.java
│ │ │ └── User.java
│ │ ├── service
│ │ │ ├── AbstractGreeter.java
│ │ │ ├── GreetingService.java
│ │ │ └── impl
│ │ │ └── GreetingServiceImpl.java
│ │ └── util
│ │ ├── CollectionUtils.java
│ │ └── IOHelper.java
│ ├── sample_project_javascript
│ │ ├── arrays.js
│ │ ├── asyncAwait.js
│ │ ├── classes.js
│ │ ├── dom.js
│ │ ├── errorHandling.js
│ │ ├── events.js
│ │ ├── exporter.js
│ │ ├── fetchAPI.js
│ │ ├── fixtures
│ │ │ └── js
│ │ │ └── accessors.js
│ │ ├── functions.js
│ │ ├── importer.js
│ │ ├── objects.js
│ │ ├── promises.js
│ │ ├── README.md
│ │ └── variables.js
│ ├── sample_project_misc
│ │ ├── index.html
│ │ ├── README.md
│ │ ├── styles.css
│ │ ├── tables.css
│ │ └── tables.html
│ ├── sample_project_php
│ │ ├── classes_objects.php
│ │ ├── database.php
│ │ ├── edgecases.php
│ │ ├── error_handling.php
│ │ ├── file_handling.php
│ │ ├── functions.php
│ │ ├── generators_iterators.php
│ │ ├── globals_superglobals.php
│ │ ├── Inheritance.php
│ │ ├── interface_traits.php
│ │ └── README.md
│ ├── sample_project_ruby
│ │ ├── class_example.rb
│ │ ├── enumerables.rb
│ │ ├── error_handling.rb
│ │ ├── file_io.rb
│ │ ├── inheritance_example.rb
│ │ ├── main.rb
│ │ ├── metaprogramming.rb
│ │ ├── mixins_example.rb
│ │ ├── module_example.rb
│ │ └── tests
│ │ ├── test_mixins.py
│ │ └── test_sample.rb
│ ├── sample_project_rust
│ │ ├── Cargo.toml
│ │ ├── README.md
│ │ └── src
│ │ ├── basic_functions.rs
│ │ ├── concurrency.rs
│ │ ├── error_handling.rs
│ │ ├── generics.rs
│ │ ├── iterators_closures.rs
│ │ ├── lib.rs
│ │ ├── lifetimes_references.rs
│ │ ├── modules.rs
│ │ ├── smart_pointers.rs
│ │ ├── structs_enums.rs
│ │ └── traits.rs
│ ├── sample_project_typescript
│ │ ├── package.json
│ │ ├── README.md
│ │ ├── src
│ │ │ ├── advanced-types.ts
│ │ │ ├── async-promises.ts
│ │ │ ├── classes-inheritance.ts
│ │ │ ├── decorators-metadata.ts
│ │ │ ├── error-validation.ts
│ │ │ ├── functions-generics.ts
│ │ │ ├── index.ts
│ │ │ ├── modules-namespaces.ts
│ │ │ ├── types-interfaces.ts
│ │ │ └── utilities-helpers.ts
│ │ └── tsconfig.json
│ ├── test_cpp_parser.py
│ ├── test_database_validation.py
│ ├── test_end_to_end.py
│ ├── test_graph_indexing_js.py
│ ├── test_graph_indexing.py
│ ├── test_tree_sitter
│ │ ├── __init__.py
│ │ ├── class_instantiation.py
│ │ ├── complex_classes.py
│ │ └── test_file.py
│ └── test_typescript_parser.py
└── website
├── .example.env
├── .gitignore
├── api
│ └── pypi.ts
├── bun.lockb
├── components.json
├── eslint.config.js
├── index.html
├── package-lock.json
├── package.json
├── postcss.config.js
├── public
│ ├── favicon.ico
│ ├── placeholder.svg
│ └── robots.txt
├── README.md
├── src
│ ├── App.css
│ ├── App.tsx
│ ├── assets
│ │ ├── function-calls.png
│ │ ├── graph-total.png
│ │ ├── hero-graph.jpg
│ │ └── hierarchy.png
│ ├── components
│ │ ├── ComparisonTable.tsx
│ │ ├── CookbookSection.tsx
│ │ ├── DemoSection.tsx
│ │ ├── ExamplesSection.tsx
│ │ ├── FeaturesSection.tsx
│ │ ├── Footer.tsx
│ │ ├── HeroSection.tsx
│ │ ├── InstallationSection.tsx
│ │ ├── MoveToTop.tsx
│ │ ├── ShowDownloads.tsx
│ │ ├── ShowStarGraph.tsx
│ │ ├── TestimonialSection.tsx
│ │ ├── ThemeProvider.tsx
│ │ ├── ThemeToggle.tsx
│ │ └── ui
│ │ ├── accordion.tsx
│ │ ├── alert-dialog.tsx
│ │ ├── alert.tsx
│ │ ├── aspect-ratio.tsx
│ │ ├── avatar.tsx
│ │ ├── badge.tsx
│ │ ├── breadcrumb.tsx
│ │ ├── button.tsx
│ │ ├── calendar.tsx
│ │ ├── card.tsx
│ │ ├── carousel.tsx
│ │ ├── chart.tsx
│ │ ├── checkbox.tsx
│ │ ├── collapsible.tsx
│ │ ├── command.tsx
│ │ ├── context-menu.tsx
│ │ ├── dialog.tsx
│ │ ├── drawer.tsx
│ │ ├── dropdown-menu.tsx
│ │ ├── form.tsx
│ │ ├── hover-card.tsx
│ │ ├── input-otp.tsx
│ │ ├── input.tsx
│ │ ├── label.tsx
│ │ ├── menubar.tsx
│ │ ├── navigation-menu.tsx
│ │ ├── orbiting-circles.tsx
│ │ ├── pagination.tsx
│ │ ├── popover.tsx
│ │ ├── progress.tsx
│ │ ├── radio-group.tsx
│ │ ├── resizable.tsx
│ │ ├── scroll-area.tsx
│ │ ├── select.tsx
│ │ ├── separator.tsx
│ │ ├── sheet.tsx
│ │ ├── sidebar.tsx
│ │ ├── skeleton.tsx
│ │ ├── slider.tsx
│ │ ├── sonner.tsx
│ │ ├── switch.tsx
│ │ ├── table.tsx
│ │ ├── tabs.tsx
│ │ ├── textarea.tsx
│ │ ├── toast.tsx
│ │ ├── toaster.tsx
│ │ ├── toggle-group.tsx
│ │ ├── toggle.tsx
│ │ ├── tooltip.tsx
│ │ └── use-toast.ts
│ ├── hooks
│ │ ├── use-mobile.tsx
│ │ └── use-toast.ts
│ ├── index.css
│ ├── lib
│ │ └── utils.ts
│ ├── main.tsx
│ ├── pages
│ │ ├── Index.tsx
│ │ └── NotFound.tsx
│ └── vite-env.d.ts
├── tailwind.config.ts
├── tsconfig.app.json
├── tsconfig.json
├── tsconfig.node.json
├── vercel.json
└── vite.config.ts
```
# Files
--------------------------------------------------------------------------------
/website/.example.env:
--------------------------------------------------------------------------------
```
VITE_SUPABASE_ANON_KEY="your-anon-key"
VITE_SUPABASE_URL="https://your-project.supabase.co"
```
--------------------------------------------------------------------------------
/website/.gitignore:
--------------------------------------------------------------------------------
```
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
```
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
```
# Python
__pycache__/
*.pyc
*.pyo
*.pyd
.Python
env/
venv/
.venv/
./.env
.venv311/
venv311/
docker-compose.yml
# PyPI
dist/
build/
*.egg-info/
# IDEs and editors
.vscode/
.idea/
*.swp
*.swo
# Config
.env
*.db
*.sqlite3
# Testing
.pytest_cache/
coverage.xml
htmlcov/
# MCP
mcp.json
# Docker
docker-compose.yml
# yaml file for amazon Q developer
devfile.yaml
# local scratch
javascript.py.bak
src/codegraphcontext/cli/nl.py
*.bak
```
--------------------------------------------------------------------------------
/tests/sample_project_misc/README.md:
--------------------------------------------------------------------------------
```markdown
# Sample Misc Project
This is a sample project containing miscellaneous files for testing:
- `index.html`: Basic HTML file
- `styles.css`: Simple CSS styling for index.html
- `tables.html`: A simple table to mock Hacktoberfest contributors.
- `tables.css`: Corresponding CSS styling for tables.html
- `README.md`: This file
```
--------------------------------------------------------------------------------
/website/README.md:
--------------------------------------------------------------------------------
```markdown
# Website
This directory contains the source code for the CodeGraphContext website.
## Development
To run the website locally, follow these steps:
1. Navigate to this directory:
```bash
cd website
```
2. Install the dependencies:
```bash
npm install
```
3. Start the development server:
```bash
npm run dev
```
## Build
To create a production build of the website, run:
```bash
npm run build
```
```
--------------------------------------------------------------------------------
/tests/sample_project_java/README.md:
--------------------------------------------------------------------------------
```markdown
# Java sample project (for `tests/`)
A tiny, dependency-free Java project (~10 files) used to exercise CodeGraphContext’s indexer.
It mirrors the Python sample by showcasing relationships: packages, interface→impl, abstract class,
enum, generics, exceptions, custom annotation, inner class, lambdas/streams, basic I/O, and a tiny thread.
## Layout
tests/sample_project_java/
├─ README.md
└─ src/com/example/app/
├─ Main.java
├─ model/Role.java
├─ model/User.java
├─ service/GreetingService.java
├─ service/AbstractGreeter.java
├─ service/impl/GreetingServiceImpl.java
├─ util/CollectionUtils.java
├─ util/IOHelper.java
├─ annotations/Logged.java
└─ misc/Outer.java
## Quick run (no build tool)
From this folder:
```bash
# compile
find src -name "*.java" > sources.txt
javac -d out @sources.txt
# run
java -cp out com.example.app.Main
```
## Expected Output
Hello, Priya (ADMIN)
sumSquares=55
firstLine=# java sample project
outer+inner
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/README.md:
--------------------------------------------------------------------------------
```markdown
# C++ Sample Project
This folder contains a set of C++ files demonstrating major aspects and nuances of C++ programming, inspired by the Python sample_project. Each file is self-contained and focuses on a specific feature or idiom.
## Files
- `control_flow.cpp`: Demonstrates if/else, ternary, and for loop control flow.
- `classes.cpp`: Shows classes, inheritance, and polymorphism.
- `templates.cpp`: Covers function templates and specialization.
- `exceptions.cpp`: Exception handling with try/catch blocks.
- `raii_example.cpp`: Resource Acquisition Is Initialization (RAII) pattern.
- `function_chains.cpp`: Function pointers, lambdas, and higher-order functions.
- `namespaces.cpp`: Use of namespaces and the `using` directive.
- `stl_usage.cpp`: STL containers and algorithms (vector, for_each, lambda).
- `file_io.cpp`: Basic file input/output using fstream.
- `edge_cases.cpp`: Edge cases such as empty files and comments only.
Each file is intended to be simple, focused, and suitable for code indexing, analysis, or as a reference for C++ language features.
```
--------------------------------------------------------------------------------
/tests/sample_project_php/README.md:
--------------------------------------------------------------------------------
```markdown
# PHP Sample Project
# PHP Sample Project
This folder contains a set of PHP files demonstrating major aspects/nuances of PHP programming, inspired by the Python sample_project
## Project Structure
sample_project_php/\
├── classes_objects.php\
├── database.php\
├── edgecases.php\
├── error_handling.php\
├── file_handling.php \
├── functions.php\
├── generators_iterators.php\
├── globals_superglobals.php\
├── inheritance.php\
└── interfaces_traits.php
### Features Covered
- **Functions & Callbacks**: Anonymous functions, closures, variadics
- **Object-Oriented PHP**: Classes, inheritance, abstract classes, interfaces, traits
- **Error Handling**: Custom exceptions, try/catch/finally
- **File I/O**: Reading and writing files, appending content
- **Database**: Connecting with PDO, creating tables, inserts, selects
- **Generators & Iterators**: Yield keyword, implementing Iterator interface
- **Edge Cases**: Type juggling, array key overwrites, null/empty comparisons
- **Superglobals**: Accessing $_GET, $_POST, and using $GLOBALS
### How to Run
Make sure you have PHP installed (>= 7.4 recommended) and a database if testing `database.php`.
Run individual files from the terminal:
```bash
php functions.php
php classes_objects.php
php inheritance.php
...etc
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/README.md:
--------------------------------------------------------------------------------
```markdown
# JavaScript Sample Project
This directory contains comprehensive JavaScript test files to demonstrate and test the enhanced JavaScript support in CodeGraphContext.
## Files Overview
### `functions.js`
Demonstrates various function definition patterns:
- Regular function declarations
- Function expressions
- Arrow functions (with multiple parameters, single parameter, no parameters)
- Functions with default parameters
- Functions with rest parameters
- Functions with destructuring parameters
- Async functions
- Generator functions
- Higher-order functions
- IIFE (Immediately Invoked Function Expressions)
### `classes.js`
Demonstrates class definitions and inheritance:
- Basic class declarations
- Constructor methods
- Instance methods
- Static methods
- Getter and setter methods
- Class inheritance with `extends`
- Method overriding
- Private fields and methods (modern JavaScript)
- Class expressions
- Mixin patterns
### `objects.js`
Demonstrates object methods and prototype assignments:
- Object literal methods (shorthand and traditional syntax)
- Nested object methods
- Prototype method assignments
- Constructor functions with prototype methods
- Module pattern with private/public methods
- Factory functions that create objects with methods
- Methods that call other methods
- Callback and higher-order function patterns
## Expected Function Detections
The enhanced JavaScript parser should detect and properly index:
1. **Function Declarations**: `function functionName(params) { ... }`
2. **Function Expressions**: `const func = function(params) { ... }`
3. **Arrow Functions**: `const func = (params) => { ... }`
4. **Single Parameter Arrow**: `const func = param => { ... }`
5. **Method Definitions**: `methodName(params) { ... }` in classes and objects
6. **Static Methods**: `static methodName(params) { ... }`
7. **Prototype Methods**: `Constructor.prototype.method = function(params) { ... }`
8. **Getter/Setter Methods**: `get property() { ... }` and `set property(value) { ... }`
## Testing Instructions
1. Index this JavaScript sample project using CodeGraphContext
2. Verify that all function types are detected with correct:
- Function names
- Line numbers
- Parameter lists
- File paths
- JSDoc comments (where applicable)
## Expected Neo4j Query Results
After indexing, you should be able to run queries like:
```cypher
// Find all JavaScript functions
MATCH (f:Function)
WHERE f.lang = 'javascript'
RETURN f.name, f.line_number, f.file_path, f.args
// Find all JavaScript classes
MATCH (c:Class)
WHERE c.lang = 'javascript'
RETURN c.name, c.line_number, c.file_path
// Find function call relationships
MATCH (caller:Function)-[r:CALLS]->(callee:Function)
WHERE caller.lang = 'javascript'
RETURN caller.name + " → " + callee.name as CallChain
```
```
--------------------------------------------------------------------------------
/tests/sample_project_go/README.md:
--------------------------------------------------------------------------------
```markdown
# Go Sample Project
This is a comprehensive Go sample project for testing code analysis and indexing tools. It covers major Go language features and patterns.
## Files Overview
### 1. `basic_functions.go`
- Basic function definitions
- Multiple return values
- Named returns
- Variadic functions
- Higher-order functions
- Closures
- Recursion
- Defer, panic, and recover
- Init functions
### 2. `structs_methods.go`
- Struct definitions
- Value and pointer receivers
- Constructor functions
- Embedded structs
- Method chaining
- Private and public fields
### 3. `interfaces.go`
- Interface definitions
- Interface implementations
- Interface embedding
- Type assertions
- Type switches
- Empty interfaces
- Polymorphism
### 4. `goroutines_channels.go`
- Goroutines
- Channels (buffered and unbuffered)
- Select statements
- Worker pools
- Mutexes (sync.Mutex, sync.RWMutex)
- Wait groups
- Pipeline patterns
- Fan-out/Fan-in patterns
- Singleton with sync.Once
### 5. `error_handling.go`
- Basic error returns
- Custom error types
- Error wrapping (Go 1.13+)
- Sentinel errors
- Error type assertions
- errors.Is and errors.As
- Validation errors
- Panic to error conversion
- Deferred error handling
### 6. `generics.go`
- Generic functions
- Generic types (Stack, Queue, Cache)
- Type constraints
- Generic data structures
- Map/Filter/Reduce with generics
- Generic linked lists
### 7. `embedded_composition.go`
- Struct embedding
- Method promotion
- Multiple embedding
- Interface embedding
- Composition over inheritance
- Name conflict resolution
### 8. `advanced_types.go`
- Custom types
- Type aliases
- Enum patterns
- Maps and nested maps
- Slices and 2D slices
- Arrays
- Struct tags
- Anonymous structs
- Function types
- Channel types
- Sortable types (sort.Interface)
- Bit flags
### 9. `packages_imports.go`
- Standard library imports
- Aliased imports
- Blank imports
- Package initialization (init)
- Multiple package usage
- Common stdlib packages: fmt, strings, math, time, os, io, net/http
### 10. `util/helpers.go` (subpackage)
- Utility types and functions
- String utilities
- Math utilities
- Slice utilities
- Validators
- Logger implementation
- Package-level helper functions
## Features Covered
- ✅ Basic syntax and functions
- ✅ Structs and methods
- ✅ Interfaces and polymorphism
- ✅ Concurrency (goroutines, channels, sync)
- ✅ Error handling patterns
- ✅ Generics (Go 1.18+)
- ✅ Embedding and composition
- ✅ Advanced types (maps, slices, custom types)
- ✅ Package organization
- ✅ Standard library usage
- ✅ Common patterns and idioms
## Building and Running
```bash
# Initialize module
go mod init github.com/example/sample_project_go
# Download dependencies
go mod tidy
# Run individual files
go run basic_functions.go
go run structs_methods.go
# ... etc
# Build all
go build ./...
# Run tests (if tests are added)
go test ./...
```
## Use Cases
This sample project is designed for:
- Testing code analysis tools
- Demonstrating Go best practices
- Code indexing and graph database population
- Understanding Go language features
- Reference implementation for Go patterns
```
--------------------------------------------------------------------------------
/tests/sample_project_rust/README.md:
--------------------------------------------------------------------------------
```markdown
# Rust Sample Project
A comprehensive Rust sample project for testing code analysis and indexing tools. This project covers major Rust language features and patterns.
## Project Structure
```
sample_project_rust/
├── Cargo.toml
├── README.md
└── src/
├── lib.rs # Main library file
├── basic_functions.rs # Basic Rust patterns
├── structs_enums.rs # Structs and enums
├── traits.rs # Traits and implementations
├── error_handling.rs # Error handling patterns
├── lifetimes_references.rs # Lifetimes and borrowing
├── generics.rs # Generic types and functions
├── concurrency.rs # Threading and sync
├── iterators_closures.rs # Iterators and closures
├── smart_pointers.rs # Smart pointers (Box, Rc, Arc)
└── modules.rs # Module organization
```
## Files Overview
### 1. `basic_functions.rs`
- Function definitions and patterns
- Ownership and borrowing
- Multiple return values (tuples)
- Result and Option types
- Lifetimes in functions
- Generic functions with trait bounds
- Higher-order functions
- Closures and function returns
- Recursion
### 2. `structs_enums.rs`
- Struct definitions (regular, tuple, unit)
- Methods (impl blocks)
- Associated functions (constructors)
- Embedded structs
- Enums with data
- Pattern matching
- Display trait implementations
### 3. `traits.rs`
- Trait definitions
- Trait implementations
- Default implementations
- Associated types and constants
- Trait bounds and where clauses
- Trait objects (dyn Trait)
- Operator overloading
- Blanket implementations
### 4. `error_handling.rs`
- Custom error types
- Result and Option handling
- Error propagation (? operator)
- Error conversion (From trait)
- Multiple error types
- Validation patterns
- Error combinators (map, and_then)
### 5. `lifetimes_references.rs`
- Explicit lifetime annotations
- Lifetime elision rules
- Structs with lifetimes
- Multiple lifetime parameters
- Static lifetimes
- Higher-ranked trait bounds
- Lifetime bounds
### 6. `generics.rs`
- Generic functions
- Generic structs and enums
- Trait bounds on generics
- Where clauses
- Associated types
- Generic collections (Stack, Queue, LinkedList)
- Const generics
- Generic closures
### 7. `concurrency.rs`
- Thread spawning
- Arc and Mutex for shared state
- RwLock for read-heavy workloads
- Channels (mpsc)
- Thread pools
- Barriers and atomic operations
- sync::Once for initialization
- Scoped threads
### 8. `iterators_closures.rs`
- Custom iterators
- Iterator adapters (map, filter, fold)
- Closure types (Fn, FnMut, FnOnce)
- Iterator chains
- Lazy evaluation
- Infinite iterators
- Peekable iterators
### 9. `smart_pointers.rs`
- Box for heap allocation
- Rc for reference counting
- Arc for thread-safe counting
- RefCell for interior mutability
- Weak references
- Cow (Clone on Write)
- Custom smart pointers
- Drop trait
### 10. `modules.rs`
- Module organization
- Nested modules
- Public/private visibility
- Re-exports (pub use)
- Module paths
- Prelude pattern
## Features Covered
- ✅ **Ownership & Borrowing**: Move semantics, references, lifetimes
- ✅ **Type System**: Structs, enums, traits, generics
- ✅ **Error Handling**: Result, Option, custom errors
- ✅ **Concurrency**: Threads, Arc, Mutex, channels
- ✅ **Functional Programming**: Iterators, closures, combinators
- ✅ **Smart Pointers**: Box, Rc, Arc, RefCell, Weak
- ✅ **Module System**: Visibility, re-exports, organization
- ✅ **Pattern Matching**: Match expressions, if let
- ✅ **Trait System**: Implementations, bounds, objects
- ✅ **Advanced Features**: Lifetimes, const generics, HRTBs
## Building and Testing
```bash
# Build the project
cargo build
# Run tests
cargo test
# Check without building
cargo check
# Build documentation
cargo doc --open
# Run clippy for lints
cargo clippy
```
## Use Cases
This sample project is designed for:
- Testing Rust code analysis tools
- Demonstrating Rust best practices
- Code indexing and graph database population
- Understanding Rust ownership model
- Reference implementation for Rust patterns
- Compiler and IDE testing
## Rust Concepts Demonstrated
### Ownership
- Move semantics
- Borrowing (immutable and mutable)
- References and dereferencing
- Lifetime annotations
### Type System
- Zero-cost abstractions
- Type inference
- Algebraic data types (enums)
- Pattern matching exhaustiveness
### Memory Safety
- No null pointers (Option instead)
- No data races (enforced by type system)
- RAII (Resource Acquisition Is Initialization)
- Automatic memory management
### Concurrency
- Fearless concurrency (no data races)
- Message passing (channels)
- Shared state (Arc + Mutex)
- Thread safety guaranteed by type system
## Integration with CodeGraphContext
This project can be used to test:
- Function call resolution across modules
- Trait implementation tracking
- Lifetime relationship analysis
- Generic type instantiation
- Module dependency graphs
- Concurrent code patterns
- Smart pointer usage patterns
```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
```markdown
# CodeGraphContext
<!-- ====== Project stats ====== -->
[](https://github.com/Shashankss1205/CodeGraphContext/stargazers)
[](https://github.com/Shashankss1205/CodeGraphContext/network/members)
[](https://github.com/Shashankss1205/CodeGraphContext/issues)
[](https://github.com/Shashankss1205/CodeGraphContext/pulls)
[](https://github.com/Shashankss1205/CodeGraphContext/pulls?q=is%3Apr+is%3Aclosed)
[](https://github.com/Shashankss1205/CodeGraphContext/graphs/contributors)
[](https://github.com/Shashankss1205/CodeGraphContext)
[](https://github.com/Shashankss1205/CodeGraphContext/actions/workflows/test.yml)
[](https://github.com/Shashankss1205/CodeGraphContext/actions/workflows/e2e-tests.yml)
[](https://pypi.org/project/codegraphcontext/)
[](https://pypi.org/project/codegraphcontext/)
[](LICENSE)
[](http://codegraphcontext.vercel.app/)
[](https://shashankss1205.github.io/CodeGraphContext/)
[](https://youtu.be/KYYSdxhg1xU)
[](https://discord.gg/dR4QY32uYQ)
An MCP server that indexes local code into a graph database to provide context to AI assistants.
### Indexing a codebase

### Using the MCP server

## Project Details
- **Version:** 0.1.17
- **Authors:** Shashank Shekhar Singh <[email protected]>
- **License:** MIT License (See [LICENSE](LICENSE) for details)
- **Website:** [CodeGraphContext](http://codegraphcontext.vercel.app/)
## Star History
[](https://www.star-history.com/#Shashankss1205/CodeGraphContext&Date)
## Features
- **Code Indexing:** Analyzes code and builds a knowledge graph of its components.
- **Relationship Analysis:** Query for callers, callees, class hierarchies, call chains and more.
- **Live Updates:** Watches local files for changes and automatically updates the graph.
- **Interactive Setup:** A user-friendly command-line wizard for easy setup.
## Used By
CodeGraphContext is already being explored by developers and projects for:
- **Static code analysis in AI assistants**
- **Graph-based visualization of projects**
- **Dead code and complexity detection**
If you’re using CodeGraphContext in your project, feel free to open a PR and add it here! 🚀
## Dependencies
- `neo4j>=5.15.0`
- `watchdog>=3.0.0`
- `requests>=2.31.0`
- `stdlibs>=2023.11.18`
- `typer[all]>=0.9.0`
- `rich>=13.7.0`
- `inquirerpy>=0.3.4`
- `python-dotenv>=1.0.0`
- `tree-sitter==0.20.4`
- `tree-sitter-languages==1.10.2`
- `pyyaml`
- `pytest`
- `nbformat`
- `nbconvert>=7.16.6`
- `pathspec>=0.12.1`
## Getting Started
1. **Install:** `pip install codegraphcontext`
2. **Setup:** `cgc setup`
This interactive command guides you through configuring your Neo4j database connection and automatically setting up your IDE.
<details>
<summary>⚙️ Troubleshooting: In case, command <code>cgc</code> not found</summary>
If you encounter <i>"cgc: command not found"</i> after installation, run the PATH fix script:
**Linux/Mac:**
```bash
# Download the fix script
curl -O https://raw.githubusercontent.com/Shashankss1205/CodeGraphContext/main/scripts/post_install_fix.sh
# Make it executable
chmod +x post_install_fix.sh
# Run the script
./post_install_fix.sh
# Restart your terminal or reload shell config
source ~/.bashrc # or ~/.zshrc for zsh users
```
**Windows (PowerShell):**
```powershell
# Download the fix script
curl -O https://raw.githubusercontent.com/Shashankss1205/CodeGraphContext/main/scripts/post_install_fix.sh
# Run with bash (requires Git Bash or WSL)
bash post_install_fix.sh
# Restart PowerShell or reload profile
. $PROFILE
```
</details>
**Database Configuration:**
* **Local Setup (Docker Recommended):** Helps you set up a local Neo4j instance using Docker. Requires Docker and Docker Compose to be installed.
* **Local Setup (Linux Binary):** For Debian-based Linux systems (like Ubuntu), `cgc setup` can automate the installation of Neo4j. Requires `sudo` privileges.
* **Hosted Setup:** Allows you to connect to an existing remote Neo4j database (e.g., Neo4j AuraDB).
**IDE/CLI Configuration:**
After setting up your database, the wizard will ask to configure your development environment. It can automatically detect and configure the following:
* VS Code
* Cursor
* Windsurf
* Claude
* Gemini CLI
* ChatGPT Codex
* Cline
* RooCode
* Amazon Q Developer
Upon successful configuration, `cgc setup` will generate and place the necessary configuration files:
* It creates an `mcp.json` file in your current directory for reference.
* It stores your Neo4j credentials securely in `~/.codegraphcontext/.env`.
* It updates the settings file of your chosen IDE/CLI (e.g., `.claude.json` or VS Code's `settings.json`).
3. **Start:** `cgc start`
## Ignoring Files (`.cgcignore`)
You can tell CodeGraphContext to ignore specific files and directories by creating a `.cgcignore` file in the root of your project. This file uses the same syntax as `.gitignore`.
**Example `.cgcignore` file:**
```
# Ignore build artifacts
/build/
/dist/
# Ignore dependencies
/node_modules/
/vendor/
# Ignore logs
*.log
```
## MCP Client Configuration
The `cgc setup` command attempts to automatically configure your IDE/CLI. If you choose not to use the automatic setup, or if your tool is not supported, you can configure it manually.
Add the following server configuration to your client's settings file (e.g., VS Code's `settings.json` or `.claude.json`):
```json
{
"mcpServers": {
"CodeGraphContext": {
"command": "cgc",
"args": [
"start"
],
"env": {
"NEO4J_URI": "YOUR_NEO4J_URI",
"NEO4J_USERNAME": "YOUR_NEO4J_USERNAME",
"NEO4J_PASSWORD": "YOUR_NEO4J_PASSWORD"
},
"tools": {
"alwaysAllow": [
"add_code_to_graph",
"add_package_to_graph",
"check_job_status",
"list_jobs",
"find_code",
"analyze_code_relationships",
"watch_directory",
"find_dead_code",
"execute_cypher_query",
"calculate_cyclomatic_complexity",
"find_most_complex_functions",
"list_indexed_repositories",
"delete_repository",
"visualize_graph_query",
"list_watched_paths",
"unwatch_directory"
],
"disabled": false
},
"disabled": false,
"alwaysAllow": []
}
}
}
```
## Natural Language Interaction Examples
Once the server is running, you can interact with it through your AI assistant using plain English. Here are some examples of what you can say:
### Indexing and Watching Files
- **To index a new project:**
- "Please index the code in the `/path/to/my-project` directory."
OR
- "Add the project at `~/dev/my-other-project` to the code graph."
- **To start watching a directory for live changes:**
- "Watch the `/path/to/my-active-project` directory for changes."
OR
- "Keep the code graph updated for the project I'm working on at `~/dev/main-app`."
When you ask to watch a directory, the system performs two actions at once:
1. It kicks off a full scan to index all the code in that directory. This process runs in the background, and you'll receive a `job_id` to track its progress.
2. It begins watching the directory for any file changes to keep the graph updated in real-time.
This means you can start by simply telling the system to watch a directory, and it will handle both the initial indexing and the continuous updates automatically.
### Querying and Understanding Code
- **Finding where code is defined:**
- "Where is the `process_payment` function?"
- "Find the `User` class for me."
- "Show me any code related to 'database connection'."
- **Analyzing relationships and impact:**
- "What other functions call the `get_user_by_id` function?"
- "If I change the `calculate_tax` function, what other parts of the code will be affected?"
- "Show me the inheritance hierarchy for the `BaseController` class."
- "What methods does the `Order` class have?"
- **Exploring dependencies:**
- "Which files import the `requests` library?"
- "Find all implementations of the `render` method."
- **Advanced Call Chain and Dependency Tracking (Spanning Hundreds of Files):**
The CodeGraphContext excels at tracing complex execution flows and dependencies across vast codebases. Leveraging the power of graph databases, it can identify direct and indirect callers and callees, even when a function is called through multiple layers of abstraction or across numerous files. This is invaluable for:
- **Impact Analysis:** Understand the full ripple effect of a change to a core function.
- **Debugging:** Trace the path of execution from an entry point to a specific bug.
- **Code Comprehension:** Grasp how different parts of a large system interact.
- "Show me the full call chain from the `main` function to `process_data`."
- "Find all functions that directly or indirectly call `validate_input`."
- "What are all the functions that `initialize_system` eventually calls?"
- "Trace the dependencies of the `DatabaseManager` module."
- **Code Quality and Maintenance:**
- "Is there any dead or unused code in this project?"
- "Calculate the cyclomatic complexity of the `process_data` function in `src/utils.py`."
- "Find the 5 most complex functions in the codebase."
- **Repository Management:**
- "List all currently indexed repositories."
- "Delete the indexed repository at `/path/to/old-project`."
## Contributing
Contributions are welcome! 🎉
Please see our [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.
If you have ideas for new features, integrations, or improvements, open an [issue](https://github.com/Shashankss1205/CodeGraphContext/issues) or submit a Pull Request.
Join discussions and help shape the future of CodeGraphContext.
```
--------------------------------------------------------------------------------
/tests/sample_project_typescript/README.md:
--------------------------------------------------------------------------------
```markdown
# TypeScript Sample Project
A comprehensive TypeScript sample project for testing code analysis and indexing tools. This project covers major TypeScript language features, patterns, and best practices across approximately 10 files.
## Project Overview
This sample project is designed to demonstrate and test TypeScript's capabilities for:
- Code analysis tools
- Code indexing systems
- Graph database population
- Understanding TypeScript language features
- Reference implementation for TypeScript patterns
## Files Overview
### 1. `src/types-interfaces.ts`
Demonstrates TypeScript's core type system including:
- ✅ **Primitive Types**: string, number, boolean, null, undefined, symbol, bigint
- ✅ **Array and Tuple Types**: typed arrays, named tuples, readonly arrays
- ✅ **Object Types**: inline object types, optional properties
- ✅ **Interface Definitions**: basic interfaces, inheritance, index signatures
- ✅ **Type Aliases**: union types, intersection types, generic aliases
- ✅ **Union Types**: discriminated unions, type guards, exhaustive checks
- ✅ **Intersection Types**: combining types, complex compositions
- ✅ **Conditional Types**: type-level conditionals, infer keyword
- ✅ **Template Literal Types**: string manipulation at type level
- ✅ **Utility Types**: Pick, Omit, Partial, Required, etc.
### 2. `src/classes-inheritance.ts`
Covers object-oriented programming features:
- ✅ **Basic Classes**: constructors, properties, methods
- ✅ **Access Modifiers**: public, private, protected, readonly
- ✅ **Static Members**: static properties and methods
- ✅ **Inheritance**: extends keyword, super calls, method overriding
- ✅ **Abstract Classes**: abstract methods and properties
- ✅ **Interface Implementation**: implementing multiple interfaces
- ✅ **Generic Classes**: class-level generics, constraints
- ✅ **Design Patterns**: Singleton, Factory, Mixin patterns
- ✅ **Getters and Setters**: property accessors
- ✅ **Method Overloads**: multiple function signatures
### 3. `src/functions-generics.ts`
Explores function types and generic programming:
- ✅ **Function Types**: basic functions, arrow functions, optional parameters
- ✅ **Function Overloads**: multiple signatures for same function
- ✅ **Generic Functions**: type parameters, constraints, inference
- ✅ **Higher-Order Functions**: functions returning functions
- ✅ **Utility Functions**: memoization, debouncing, throttling
- ✅ **Generic Constraints**: extends keyword, keyof operator
- ✅ **Generic Data Structures**: Stack, Queue, PriorityQueue
- ✅ **Function Composition**: pipe, compose patterns
- ✅ **Currying**: partial application, function currying
### 4. `src/async-promises.ts`
Demonstrates asynchronous programming patterns:
- ✅ **Promises**: creating, chaining, error handling
- ✅ **Async/Await**: modern async syntax, error handling
- ✅ **Promise Combinators**: Promise.all, Promise.race, custom combinators
- ✅ **Async Iterators**: async generators, for-await-of
- ✅ **Observable Patterns**: EventEmitter, subscription management
- ✅ **Concurrency Control**: Promise pools, semaphores, rate limiting
- ✅ **Async Cache**: TTL-based caching, async operations
- ✅ **Error Handling**: retry patterns, timeout handling
- ✅ **Stream Processing**: batch processing, async pipelines
### 5. `src/decorators-metadata.ts`
Showcases TypeScript decorator system:
- ✅ **Class Decorators**: @Entity, @Injectable, @Component
- ✅ **Method Decorators**: @Log, @Cache, @Validate, @Retry
- ✅ **Property Decorators**: @Column, @Required, @SerializableProperty
- ✅ **Parameter Decorators**: @Inject, @ValidateParam
- ✅ **Metadata Reflection**: using reflect-metadata
- ✅ **Decorator Factories**: parameterized decorators
- ✅ **Custom Decorators**: role-based access, validation
- ✅ **Metadata Readers**: utility classes for metadata access
### 6. `src/modules-namespaces.ts`
Covers module system and organization:
- ✅ **Basic Exports**: named exports, default exports, re-exports
- ✅ **Namespace Declarations**: nested namespaces, namespace merging
- ✅ **Module Augmentation**: extending existing types globally
- ✅ **Ambient Declarations**: declaring external libraries
- ✅ **Dynamic Imports**: code splitting, conditional loading
- ✅ **Module Factories**: configurable modules, dependency injection
- ✅ **Barrel Exports**: index files, re-export patterns
- ✅ **Triple-Slash Directives**: type references, library references
### 7. `src/advanced-types.ts`
Advanced type system features:
- ✅ **Mapped Types**: transforming object types, key transformation
- ✅ **Conditional Types**: type-level logic, distributive conditionals
- ✅ **Template Literal Types**: string manipulation, path building
- ✅ **Recursive Types**: deeply nested type operations
- ✅ **Branded Types**: nominal typing patterns, type safety
- ✅ **Tuple Utilities**: head, tail, reverse operations
- ✅ **String Manipulation**: uppercase, lowercase, split, join
- ✅ **Type Predicates**: union detection, type guards
- ✅ **Higher-Kinded Types**: functor simulation, HKT patterns
### 8. `src/error-validation.ts`
Error handling and validation patterns:
- ✅ **Custom Error Classes**: structured error hierarchies
- ✅ **Result Pattern**: functional error handling
- ✅ **Type Guards**: runtime type checking, assertion functions
- ✅ **Validation Schemas**: rule-based validation, transformers
- ✅ **Error Boundaries**: centralized error handling
- ✅ **Safe Parsing**: result-based parsing functions
- ✅ **Assertion Functions**: type-narrowing assertions
- ✅ **Try-Catch Utilities**: functional try-catch patterns
### 9. `src/utilities-helpers.ts`
Common utility functions and type helpers:
- ✅ **String Utilities**: case conversion, truncation, normalization
- ✅ **Array Utilities**: chunking, grouping, shuffling, sampling
- ✅ **Object Utilities**: deep cloning, merging, property access
- ✅ **Function Utilities**: debouncing, throttling, memoization
- ✅ **Date Utilities**: formatting, arithmetic, comparisons
- ✅ **Number Utilities**: clamping, rounding, formatting
- ✅ **Validation Helpers**: email, URL, UUID, password validation
- ✅ **Color Utilities**: hex/RGB conversion, color manipulation
- ✅ **Performance Utilities**: timing, batching, measurement
### 10. `src/index.ts` (Entry Point)
Main entry point that imports and demonstrates usage of all modules.
## Project Structure
```
sample_project_typescript/
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
├── README.md # This documentation
└── src/
├── index.ts # Main entry point
├── types-interfaces.ts # Core type system
├── classes-inheritance.ts # OOP features
├── functions-generics.ts # Functions and generics
├── async-promises.ts # Async programming
├── decorators-metadata.ts # Decorators system
├── modules-namespaces.ts # Module organization
├── advanced-types.ts # Advanced type features
├── error-validation.ts # Error handling
└── utilities-helpers.ts # Common utilities
```
## Installation and Setup
### Prerequisites
- Node.js (v16 or higher)
- npm or yarn package manager
### Installation
```bash
# Install dependencies
npm install
# Or with yarn
yarn install
```
### Available Scripts
```bash
# Compile TypeScript
npm run build
# Compile and watch for changes
npm run build:watch
# Run compiled JavaScript
npm start
# Run with ts-node (development)
npm run dev
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Lint code
npm run lint
# Fix lint issues
npm run lint:fix
# Clean build artifacts
npm run clean
```
## TypeScript Configuration
The project uses strict TypeScript settings for maximum type safety:
```json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"exactOptionalPropertyTypes": true,
"noUncheckedIndexedAccess": true,
// ... other strict settings
}
}
```
## Key Features Demonstrated
### Type Safety
- Strict null checks
- Exact optional properties
- No unchecked indexed access
- Comprehensive type annotations
### Modern TypeScript
- Latest ES features (ES2020 target)
- Experimental decorators
- Advanced type manipulations
- Template literal types
### Best Practices
- Proper error handling patterns
- Functional programming concepts
- Design pattern implementations
- Performance optimization techniques
### Real-World Patterns
- Dependency injection
- Validation frameworks
- Async operation management
- Utility library patterns
## Usage Examples
### Basic Type Usage
```typescript
import { User, createUser } from './types-interfaces';
const user: User = {
id: 1,
name: "John Doe",
email: "[email protected]",
createdAt: new Date(),
preferences: {
theme: "dark",
notifications: true,
language: "en"
}
};
```
### Class Inheritance
```typescript
import { Employee, Person } from './classes-inheritance';
const employee = new Employee("Jane Smith", 28, 456, "Engineering", 75000);
console.log(employee.introduce()); // Uses overridden method
employee.celebrateBirthday(); // Accesses protected members
```
### Async Operations
```typescript
import { PromisePool, AsyncCache } from './async-promises';
const pool = new PromisePool(3);
const cache = new AsyncCache(60000);
// Use promise pool for concurrent operations
userIds.forEach(id => {
pool.add(() => fetchUserData(id));
});
const results = await pool.execute();
```
### Advanced Types
```typescript
import { DeepPartial, Paths, Get } from './advanced-types';
type UserUpdate = DeepPartial<User>;
type UserPaths = Paths<User>; // "name" | "email" | "preferences.theme" | etc.
function getValue<T, K extends Paths<T>>(obj: T, path: K): Get<T, K> {
// Type-safe nested property access
}
```
### Error Handling
```typescript
import { Result, Ok, Err, validateUser } from './error-validation';
const result = validateUser(userData);
if (result.success) {
// result.data is properly typed
console.log(result.data.name);
} else {
// result.error contains validation errors
console.error(result.error);
}
```
## Testing with Code Analysis Tools
This project is specifically designed to test various code analysis scenarios:
### Dependency Analysis
- Import/export relationships
- Module dependencies
- Circular dependency detection
### Type Analysis
- Type inference testing
- Generic resolution
- Complex type relationships
### Pattern Recognition
- Design pattern detection
- Common TypeScript idioms
- Best practice validation
### Complexity Metrics
- Cyclomatic complexity
- Type complexity
- Inheritance hierarchies
## Integration with Graph Databases
The project structure supports graph database population for:
### Node Types
- **Files**: Source files, test files, configuration files
- **Classes**: Regular classes, abstract classes, interfaces
- **Functions**: Methods, static methods, constructors
- **Types**: Interfaces, type aliases, enums
- **Variables**: Properties, parameters, local variables
### Relationship Types
- **IMPORTS**: File import relationships
- **EXTENDS**: Class/interface inheritance
- **IMPLEMENTS**: Interface implementation
- **CALLS**: Function call relationships
- **USES**: Type usage relationships
- **CONTAINS**: Containment relationships
### Properties
- **Language Features**: decorators, generics, async/await
- **Access Modifiers**: public, private, protected
- **Type Information**: parameter types, return types
- **Metadata**: JSDoc comments, decorator metadata
## Contributing
When adding new TypeScript features or patterns:
1. Create focused examples in the appropriate file
2. Include comprehensive type annotations
3. Add JSDoc comments for documentation
4. Update this README with new features
5. Ensure examples are realistic and practical
## Language Features Coverage
| Feature Category | Coverage | File Location |
|-----------------|----------|---------------|
| Basic Types | ✅ Complete | `types-interfaces.ts` |
| Classes & OOP | ✅ Complete | `classes-inheritance.ts` |
| Functions & Generics | ✅ Complete | `functions-generics.ts` |
| Async Programming | ✅ Complete | `async-promises.ts` |
| Decorators | ✅ Complete | `decorators-metadata.ts` |
| Modules & Namespaces | ✅ Complete | `modules-namespaces.ts` |
| Advanced Types | ✅ Complete | `advanced-types.ts` |
| Error Handling | ✅ Complete | `error-validation.ts` |
| Utilities | ✅ Complete | `utilities-helpers.ts` |
## Use Cases
This sample project is ideal for:
### Development Tools
- **IDEs**: Testing IntelliSense, refactoring, navigation
- **Linters**: ESLint rule validation, custom rule testing
- **Formatters**: Prettier configuration testing
### Code Analysis
- **Static Analysis**: Type checking, unused code detection
- **Dependency Analysis**: Import graph construction
- **Complexity Analysis**: Metrics calculation
### Learning & Training
- **TypeScript Education**: Comprehensive feature examples
- **Best Practices**: Real-world pattern demonstration
- **Code Reviews**: Reference implementation examples
### Testing & QA
- **Type System Testing**: Edge case coverage
- **Tool Validation**: Ensuring tools handle complex TypeScript
- **Performance Testing**: Large-scale TypeScript compilation
## Versioning
This project follows semantic versioning:
- **Major**: Breaking changes to file structure or major feature additions
- **Minor**: New TypeScript features, enhanced examples
- **Patch**: Bug fixes, documentation improvements, minor updates
Current version: **1.0.0**
## License
MIT License - feel free to use this project for testing, education, or as a reference implementation.
---
*This TypeScript sample project provides comprehensive coverage of modern TypeScript features and patterns, making it an ideal testing ground for code analysis tools, educational purposes, and development tool validation.*
```
--------------------------------------------------------------------------------
/docs/docs/license.md:
--------------------------------------------------------------------------------
```markdown
# License
CodeGraphContext is licensed under the MIT License.
```
MIT License
Copyright (c) 2025
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
```
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
```markdown
# Contributing to CodeGraphContext
We welcome contributions! Please follow these steps:
## General Guidelines
* Ensure your code adheres to the existing style and conventions of the project.
* Write clear, concise, and well-documented code.
* All new features or bug fixes should be accompanied by appropriate tests.
* Keep your pull requests focused on a single feature or bug fix.
## Setting up Your Development Environment
1. Fork the repository.
2. Set up your development environment: `pip install -e ".[dev]"`
3. Create a new branch for your feature or bugfix (e.g., `git checkout -b feature/my-new-feature`).
## Debugging
To enable debug mode for detailed logging, locate the `debug_mode` variable in `src/codegraphcontext/tools/graph_builder.py` and set its value to `1`.
```python
# src/codegraphcontext/tools/graph_builder.py
debug_mode = 1
```
## Running Tests
Tests are located in the `tests/` directory and are run using `pytest`.
1. Navigate to the root of the `CodeGraphContext` directory.
2. Run all tests using the command: `pytest`
3. To run specific tests, you can provide the path to the test file, for example: `pytest tests/test_tools.py`
4. **Skipping Re-indexing:** To speed up test runs, especially during development, you can set the `CGC_SKIP_REINDEX` environment variable to `true`. This will prevent the test suite from re-indexing the sample project if it's already indexed.
```bash
CGC_SKIP_REINDEX=true pytest
```
## Submitting Changes
1. Write your code and add corresponding tests in the `tests/` directory.
2. Ensure all tests pass and your code lints without errors.
3. Commit your changes with a descriptive commit message.
4. Submit a pull request to the `main` branch.
<!-- "Failed to check job status: 'JobManager' object has no attribute 'JobStatus'" -->
```
--------------------------------------------------------------------------------
/docs/docs/contributing.md:
--------------------------------------------------------------------------------
```markdown
# Contributing to CodeGraphContext
We welcome contributions! Please follow these steps:
## General Guidelines
* Ensure your code adheres to the existing style and conventions of the project.
* Write clear, concise, and well-documented code.
* All new features or bug fixes should be accompanied by appropriate tests.
* Keep your pull requests focused on a single feature or bug fix.
## Setting up Your Development Environment
1. Fork the repository.
2. Set up your development environment: `pip install -e ".[dev]"`
3. Create a new branch for your feature or bugfix (e.g., `git checkout -b feature/my-new-feature`).
## Debugging
To enable debug mode for detailed logging, locate the `debug_mode` variable in `src/codegraphcontext/tools/graph_builder.py` and set its value to `1`.
```python
# src/codegraphcontext/tools/graph_builder.py
debug_mode = 1
```
## Running Tests
Tests are located in the `tests/` directory and are run using `pytest`.
1. Navigate to the root of the `CodeGraphContext` directory.
2. Run all tests using the command: `pytest`
3. To run specific tests, you can provide the path to the test file, for example: `pytest tests/test_tools.py`
4. **Skipping Re-indexing:** To speed up test runs, especially during development, you can set the `CGC_SKIP_REINDEX` environment variable to `true`. This will prevent the test suite from re-indexing the sample project if it's already indexed.
```bash
CGC_SKIP_REINDEX=true pytest
```
## Submitting Changes
1. Write your code and add corresponding tests in the `tests/` directory.
2. Ensure all tests pass and your code lints without errors.
3. Commit your changes with a descriptive commit message.
4. Submit a pull request to the `main` branch.
<!-- "Failed to check job status: 'JobManager' object has no attribute 'JobStatus'" -->
```
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
```markdown
# 🛡️ Security Policy
## 📌 Supported Versions
We aim to keep `CodeGraphContext` up to date and secure. Please see below for the versions we currently support with security updates.
| Version | Supported |
|---------|--------------------|
| Latest | ✅ Yes |
| Older | ❌ No |
---
## 📬 Reporting a Vulnerability
If you discover a security vulnerability, **please do not open an issue** on GitHub.
Instead, follow these steps:
1. **Email the maintainer directly**
2. Include the following details:
- Description of the vulnerability
- Steps to reproduce (if possible)
- Potential impact
- Any mitigation or workaround suggestions
⌛ We aim to respond to security reports **within 72 hours**.
---
## 🚫 Responsible Disclosure Guidelines
We ask that you:
- Do not publicly disclose the issue until it has been resolved.
- Avoid testing vulnerabilities in a way that could disrupt services.
- Act in good faith and with respect for user data and privacy.
---
## 📃 Disclosure Policy
- We follow a **coordinated disclosure** approach.
- We appreciate responsible reporting and will publicly disclose the issue only **after a fix has been released**.
---
## ✅ Security Best Practices
While using this project, we recommend you:
- Always run software in a secure and isolated environment.
- Keep your dependencies up to date.
- Avoid sharing sensitive API keys or credentials in `.env` or other public files.
---
## 🙏 Acknowledgments
We value the contributions from the community and encourage responsible disclosure to help keep `CodeGraphContext` safe and secure for all users.
---
## 🔒 Resources
- [GitHub Security Advisories](https://docs.github.com/en/code-security/security-advisories)
- [OpenSSF Best Practices](https://bestpractices.dev/)
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/__init__.py:
--------------------------------------------------------------------------------
```python
```
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
```python
```
--------------------------------------------------------------------------------
/tests/sample_project_php/error_handling.php:
--------------------------------------------------------------------------------
```php
```
--------------------------------------------------------------------------------
/tests/sample_project/edge_cases/empty.py:
--------------------------------------------------------------------------------
```python
```
--------------------------------------------------------------------------------
/tests/test_tree_sitter/__init__.py:
--------------------------------------------------------------------------------
```python
```
--------------------------------------------------------------------------------
/tests/sample_project/edge_cases/docstring_only.py:
--------------------------------------------------------------------------------
```python
"""Only a docstring."""
```
--------------------------------------------------------------------------------
/tests/sample_project/edge_cases/comments_only.py:
--------------------------------------------------------------------------------
```python
# comment only
# nothing here
```
--------------------------------------------------------------------------------
/tests/sample_project/edge_cases/syntax_error.py:
--------------------------------------------------------------------------------
```python
def broken_func(
return 1
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.jp.min.js:
--------------------------------------------------------------------------------
```javascript
module.exports=require("./lunr.ja");
```
--------------------------------------------------------------------------------
/src/codegraphcontext/cli/__init__.py:
--------------------------------------------------------------------------------
```python
# src/codegraphcontext/cli/__init__.py
```
--------------------------------------------------------------------------------
/website/src/vite-env.d.ts:
--------------------------------------------------------------------------------
```typescript
/// <reference types="vite/client" />
```
--------------------------------------------------------------------------------
/src/codegraphcontext/core/__init__.py:
--------------------------------------------------------------------------------
```python
# src/codegraphcontext/core/__init__.py
```
--------------------------------------------------------------------------------
/tests/sample_project/module_c/__init__.py:
--------------------------------------------------------------------------------
```python
__all__ = ['submodule1', 'submodule2']
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/module_example.rb:
--------------------------------------------------------------------------------
```ruby
module MathTools
def square(x)
x * x
end
end
```
--------------------------------------------------------------------------------
/tests/sample_project/namespace_pkg/ns_module.py:
--------------------------------------------------------------------------------
```python
def ns_func():
return 'I am in a namespace package'
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/function_chain.h:
--------------------------------------------------------------------------------
```
// function_chain.h
#pragma once
void functionChainDemo();
```
--------------------------------------------------------------------------------
/tests/sample_project/circular1.py:
--------------------------------------------------------------------------------
```python
from circular2 import func2
def func1():
return func2()
```
--------------------------------------------------------------------------------
/tests/test_tree_sitter/complex_classes.py:
--------------------------------------------------------------------------------
```python
class Z:
def greet(self):
return "Z's complex greeting"
```
--------------------------------------------------------------------------------
/tests/sample_project/circular2.py:
--------------------------------------------------------------------------------
```python
from circular1 import func1
def func2():
return 'ok_from_circular2'
```
--------------------------------------------------------------------------------
/tests/sample_project_java/src/com/example/app/model/Role.java:
--------------------------------------------------------------------------------
```java
package com.example.app.model;
public enum Role { ADMIN, EDITOR, VIEWER }
```
--------------------------------------------------------------------------------
/src/codegraphcontext/__init__.py:
--------------------------------------------------------------------------------
```python
# src/codegraphcontext/__init__.py
# This makes 'codegraphcontext' a package.
```
--------------------------------------------------------------------------------
/website/postcss.config.js:
--------------------------------------------------------------------------------
```javascript
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
```
--------------------------------------------------------------------------------
/website/src/components/ui/use-toast.ts:
--------------------------------------------------------------------------------
```typescript
import { useToast, toast } from "@/hooks/use-toast";
export { useToast, toast };
```
--------------------------------------------------------------------------------
/tests/sample_project/module_c/submodule1.py:
--------------------------------------------------------------------------------
```python
from module_b import helper
def call_helper_twice(x):
return helper(x) + helper(x + 1)
```
--------------------------------------------------------------------------------
/tests/sample_project_c/src/math/vec.c:
--------------------------------------------------------------------------------
```cpp
#include "math/vec.h"
Vec3 vec_add(Vec3 a, Vec3 b) { return (Vec3){a.x+b.x, a.y+b.y, a.z+b.z}; }
```
--------------------------------------------------------------------------------
/src/codegraphcontext/__main__.py:
--------------------------------------------------------------------------------
```python
# src/codegraphcontext/__main__.py
from .cli.main import app
if __name__ == "__main__":
app()
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/main.cpp:
--------------------------------------------------------------------------------
```cpp
#include <iostream>
int main() {
std::cout << "C++ Sample Project Running!\n";
return 0;
}
```
--------------------------------------------------------------------------------
/tests/sample_project/module_c/submodule2.py:
--------------------------------------------------------------------------------
```python
from module_c.submodule1 import call_helper_twice
def wrapper(x):
return call_helper_twice(x) * 2
```
--------------------------------------------------------------------------------
/tests/sample_project_c/include/math/vec.h:
--------------------------------------------------------------------------------
```
#ifndef VEC_H
#define VEC_H
typedef struct { float x, y, z; } Vec3;
Vec3 vec_add(Vec3 a, Vec3 b);
#endif
```
--------------------------------------------------------------------------------
/tests/sample_project_c/src/util.c:
--------------------------------------------------------------------------------
```cpp
#include "util.h"
int g_counter = 0; // definition
int max_int(int a, int b) { return a > b ? a : b; }
```
--------------------------------------------------------------------------------
/website/vercel.json:
--------------------------------------------------------------------------------
```json
{
"rewrites": [
{
"source": "/api/pypi/:path*",
"destination": "/api/pypi"
}
]
}
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/class_example.rb:
--------------------------------------------------------------------------------
```ruby
class Greeter
def initialize(name)
@name = name
end
def greet
"Hello, #{@name}!"
end
end
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/edge_cases.cpp:
--------------------------------------------------------------------------------
```cpp
// Demonstrates edge cases: empty, comments only, etc.
// This file intentionally left mostly blank.
// ...
```
--------------------------------------------------------------------------------
/docs/site/sitemap.xml:
--------------------------------------------------------------------------------
```
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
</urlset>
```
--------------------------------------------------------------------------------
/tests/sample_project/import_reexports.py:
--------------------------------------------------------------------------------
```python
def core_function(): return 'core'
def reexport(): return core_function()
import math as m
val = m.sqrt(16)
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/events.js:
--------------------------------------------------------------------------------
```javascript
// Event listeners (run in browser)
document.addEventListener("click", () => {
alert("You clicked the page!");
});
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/error_handling.rb:
--------------------------------------------------------------------------------
```ruby
begin
num = 10 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
ensure
puts "Execution finished"
end
```
--------------------------------------------------------------------------------
/tests/sample_project_c/include/config.h:
--------------------------------------------------------------------------------
```
#ifndef CONFIG_H
#define CONFIG_H
#define APP_NAME "CgcSample"
#define APP_VERSION "0.1.0"
#define ENABLE_STATS 1
#endif
```
--------------------------------------------------------------------------------
/tests/test_tree_sitter/class_instantiation.py:
--------------------------------------------------------------------------------
```python
class A:
def greet(self):
return "A's greeting"
class B(A):
def greet(self):
return super().greet()
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/file_io.rb:
--------------------------------------------------------------------------------
```ruby
File.open("example.txt", "w") { |f| f.puts "Hello Ruby File!" }
content = File.read("example.txt")
puts "File says: #{content}"
```
--------------------------------------------------------------------------------
/tests/sample_project_java/src/com/example/app/service/GreetingService.java:
--------------------------------------------------------------------------------
```java
package com.example.app.service;
import com.example.app.model.User;
public interface GreetingService {
String greet(User user);
}
```
--------------------------------------------------------------------------------
/tests/sample_project_c/include/module.h:
--------------------------------------------------------------------------------
```
#ifndef MODULE_H
#define MODULE_H
typedef enum { MODE_A=0, MODE_B=1 } Mode;
void module_init(Mode m);
int module_compute(int base);
#endif
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/mixins_example.rb:
--------------------------------------------------------------------------------
```ruby
module Flyable
def fly
"#{@name} is flying!"
end
end
class Bird
include Flyable
def initialize(name)
@name = name
end
end
```
--------------------------------------------------------------------------------
/website/src/components/ui/aspect-ratio.tsx:
--------------------------------------------------------------------------------
```typescript
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
const AspectRatio = AspectRatioPrimitive.Root;
export { AspectRatio };
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/enumerables.rb:
--------------------------------------------------------------------------------
```ruby
numbers = [1, 2, 3, 4, 5]
squares = numbers.map { |n| n * n }
evens = numbers.select(&:even?)
puts "Squares: #{squares}"
puts "Evens: #{evens}"
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/errorHandling.js:
--------------------------------------------------------------------------------
```javascript
// Try/catch error handling
try {
throw new Error("Something went wrong!");
} catch (error) {
console.error("Caught error:", error.message);
}
```
--------------------------------------------------------------------------------
/tests/sample_project/async_features.py:
--------------------------------------------------------------------------------
```python
import asyncio
async def fetch_data(x):
await asyncio.sleep(0)
return x * 2
async def main():
result = await fetch_data(10)
return result
```
--------------------------------------------------------------------------------
/website/public/robots.txt:
--------------------------------------------------------------------------------
```
User-agent: Googlebot
Allow: /
User-agent: Bingbot
Allow: /
User-agent: Twitterbot
Allow: /
User-agent: facebookexternalhit
Allow: /
User-agent: *
Allow: /
```
--------------------------------------------------------------------------------
/tests/sample_project/advanced_imports.py:
--------------------------------------------------------------------------------
```python
def outer_import():
import math
return math.sqrt(25)
if True:
import random
else:
import sys
def use_random():
return random.randint(1, 10)
```
--------------------------------------------------------------------------------
/tests/sample_project_c/include/platform.h:
--------------------------------------------------------------------------------
```
#ifndef PLATFORM_H
#define PLATFORM_H
#if defined(_WIN32) || defined(_WIN64)
#define CGC_PLATFORM_WINDOWS 1
#else
#define CGC_PLATFORM_POSIX 1
#endif
#endif
```
--------------------------------------------------------------------------------
/tests/sample_project_java/src/com/example/app/annotations/Logged.java:
--------------------------------------------------------------------------------
```java
package com.example.app.annotations;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Logged {}
```
--------------------------------------------------------------------------------
/tests/sample_project_rust/Cargo.toml:
--------------------------------------------------------------------------------
```toml
[package]
name = "sample_project_rust"
version = "0.1.0"
edition = "2021"
[dependencies]
[dev-dependencies]
[lib]
name = "sample_project_rust"
path = "src/lib.rs"
```
--------------------------------------------------------------------------------
/website/src/lib/utils.ts:
--------------------------------------------------------------------------------
```typescript
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
```
--------------------------------------------------------------------------------
/tests/sample_project/module_b.py:
--------------------------------------------------------------------------------
```python
value = 42
def helper(x):
return x + 1
def process_data(data):
return sum(data)
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/inheritance_example.rb:
--------------------------------------------------------------------------------
```ruby
class Animal
def initialize(name)
@name = name
end
def speak
"#{@name} makes a sound."
end
end
class Dog < Animal
def speak
"#{@name} barks!"
end
end
```
--------------------------------------------------------------------------------
/tests/sample_project/pattern_matching.py:
--------------------------------------------------------------------------------
```python
def matcher(x):
match x:
case 0: return 'zero'
case 1 | 2: return 'one or two'
case str() as s: return f'string: {s}'
case _: return 'other'
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/namespaces.cpp:
--------------------------------------------------------------------------------
```cpp
// Demonstrates namespaces and using directive
#include <iostream>
namespace foo {
void bar() { std::cout << "foo::bar\n"; }
}
void namespaceDemo() {
using namespace foo;
bar();
}
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/variables.js:
--------------------------------------------------------------------------------
```javascript
// Demonstrating variable declarations in JavaScript
var a = 10; // function-scoped
let b = 20; // block-scoped
const c = 30; // block-scoped and constant
console.log(a, b, c);
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/promises.js:
--------------------------------------------------------------------------------
```javascript
// Promise chaining
const fetchData = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("Data loaded"), 1000);
});
};
fetchData().then(data => {
console.log(data);
});
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/tests/test_sample.rb:
--------------------------------------------------------------------------------
```ruby
require 'minitest/autorun'
require_relative '../class_example'
class TestGreeter < Minitest::Test
def test_greet
g = Greeter.new("World")
assert_equal "Hello, World!", g.greet
end
end
```
--------------------------------------------------------------------------------
/tests/sample_project/context_managers.py:
--------------------------------------------------------------------------------
```python
class FileOpener:
def __enter__(self):
return 'opened'
def __exit__(self, exc_type, exc_val, exc_tb):
return False
def use_file():
with FileOpener() as f:
return f
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/query_tool_languages/c_toolkit.py:
--------------------------------------------------------------------------------
```python
class CToolkit:
"""Template placeholder for future implementation."""
def get_cypher_query(query: str) -> str:
raise NotImplementedError("AdvancedLanguageQuery is not implemented yet.")
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/query_tool_languages/go_toolkit.py:
--------------------------------------------------------------------------------
```python
class GoToolkit:
"""Template placeholder for future implementation."""
def get_cypher_query(query: str) -> str:
raise NotImplementedError("AdvancedLanguageQuery is not implemented yet.")
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/query_tool_languages/java_toolkit.py:
--------------------------------------------------------------------------------
```python
class JavaToolkit:
"""Template placeholder for future implementation."""
def get_cypher_query(query: str) -> str:
raise NotImplementedError("AdvancedLanguageQuery is not implemented yet.")
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/query_tool_languages/ruby_toolkit.py:
--------------------------------------------------------------------------------
```python
class RubyToolkit:
"""Template placeholder for future implementation."""
def get_cypher_query(query: str) -> str:
raise NotImplementedError("AdvancedLanguageQuery is not implemented yet.")
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/query_tool_languages/rust_toolkit.py:
--------------------------------------------------------------------------------
```python
class RustToolkit:
"""Template placeholder for future implementation."""
def get_cypher_query(query: str) -> str:
raise NotImplementedError("AdvancedLanguageQuery is not implemented yet.")
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/query_tool_languages/python_toolkit.py:
--------------------------------------------------------------------------------
```python
class PythonToolkit:
"""Template placeholder for future implementation."""
def get_cypher_query(query: str) -> str:
raise NotImplementedError("AdvancedLanguageQuery is not implemented yet.")
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/query_tool_languages/javascript_toolkit.py:
--------------------------------------------------------------------------------
```python
class JavascriptToolkit:
"""Template placeholder for future implementation."""
def get_cypher_query(query: str) -> str:
raise NotImplementedError("AdvancedLanguageQuery is not implemented yet.")
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/query_tool_languages/typescript_toolkit.py:
--------------------------------------------------------------------------------
```python
class TypescriptToolkit:
"""Template placeholder for future implementation."""
def get_cypher_query(query: str) -> str:
raise NotImplementedError("AdvancedLanguageQuery is not implemented yet.")
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/asyncAwait.js:
--------------------------------------------------------------------------------
```javascript
// Async/await syntax
const getData = async () => {
const result = await fetchData();
console.log("Async result:", result);
};
getData();
async function fetchData() {
return "Fetched with async/await";
}
```
--------------------------------------------------------------------------------
/tests/sample_project_php/edgecases.php:
--------------------------------------------------------------------------------
```php
<?php
var_dump("0" == 0);
var_dump("0" === 0);
$arr = [1 => "one", "1" => "uno"];
print_r($arr);
var_dump(null == "");
var_dump(null === "");
$a = true + false;
$b = "5 apples" + 2;
echo $a . "\n";
echo $b . "\n";
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/dom.js:
--------------------------------------------------------------------------------
```javascript
// Basic DOM manipulation (run in browser)
document.body.style.backgroundColor = "lightblue";
const heading = document.createElement("h1");
heading.textContent = "Hello from JavaScript!";
document.body.appendChild(heading);
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/fetchAPI.js:
--------------------------------------------------------------------------------
```javascript
// Fetch API (run in browser or Node with fetch support)
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error("Error:", err));
```
--------------------------------------------------------------------------------
/tests/sample_project/typing_examples.py:
--------------------------------------------------------------------------------
```python
from typing import List, Dict, Union
def typed_func(a: int, b: str) -> List[str]:
return [b] * a
def union_func(x: Union[int, str]) -> str:
return str(x)
def dict_func(d: Dict[str, int]) -> int:
return sum(d.values())
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/fixtures/js/accessors.js:
--------------------------------------------------------------------------------
```javascript
class Demo {
get value() { return this._v }
set value(x) { this._v = x }
static ping() { return "pong" }
}
const obj = {
get foo() { return 1 },
set foo(v) { this._f = v },
bar() { return 2 } // regular method (no type)
}
```
--------------------------------------------------------------------------------
/website/src/components/ui/skeleton.tsx:
--------------------------------------------------------------------------------
```typescript
import { cn } from "@/lib/utils";
function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div className={cn("animate-pulse rounded-md bg-muted", className)} {...props} />;
}
export { Skeleton };
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/arrays.js:
--------------------------------------------------------------------------------
```javascript
// Array methods: map, filter, reduce
const nums = [1, 2, 3, 4, 5];
const doubled = nums.map(n => n * 2);
const evens = nums.filter(n => n % 2 === 0);
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(doubled, evens, sum);
```
--------------------------------------------------------------------------------
/tests/sample_project/datatypes.py:
--------------------------------------------------------------------------------
```python
from dataclasses import dataclass
import enum
from collections import namedtuple
@dataclass
class Point:
x: int
y: int
class Color(enum.Enum):
RED = 1
GREEN = 2
BLUE = 3
Person = namedtuple('Person', ['name', 'age'])
```
--------------------------------------------------------------------------------
/tests/sample_project_java/src/com/example/app/service/AbstractGreeter.java:
--------------------------------------------------------------------------------
```java
package com.example.app.service;
import com.example.app.annotations.Logged;
import com.example.app.model.User;
public abstract class AbstractGreeter {
@Logged
protected String base(User u) {
return "Hello, " + u.getName();
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/stl_usage.cpp:
--------------------------------------------------------------------------------
```cpp
// Demonstrates STL containers and algorithms
#include <iostream>
#include <vector>
#include <algorithm>
void stlDemo() {
std::vector<int> v = {1, 2, 3};
std::for_each(v.begin(), v.end(), [](int x){ std::cout << x << ' '; });
std::cout << std::endl;
}
```
--------------------------------------------------------------------------------
/website/src/main.tsx:
--------------------------------------------------------------------------------
```typescript
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import "aos/dist/aos.css";
createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/function_chain.cpp:
--------------------------------------------------------------------------------
```cpp
// Demonstrates function pointers and lambdas
#include <iostream>
#include <functional>
void callTwice(const std::function<void()>& f) {
f(); f();
}
void functionChainDemo() {
auto lambda = [](){ std::cout << "Hello from lambda\n"; };
callTwice(lambda);
}
```
--------------------------------------------------------------------------------
/tests/sample_project/module_a.py:
--------------------------------------------------------------------------------
```python
import math
import module_b as mb
from module_b import process_data
def foo(x):
return mb.helper(x) + mb.value + process_data([x])
def bar():
return math.sqrt(16)
nested = lambda x: x * 2
def outer():
def inner(y):
return y + 1
return inner(5)
```
--------------------------------------------------------------------------------
/tests/sample_project/advanced_functions.py:
--------------------------------------------------------------------------------
```python
def with_defaults(a, b=5, c='hello'):
return f"{a}-{b}-{c}"
def with_args_kwargs(*args, **kwargs):
return args, kwargs
def higher_order(func, data):
return [func(x) for x in data]
def return_function(x):
def inner(y):
return x + y
return inner
```
--------------------------------------------------------------------------------
/tests/sample_project/advanced_calls.py:
--------------------------------------------------------------------------------
```python
def square(x): return x * x
def calls():
data = [1, 2, 3]
result1 = [square(x) for x in data]
result2 = list(map(square, data))
obj = Dummy()
result3 = getattr(obj, 'method')(5)
return result1, result2, result3
class Dummy:
def method(self, x): return x + 10
```
--------------------------------------------------------------------------------
/tests/sample_project_php/file_handling.php:
--------------------------------------------------------------------------------
```php
<?php
$file = "shashank.txt";
try {
file_put_contents($file, "Hello Shashank\n");
file_put_contents($file, "Welcome to PHP\n", FILE_APPEND);
$data = file_get_contents($file);
echo $data;
unlink($file);
} catch (Exception $e) {
echo "File error: " . $e->getMessage();
}
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/metaprogramming.rb:
--------------------------------------------------------------------------------
```ruby
class DynamicGreeter
[:hello, :goodbye].each do |method|
define_method(method) do |name|
"#{method.capitalize}, #{name}!"
end
end
def method_missing(name, *args)
"Method #{name} not defined"
end
end
dg = DynamicGreeter.new
puts dg.hello("Name")
puts dg.foobar("X")
```
--------------------------------------------------------------------------------
/tests/sample_project_c/src/module.c:
--------------------------------------------------------------------------------
```cpp
#include "module.h"
#include "util.h"
static int s_secret = 42; // file-local static
void module_init(Mode m) {
(void)m;
s_secret = 42;
}
int module_compute(int base) {
#if ENABLE_STATS
g_counter++;
#endif
return clamp(base + s_secret, 0, 1000); // uses inline from util.h
}
```
--------------------------------------------------------------------------------
/tests/sample_project/callbacks_decorators.py:
--------------------------------------------------------------------------------
```python
def executor(func, val):
return func(val)
def square(x): return x * x
res = executor(square, 5)
def log_decorator(fn):
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
@log_decorator
def hello(name): return f'Hello {name}'
msg = hello('Shashank')
```
--------------------------------------------------------------------------------
/tests/sample_project/comprehensions_generators.py:
--------------------------------------------------------------------------------
```python
def double(x): return x * 2
nums = [double(i) for i in range(5)]
gen = (double(i) for i in range(5))
values = list(gen)
words = ['apple', 'banana', 'pear']
sorted_words = sorted(words, key=len)
with open('temp.txt', 'w') as f:
f.write('hello')
with open('temp.txt', 'r') as f:
data = f.read()
```
--------------------------------------------------------------------------------
/tests/sample_project_php/functions.php:
--------------------------------------------------------------------------------
```php
<?php
function greet($name, $age = 20) {
return "Hello {$name}, you are {$age} years old";
}
function sumNumbers(...$nums) {
return array_sum($nums);
}
$double = function($n) {
return $n * 2;
};
echo greet("Shashank", 21) . "\n";
echo sumNumbers(1,2,3,4) . "\n";
echo $double(5) . "\n";
```
--------------------------------------------------------------------------------
/tests/sample_project_java/src/com/example/app/model/User.java:
--------------------------------------------------------------------------------
```java
package com.example.app.model;
public class User {
private final String name;
private final Role role;
public User(String name, Role role) {
this.name = name;
this.role = role;
}
public String getName() { return name; }
public Role getRole() { return role; }
}
```
--------------------------------------------------------------------------------
/tests/sample_project_misc/styles.css:
--------------------------------------------------------------------------------
```css
body {
font-family: Arial, sans-serif;
background: #f9f9f9;
color: #222;
margin: 0;
padding: 2rem;
}
h1 {
color: #007acc;
}
button {
background: #007acc;
color: #fff;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background: #005fa3;
}
```
--------------------------------------------------------------------------------
/tests/sample_project/mapping_calls.py:
--------------------------------------------------------------------------------
```python
class Dispatcher:
def __init__(self):
self._map = {'start': self.start, 'stop': self.stop}
def start(self): return 'started'
def stop(self): return 'stopped'
def call(self, cmd):
return self._map[cmd]()
def use_dispatcher(cmd):
d = Dispatcher()
return d.call(cmd)
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/main.rb:
--------------------------------------------------------------------------------
```ruby
require_relative 'class_example'
require_relative 'inheritance_example'
require_relative 'module_example'
require_relative 'mixins_example'
puts "=== Ruby Sample Project ==="
greeter = Greeter.new("Name")
puts greeter.greet
dog = Dog.new("Rex")
puts dog.speak
include MathTools
puts "Square of 4: #{square(4)}"
```
--------------------------------------------------------------------------------
/website/src/components/ui/collapsible.tsx:
--------------------------------------------------------------------------------
```typescript
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
const Collapsible = CollapsiblePrimitive.Root;
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger;
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent;
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
```
--------------------------------------------------------------------------------
/tests/sample_project/function_chains.py:
--------------------------------------------------------------------------------
```python
def f1(x): return x + 1
def f2(x): return x * 2
def f3(x): return x - 3
result = f1(f2(f3(10)))
text = ' Hello World '
cleaned = text.strip().lower().replace('hello', 'hi')
def make_adder(n):
def adder(x):
return x + n
return adder
adder5 = make_adder(5)
result2 = adder5(10)
result3 = make_adder(2)(8)
```
--------------------------------------------------------------------------------
/tests/sample_project_c/include/util.h:
--------------------------------------------------------------------------------
```
#ifndef UTIL_H
#define UTIL_H
#include <stddef.h>
extern int g_counter; // extern variable
typedef struct { int x, y; } Point;
typedef int (*cmp_fn)(int, int); // function pointer typedef
int max_int(int a, int b);
static inline int clamp(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); }
#endif
```
--------------------------------------------------------------------------------
/website/src/components/ThemeProvider.tsx:
--------------------------------------------------------------------------------
```typescript
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
import { type ThemeProviderProps } from "next-themes/dist/types"
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/file_io.cpp:
--------------------------------------------------------------------------------
```cpp
// Demonstrates file I/O in C++
#include <iostream>
#include <fstream>
#include "function_chain.h"
void fileIODemo() {
std::ofstream out("out.txt");
out << "Hello, file!" << std::endl;
out.close();
functionChainDemo();
std::ifstream in("out.txt");
std::string line;
std::cout << line << std::endl;
}
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/raii_example.cpp:
--------------------------------------------------------------------------------
```cpp
// Demonstrates RAII (Resource Acquisition Is Initialization)
#include <iostream>
class File {
public:
File(const char* name) { std::cout << "Opening " << name << std::endl; }
~File() { std::cout << "Closing file" << std::endl; }
};
void raiiDemo() {
File f("test.txt");
std::cout << "Using file..." << std::endl;
}
```
--------------------------------------------------------------------------------
/tests/sample_project_java/src/com/example/app/util/CollectionUtils.java:
--------------------------------------------------------------------------------
```java
package com.example.app.util;
import java.util.Collection;
public final class CollectionUtils {
private CollectionUtils() {}
public static <T extends Number> int sumOfSquares(Collection<T> nums) {
return nums.stream().mapToInt(n -> {
int v = n.intValue();
return v * v;
}).sum();
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_php/Inheritance.php:
--------------------------------------------------------------------------------
```php
<?php
abstract class Animal {
abstract public function sound();
}
class Dog extends Animal {
public function sound() {
return "Woof!";
}
}
class Cat extends Animal {
public function sound() {
return "Meow!";
}
}
$dog = new Dog();
$cat = new Cat();
echo $dog->sound() . "\n";
echo $cat->sound() . "\n";
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/exporter.js:
--------------------------------------------------------------------------------
```javascript
export function exportedFunction() {
return "This is an exported function.";
}
export class ExportedClass {
constructor() {
this.name = "ExportedClass";
}
}
export default function defaultExportedFunction() {
return "This is a default exported function.";
}
export const exportedVariable = "This is an exported variable.";
```
--------------------------------------------------------------------------------
/tests/sample_project_misc/index.html:
--------------------------------------------------------------------------------
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample Misc Project</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Hello, World!</h1>
<p id="message">This is a sample HTML file for the sample misc test.</p>
</body>
</html>
```
--------------------------------------------------------------------------------
/tests/sample_project_php/classes_objects.php:
--------------------------------------------------------------------------------
```php
<?php
class Person {
public $name;
public $age;
function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
function introduce() {
return "Hi, I'm {$this->name} and I'm {$this->age} years old";
}
}
$shashank = new Person("Shashank", 22);
echo $shashank->introduce() . "\n";
```
--------------------------------------------------------------------------------
/tests/sample_project/generators.py:
--------------------------------------------------------------------------------
```python
def gen_numbers(n):
for i in range(n):
yield i
async def agen_numbers(n):
for i in range(n):
yield i
async def async_with_example():
async with AsyncCM() as val:
return val
class AsyncCM:
async def __aenter__(self): return 'async_entered'
async def __aexit__(self, exc_type, exc_val, exc_tb): return False
```
--------------------------------------------------------------------------------
/tests/sample_project/cli_and_dunder.py:
--------------------------------------------------------------------------------
```python
import argparse
import advanced_functions
def run(argv=None):
parser = argparse.ArgumentParser(prog='cli_and_dunder')
parser.add_argument('--a', type=int, default=1)
parser.add_argument('--b', type=int, default=2)
ns = parser.parse_args(argv)
print(advanced_functions.with_defaults(ns.a, ns.b))
if __name__ == '__main__':
run()
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/templates.cpp:
--------------------------------------------------------------------------------
```cpp
// Demonstrates templates and specialization
#include <iostream>
template<typename T>
T add(T a, T b) { return a + b; }
template<>
std::string add(std::string a, std::string b) { return a + " (specialized) " + b; }
void templateDemo() {
std::cout << add(2, 3) << std::endl;
std::cout << add(std::string("foo"), std::string("bar")) << std::endl;
}
```
--------------------------------------------------------------------------------
/tests/sample_project_php/globals_superglobals.php:
--------------------------------------------------------------------------------
```php
<?php
// simulating for learning purposes
$_GET['name'] = "Shashank";
$_POST['age'] = 22;
// always validate user input
$name = htmlspecialchars($_GET['name']);
$age = filter_var($_POST['age'], FILTER_VALIDATE_INT);
echo $name . "\n";
echo $age . "\n";
$GLOBALS['x'] = 10;
function addFive(): void {
$GLOBALS['x'] += 5;
}
addFive();
echo $GLOBALS['x'] . "\n";
```
--------------------------------------------------------------------------------
/website/tsconfig.json:
--------------------------------------------------------------------------------
```json
{
"files": [],
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"noImplicitAny": false,
"noUnusedParameters": false,
"skipLibCheck": true,
"allowJs": true,
"noUnusedLocals": false,
"strictNullChecks": false
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_java/src/com/example/app/service/impl/GreetingServiceImpl.java:
--------------------------------------------------------------------------------
```java
package com.example.app.service.impl;
import com.example.app.model.User;
import com.example.app.service.AbstractGreeter;
import com.example.app.service.GreetingService;
public class GreetingServiceImpl extends AbstractGreeter implements GreetingService {
@Override
public String greet(User user) {
return base(user) + " (" + user.getRole() + ")";
}
}
```
--------------------------------------------------------------------------------
/website/api/pypi.ts:
--------------------------------------------------------------------------------
```typescript
// api/pypi.ts
export default async function handler(req: any, res: any) {
const path = req.url?.replace("/api/pypi", "") || "";
try {
const response = await fetch(`https://pypistats.org/api${path}`);
const data = await response.json();
res.status(200).json(data);
} catch (err) {
res.status(500).json({ error: "Failed to fetch PyPI stats" });
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/classes.cpp:
--------------------------------------------------------------------------------
```cpp
// Demonstrates classes, inheritance, and polymorphism
#include <iostream>
class Animal {
public:
virtual void speak() const { std::cout << "Animal sound\n"; }
virtual ~Animal() = default;
};
class Dog : public Animal {
public:
void speak() const override { std::cout << "Woof!\n"; }
};
void classDemo() {
Animal* a = new Dog();
a->speak();
delete a;
}
```
--------------------------------------------------------------------------------
/tests/sample_project/class_instantiation.py:
--------------------------------------------------------------------------------
```python
class A:
def greet(self): return 'Hello from A'
class B(A):
def greet(self): return super().greet() + ' + B'
obj = A()
msg1 = obj.greet()
obj2 = B()
msg2 = obj2.greet()
class Fluent:
def step1(self): return self
def step2(self): return self
def step3(self): return self
f = Fluent().step1().step2().step3()
obj2.dynamic = lambda x: x * 2
val = obj2.dynamic(10)
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/control_flow.cpp:
--------------------------------------------------------------------------------
```cpp
// Demonstrates control flow constructs in C++
#include <iostream>
void controlFlow(int x) {
if (x > 0) std::cout << "positive\n";
else if (x == 0) std::cout << "zero\n";
else std::cout << "negative\n";
std::cout << ((x > 0) ? "pos" : "non-pos") << std::endl;
for (int i = 0; i < 3; ++i) std::cout << i << ' ';
std::cout << std::endl;
}
// ...existing code...
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/exceptions.cpp:
--------------------------------------------------------------------------------
```cpp
// Demonstrates exception handling in C++
#include <iostream>
#include <stdexcept>
void exceptionDemo(int x) {
try {
if (x == 0) throw std::invalid_argument("zero");
std::cout << 10 / x << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << e.what() << std::endl;
} catch (...) {
std::cout << "Unknown error" << std::endl;
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project/dynamic_imports.py:
--------------------------------------------------------------------------------
```python
import importlib
def import_optional():
try:
import ujson as json
except ImportError:
import json
return json.dumps({'a': 1})
def import_by___import__(name):
mod = __import__(name)
return getattr(mod, 'platform', None)
def importlib_runtime(name, attr=None):
mod = importlib.import_module(name)
if attr:
return getattr(mod, attr)
return mod
```
--------------------------------------------------------------------------------
/tests/sample_project/edge_cases/hardcoded_secrets.py:
--------------------------------------------------------------------------------
```python
def connect_to_service():
password = "supersecret123"
api_key = "AKIAIOSFODNN7EXAMPLE"
secret_token = "ghp_16charactertoken"
# Simulate usage
print("Connecting with password:", password)
print("Using API key:", api_key)
print("Token:", secret_token)
return True
def harmless_function():
value = 42
print("This function does not use secrets.")
return value
```
--------------------------------------------------------------------------------
/tests/sample_project_java/sources.txt:
--------------------------------------------------------------------------------
```
src/com/example/app/misc/Outer.java
src/com/example/app/util/IOHelper.java
src/com/example/app/util/CollectionUtils.java
src/com/example/app/annotations/Logged.java
src/com/example/app/Main.java
src/com/example/app/model/User.java
src/com/example/app/model/Role.java
src/com/example/app/service/impl/GreetingServiceImpl.java
src/com/example/app/service/AbstractGreeter.java
src/com/example/app/service/GreetingService.java
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/importer.js:
--------------------------------------------------------------------------------
```javascript
import defaultExport, { exportedFunction, ExportedClass, exportedVariable as myVar } from './exporter.js';
import * as exporter from './exporter.js';
const { exportedFunction: destructuredFunc } = exporter;
console.log(defaultExport());
console.log(exportedFunction());
const instance = new ExportedClass();
console.log(instance.name);
console.log(myVar);
console.log(exporter.exportedVariable);
console.log(destructuredFunc());
```
--------------------------------------------------------------------------------
/tests/sample_project_java/src/com/example/app/misc/Outer.java:
--------------------------------------------------------------------------------
```java
package com.example.app.misc;
public class Outer {
private final String name;
public Outer(String name) { this.name = name; }
public class Inner {
private final String name;
public Inner(String name) { this.name = name; }
public String combine() {
Thread t = new Thread(() -> { /* no-op */ });
t.start();
return Outer.this.name + "+" + this.name;
}
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_php/interface_traits.php:
--------------------------------------------------------------------------------
```php
<?php
interface Greeter {
public function greet();
}
trait Logger {
public function log($msg) {
echo "[LOG] $msg\n";
}
}
class Human implements Greeter {
use Logger;
public $name;
public function __construct($name) {
$this->name = $name;
}
public function greet() {
return "Hello, I am {$this->name}";
}
}
$shashank = new Human("Shashank");
echo $shashank->greet() . "\n";
$shashank->log("Greeting done");
```
--------------------------------------------------------------------------------
/tests/sample_project/complex_classes.py:
--------------------------------------------------------------------------------
```python
class Base:
def greet(self):
return "hello"
class Child(Base):
def greet(self):
return super().greet() + " world"
@staticmethod
def static_method(x):
return x * 2
@classmethod
def class_method(cls, y):
return cls().greet(cls()) + str(y)
def decorator(func):
def wrapper(*args, **kwargs):
return "decorated: " + str(func(*args, **kwargs))
return wrapper
@decorator
def decorated_function(x):
return x + 10
```
--------------------------------------------------------------------------------
/docs/mkdocs.yml:
--------------------------------------------------------------------------------
```yaml
site_name: CodeGraphContext
theme:
name: material
nav:
- Home: index.md
- Installation: installation.md
- Use Cases: use_cases.md
- Architecture: architecture.md
- CLI Reference: cli.md
- Server: server.md
- Core Concepts: core.md
- Tools: tools.md
- Cookbook: cookbook.md
- Contributing:
- Overview: contributing.md
- Adding New Languages: contributing_languages.md
- Troubleshooting: troubleshooting.md
- Future Work: future_work.md
- License: license.md
```
--------------------------------------------------------------------------------
/tests/sample_project/advanced_classes.py:
--------------------------------------------------------------------------------
```python
from abc import ABC, abstractmethod
class A:
def foo(self): return 'A'
class B:
def foo(self): return 'B'
class C(A, B):
def bar(self): return 'C'
class AbstractThing(ABC):
@abstractmethod
def do(self): pass
class ConcreteThing(AbstractThing):
def do(self): return 'done'
class Meta(type):
def __new__(mcls, name, bases, dct):
dct['created_by_meta'] = True
return super().__new__(mcls, name, bases, dct)
class WithMeta(metaclass=Meta):
pass
```
--------------------------------------------------------------------------------
/tests/sample_project_java/src/com/example/app/util/IOHelper.java:
--------------------------------------------------------------------------------
```java
package com.example.app.util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public final class IOHelper {
private IOHelper() {}
public static String readFirstLine(String path) {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line = br.readLine();
return line == null ? "" : line;
} catch (IOException e) {
throw new RuntimeException("unable to read: " + path, e);
}
}
}
```
--------------------------------------------------------------------------------
/website/components.json:
--------------------------------------------------------------------------------
```json
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "src/index.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {
"@magicui": "https://magicui.design/r/{name}.json"
}
}
```
--------------------------------------------------------------------------------
/docs/docs/future_work.md:
--------------------------------------------------------------------------------
```markdown
# Ongoing Concerns and Future Work
This page outlines some of the current limitations of CodeGraphContext and areas for future development.
## Semantic Search
The tool is smart enough to find and analyze a function through millions of code files, but the tool is not yet smart enough to understand that a user searching for “calculate_sum” is also intending to look at the “calculate_addition” function. This level of semantic similarity needs to be researched, developed, tested and eventually implemented by our tool.
```
--------------------------------------------------------------------------------
/website/tsconfig.node.json:
--------------------------------------------------------------------------------
```json
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2015"],
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
```
--------------------------------------------------------------------------------
/website/vite.config.ts:
--------------------------------------------------------------------------------
```typescript
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => ({
server: {
host: "::",
port: 8080,
proxy: {
"/api/pypi": {
target: "https://pypistats.org",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api\/pypi/, "/api"),
},
},
},
plugins: [react()].filter(Boolean),
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
}));
```
--------------------------------------------------------------------------------
/.github/workflows/e2e-tests.yml:
--------------------------------------------------------------------------------
```yaml
name: End-to-end Tests
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -e .
pip install pytest
- name: Run end-to-end tests
run: |
pytest -s tests/test_end_to_end.py
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/enum_struct_union.cpp:
--------------------------------------------------------------------------------
```cpp
enum Color {
RED = 0,
GREEN = 1,
BLUE = 2
};
enum class Direction {
NORTH = 0,
EAST = 1,
SOUTH = 2,
WEST = 3
};
struct MyStruct {
int x = 5;
float y = 3.14f;
void doSomething();
};
void MyStruct::doSomething() {
x += 1;
y *= 2.0f;
}
union MyUnion {
int intValue;
float floatValue;
};
int main() {
// enum
Color color = RED;
Direction dir = Direction::NORTH;
// struct
MyStruct s;
s.doSomething();
// union
MyUnion u;
u.intValue = 42;
return 0;
}
```
--------------------------------------------------------------------------------
/website/src/hooks/use-mobile.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
return !!isMobile;
}
```
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
```yaml
name: Build Test
on:
push:
branches:
- main
pull_request:
schedule:
- cron: "30 18 * * *"
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install build
pip install .[dev]
- name: Build package
run: python -m build
```
--------------------------------------------------------------------------------
/website/src/App.css:
--------------------------------------------------------------------------------
```css
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
```
--------------------------------------------------------------------------------
/tests/sample_project_php/database.php:
--------------------------------------------------------------------------------
```php
<?php
$dsn = "mysql:host=localhost;dbname=testdb";
$user = "root";
$pass = "";
try {
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE TABLE IF NOT EXISTS users(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))");
$stmt = $pdo->prepare("INSERT INTO users(name) VALUES(:name)");
$stmt->execute(['name' => 'Shashank']);
$result = $pdo->query("SELECT * FROM users");
foreach($result as $row) {
echo $row['name'] . "\n";
}
} catch(PDOException $e) {
echo "DB Error: " . $e->getMessage() . "\n";
}
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/class_features.cpp:
--------------------------------------------------------------------------------
```cpp
#include <string>
// Tests for access specifiers
class AccessSpecifierTests {
public:
AccessSpecifierTests() : publicData(10), protectedValue(20), privateData("default") {}
void publicMethod() {/* ... */}
protected:
int protectedValue;
void protectedMethod() {/* ... */}
private:
std::string privateData;
void privateMethod() {/* ... */}
public:
int publicData;
};
// Tests for constructors and destructors
class ConstructorDestructorTests {
public:
ConstructorDestructorTests() : exampleData(100) {}
~ConstructorDestructorTests() {/* ... */}
void exampleMethod() {/* ... */}
private:
int exampleData;
};
```
--------------------------------------------------------------------------------
/website/tsconfig.app.json:
--------------------------------------------------------------------------------
```json
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noImplicitAny": false,
"noFallthroughCasesInSwitch": false,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src", "api"]
}
```
--------------------------------------------------------------------------------
/website/src/components/ui/label.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const labelVariants = cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70");
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label };
```
--------------------------------------------------------------------------------
/website/src/components/ui/separator.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as SeparatorPrimitive from "@radix-ui/react-separator";
import { cn } from "@/lib/utils";
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(({ className, orientation = "horizontal", decorative = true, ...props }, ref) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn("shrink-0 bg-border", orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]", className)}
{...props}
/>
));
Separator.displayName = SeparatorPrimitive.Root.displayName;
export { Separator };
```
--------------------------------------------------------------------------------
/website/src/pages/NotFound.tsx:
--------------------------------------------------------------------------------
```typescript
import { useLocation } from "react-router-dom";
import { useEffect } from "react";
const NotFound = () => {
const location = useLocation();
useEffect(() => {
console.error("404 Error: User attempted to access non-existent route:", location.pathname);
}, [location.pathname]);
return (
<div className="flex min-h-screen items-center justify-center bg-gray-100">
<div className="text-center">
<h1 className="mb-4 text-4xl font-bold">404</h1>
<p className="mb-4 text-xl text-gray-600">Oops! Page not found</p>
<a href="/" className="text-blue-500 underline hover:text-blue-700">
Return to Home
</a>
</div>
</div>
);
};
export default NotFound;
```
--------------------------------------------------------------------------------
/website/src/components/ui/toaster.tsx:
--------------------------------------------------------------------------------
```typescript
import { useToast } from "@/hooks/use-toast";
import { Toast, ToastClose, ToastDescription, ToastProvider, ToastTitle, ToastViewport } from "@/components/ui/toast";
export function Toaster() {
const { toasts } = useToast();
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && <ToastDescription>{description}</ToastDescription>}
</div>
{action}
<ToastClose />
</Toast>
);
})}
<ToastViewport />
</ToastProvider>
);
}
```
--------------------------------------------------------------------------------
/tests/sample_project_php/generators_iterators.php:
--------------------------------------------------------------------------------
```php
<?php
function numbers(int $n): Generator {
for($i = 0; $i < $n; $i++) {
yield $i;
}
}
foreach(numbers(5) as $num) {
echo $num . "\n";
}
class MyIterator implements Iterator {
private array $items = ["apple", "banana", "cherry"];
private int $pos = 0;
public function current(): mixed {
return $this->items[$this->pos];
}
public function key(): int {
return $this->pos;
}
public function next(): void {
$this->pos++;
}
public function rewind(): void {
$this->pos = 0;
}
public function valid(): bool {
return isset($this->items[$this->pos]);
}
}
$it = new MyIterator();
foreach($it as $v) {
echo $v . "\n";
}
```
--------------------------------------------------------------------------------
/website/src/components/ui/textarea.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { cn } from "@/lib/utils";
export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
ref={ref}
{...props}
/>
);
});
Textarea.displayName = "Textarea";
export { Textarea };
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.vi.min.js:
--------------------------------------------------------------------------------
```javascript
!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");e.vi=function(){this.pipeline.reset(),this.pipeline.add(e.vi.stopWordFilter,e.vi.trimmer)},e.vi.wordCharacters="[A-Za-ẓ̀͐́͑̉̃̓ÂâÊêÔôĂ-ăĐ-đƠ-ơƯ-ư]",e.vi.trimmer=e.trimmerSupport.generateTrimmer(e.vi.wordCharacters),e.Pipeline.registerFunction(e.vi.trimmer,"trimmer-vi"),e.vi.stopWordFilter=e.generateStopWordFilter("là cái nhưng mà".split(" "))}});
```
--------------------------------------------------------------------------------
/tests/sample_project_c/src/main.c:
--------------------------------------------------------------------------------
```cpp
#include <stdio.h>
#include "config.h"
#include "platform.h"
#include "util.h"
#include "math/vec.h"
#include "module.h"
static int cmp_desc(int a, int b) { return b - a; } // matches cmp_fn typedef shape
int main(void) {
module_init(MODE_A);
Point p = { .x = 3, .y = 4 };
Vec3 v = {1,2,3}, w = {4,5,6};
Vec3 sum = vec_add(v, w);
int m = max_int(p.x, p.y);
int r = module_compute(m);
#ifdef CGC_PLATFORM_WINDOWS
printf("%s %s (win) r=%d sum=(%.0f,%.0f,%.0f)\n", APP_NAME, APP_VERSION, r, sum.x, sum.y, sum.z);
#else
printf("%s %s (posix) r=%d sum=(%.0f,%.0f,%.0f)\n", APP_NAME, APP_VERSION, r, sum.x, sum.y, sum.z);
#endif
// use function pointer typedef
cmp_fn f = cmp_desc;
return f(r, g_counter) < 0 ? 0 : 1;
}
```
--------------------------------------------------------------------------------
/website/eslint.config.js:
--------------------------------------------------------------------------------
```javascript
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
export default tseslint.config(
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
"@typescript-eslint/no-unused-vars": "off",
},
},
);
```
--------------------------------------------------------------------------------
/website/src/components/ui/progress.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as ProgressPrimitive from "@radix-ui/react-progress";
import { cn } from "@/lib/utils";
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn("relative h-4 w-full overflow-hidden rounded-full bg-secondary", className)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
));
Progress.displayName = ProgressPrimitive.Root.displayName;
export { Progress };
```
--------------------------------------------------------------------------------
/website/src/components/ui/input.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { cn } from "@/lib/utils";
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className,
)}
ref={ref}
{...props}
/>
);
},
);
Input.displayName = "Input";
export { Input };
```
--------------------------------------------------------------------------------
/tests/sample_project/advanced_classes2.py:
--------------------------------------------------------------------------------
```python
from dataclasses import dataclass
from enum import Enum
class Base: pass
class Mid(Base): pass
class Final(Mid): pass
class Mixin1:
def m1(self): return 'm1'
class Mixin2:
def m2(self): return 'm2'
class Combined(Mixin1, Mixin2, Base):
def both(self): return self.m1() + self.m2()
c = Combined()
res = c.both()
@dataclass
class Point:
x: int
y: int
def magnitude(self): return (self.x ** 2 + self.y ** 2) ** 0.5
p = Point(3,4)
dist = p.magnitude()
class Color(Enum):
RED = 1
BLUE = 2
def is_primary(self): return self in {Color.RED, Color.BLUE}
flag = Color.RED.is_primary()
def handle(val):
match val:
case Point(x, y):
return f'Point with magnitude {val.magnitude()}'
case _:
return 'Unknown'
msg = handle(p)
```
--------------------------------------------------------------------------------
/tests/sample_project/control_flow.py:
--------------------------------------------------------------------------------
```python
import os
def choose_path(x):
if x > 0: return 'positive'
elif x == 0: return 'zero'
else: return 'negative'
def ternary(x):
return 'pos' if x > 0 else 'non-pos'
def try_except_finally(x):
try:
if x == 0:
raise ValueError('zero')
return 10 / x
except ValueError as e:
return str(e)
except Exception:
return None
finally:
_ = 'cleaned'
def conditional_inner_import(use_numpy=False):
if use_numpy:
import numpy as np
return np.array([1, 2, 3])
else:
return [1, 2, 3]
def env_based_import():
if os.getenv('USE_UJSON') == '1':
try:
import ujson as json
except Exception:
import json
else:
import json
return json.dumps({'a': 1})
```
--------------------------------------------------------------------------------
/tests/sample_project/dynamic_dispatch.py:
--------------------------------------------------------------------------------
```python
from functools import partial
import operator
import importlib
def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
DISPATCH = {'add': add, 'sub': sub, 'mul': mul}
def dispatch_by_key(name, a, b):
return DISPATCH[name](a, b)
def dispatch_by_string(name, *args, **kwargs):
fn = globals().get(name)
if callable(fn):
return fn(*args, **kwargs)
raise KeyError(name)
def partial_example():
add5 = partial(add, 5)
return add5(10)
class C:
def method(self, x): return x + 3
def methodcaller_example(x):
c = C()
mc = operator.methodcaller('method', x)
return mc(c)
def dynamic_import_call(mod_name, fn_name, *args, **kwargs):
mod = importlib.import_module(mod_name)
fn = getattr(mod, fn_name)
return fn(*args, **kwargs)
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.multi.min.js:
--------------------------------------------------------------------------------
```javascript
!function(e,t){"function"==typeof define&&define.amd?define(t):"object"==typeof exports?module.exports=t():t()(e.lunr)}(this,function(){return function(e){e.multiLanguage=function(){for(var t=Array.prototype.slice.call(arguments),i=t.join("-"),r="",n=[],s=[],p=0;p<t.length;++p)"en"==t[p]?(r+="\\w",n.unshift(e.stopWordFilter),n.push(e.stemmer),s.push(e.stemmer)):(r+=e[t[p]].wordCharacters,e[t[p]].stopWordFilter&&n.unshift(e[t[p]].stopWordFilter),e[t[p]].stemmer&&(n.push(e[t[p]].stemmer),s.push(e[t[p]].stemmer)));var o=e.trimmerSupport.generateTrimmer(r);return e.Pipeline.registerFunction(o,"lunr-multi-trimmer-"+i),n.unshift(o),function(){this.pipeline.reset(),this.pipeline.add.apply(this.pipeline,n),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add.apply(this.searchPipeline,s))}}}});
```
--------------------------------------------------------------------------------
/website/src/components/ui/sonner.tsx:
--------------------------------------------------------------------------------
```typescript
import { useTheme } from "next-themes";
import { Toaster as Sonner, toast } from "sonner";
type ToasterProps = React.ComponentProps<typeof Sonner>;
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton: "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
);
};
export { Toaster, toast };
```
--------------------------------------------------------------------------------
/tests/sample_project_misc/tables.css:
--------------------------------------------------------------------------------
```css
body {
font-family: Arial, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
}
h1 {
color: #2c3e50;
text-align: center;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
background: white;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}
caption {
font-size: 1.2em;
font-weight: bold;
margin-bottom: 10px;
color: #34495e;
}
th, td {
padding: 12px;
text-align: left;
border: 1px solid #ddd;
}
th {
background-color: #3498db;
color: white;
font-weight: bold;
}
thead th {
background-color: #2980b9;
}
tfoot th, tfoot td {
background-color: #f8f9fa;
font-weight: bold;
}
tbody tr:nth-child(even) {
background-color: #f2f2f2;
}
tbody tr:hover {
background-color: #e9f5ff;
}
@media screen and (max-width: 600px) {
table {
display: block;
overflow-x: auto;
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_typescript/tsconfig.json:
--------------------------------------------------------------------------------
```json
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM"],
"module": "commonjs",
"moduleResolution": "node",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strictPropertyInitialization": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"allowUnusedLabels": false,
"allowUnreachableCode": false,
"noPropertyAccessFromIndexSignature": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist",
"**/*.test.ts",
"**/*.spec.ts"
]
}
```
--------------------------------------------------------------------------------
/src/codegraphcontext/utils/debug_log.py:
--------------------------------------------------------------------------------
```python
import os
from datetime import datetime
import logging
logger = logging.getLogger(__name__)
# Toggle this to True to enable debug logging
debug_mode = False # Set to True for dev/test, False for production
log_mode = False # Set to True to enable user login logging
def debug_log(message):
"""Write debug message to a file if debug_mode is enabled"""
if not debug_mode:
return
debug_file = os.path.expanduser("~/mcp_debug.log")
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(debug_file, "a") as f:
f.write(f"[{timestamp}] {message}\n")
f.flush()
def info_logger(msg):
if log_mode:
return logger.info(msg)
else:
return
def error_logger(msg):
if log_mode:
return logger.error(msg)
else:
return
def warning_logger(msg):
if log_mode:
return logger.warning(msg)
else:
return
def debug_logger(msg):
return logger.debug(msg)
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.th.min.js:
--------------------------------------------------------------------------------
```javascript
!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r():r()(e.lunr)}(this,function(){return function(e){if(void 0===e)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===e.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");var r="2"==e.version[0];e.th=function(){this.pipeline.reset(),this.pipeline.add(e.th.trimmer),r?this.tokenizer=e.th.tokenizer:(e.tokenizer&&(e.tokenizer=e.th.tokenizer),this.tokenizerFn&&(this.tokenizerFn=e.th.tokenizer))},e.th.wordCharacters="[-]",e.th.trimmer=e.trimmerSupport.generateTrimmer(e.th.wordCharacters),e.Pipeline.registerFunction(e.th.trimmer,"trimmer-th");var t=e.wordcut;t.init(),e.th.tokenizer=function(i){if(!arguments.length||null==i||void 0==i)return[];if(Array.isArray(i))return i.map(function(t){return r?new e.Token(t):t});var n=i.toString().replace(/^\s+/,"");return t.cut(n).split("|")}}});
```
--------------------------------------------------------------------------------
/tests/sample_project_typescript/package.json:
--------------------------------------------------------------------------------
```json
{
"name": "sample_project_typescript",
"version": "1.0.0",
"description": "Comprehensive TypeScript sample project for testing code analysis and indexing tools",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"build:watch": "tsc --watch",
"start": "node dist/index.js",
"dev": "ts-node src/index.ts",
"test": "jest",
"test:watch": "jest --watch",
"lint": "eslint src/**/*.ts",
"lint:fix": "eslint src/**/*.ts --fix",
"clean": "rimraf dist"
},
"keywords": [
"typescript",
"sample",
"code-analysis",
"indexing",
"testing"
],
"author": "Sample Project",
"license": "MIT",
"devDependencies": {
"@types/node": "^20.0.0",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"eslint": "^8.0.0",
"jest": "^29.0.0",
"@types/jest": "^29.0.0",
"ts-jest": "^29.0.0",
"ts-node": "^10.0.0",
"typescript": "^5.0.0",
"rimraf": "^5.0.0"
},
"dependencies": {
"reflect-metadata": "^0.1.13"
}
}
```
--------------------------------------------------------------------------------
/website/src/components/ui/checkbox.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };
```
--------------------------------------------------------------------------------
/.github/workflows/update-contributors.yml:
--------------------------------------------------------------------------------
```yaml
name: Update Contributors
on:
schedule:
- cron: '0 */6 * * *' # Runs every 6 hours
workflow_dispatch: # Allows manual triggering
jobs:
update-contributors:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'
- name: Run script to generate contributors file
run: python scripts/generate_lang_contributors.py
- name: Commit and push if there are changes
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email 'github-actions[bot]@users.noreply.github.com'
git add contributors.md
if ! git diff --staged --quiet; then
git commit -m "docs: update contributors"
git push
else
echo "No changes to contributors.md"
fi
```
--------------------------------------------------------------------------------
/website/src/components/ui/slider.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as SliderPrimitive from "@radix-ui/react-slider";
import { cn } from "@/lib/utils";
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn("relative flex w-full touch-none select-none items-center", className)}
{...props}
>
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
));
Slider.displayName = SliderPrimitive.Root.displayName;
export { Slider };
```
--------------------------------------------------------------------------------
/website/src/components/ui/badge.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
}
export { Badge, badgeVariants };
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/function_types.cpp:
--------------------------------------------------------------------------------
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
// Regular function
int add(int a, int b) {
return a + b;
}
// Templated function
template <typename T>
T multiply(T a, T b) {
return a * b;
}
class Calculator {
public:
// Static member function
static int subtract(int a, int b) {
return a - b;
}
// Method using a local lambda
void printSum(const std::vector<int>& nums) {
auto printer = [](int val) { std::cout << val << std::endl; };
for (int n : nums) printer(n);
}
};
int main() {
Calculator calc;
std::vector<int> numbers = {1, 2, 3};
calc.printSum(numbers);
// Standalone lambda
auto lambda = [](int a, int b) { return a + b; };
std::cout << "Lambda sum: " << lambda(3,4) << std::endl;
// Regular function call
std::cout << "Add: " << add(2,3) << std::endl;
// Templated function call
std::cout << "Multiply: " << multiply(2,3) << std::endl;
// Static member function call
std::cout << "Subtract: " << Calculator::subtract(5,2) << std::endl;
return 0;
}
```
--------------------------------------------------------------------------------
/tests/sample_project_ruby/tests/test_mixins.py:
--------------------------------------------------------------------------------
```python
def test_ruby_class_includes_module(graph):
# Check that the module node exists
rows = graph.query('MATCH (:Module {name:"Flyable"}) RETURN 1 AS ok LIMIT 1')
assert rows, "Expected a Module node named 'Flyable' but none was found."
# Check that the class node exists
rows = graph.query('MATCH (:Class {name:"Bird"}) RETURN 1 AS ok LIMIT 1')
assert rows, "Expected a Class node named 'Bird' but none was found."
# Check that the INCLUDES relationship exists between Bird and Flyable
rows = graph.query('''
MATCH (:Class {name:"Bird"})-[:INCLUDES]->(:Module {name:"Flyable"})
RETURN count(*) AS c
''')
assert rows and rows[0]["c"] > 0, \
"Expected an INCLUDES relationship from Class 'Bird' to Module 'Flyable', but none was found."
def test_module_is_unique(graph):
# Ensure only one Module node named 'Flyable' exists
rows = graph.query('MATCH (m:Module {name:"Flyable"}) RETURN count(m) AS c')
assert rows and rows[0]["c"] == 1, \
f"Expected exactly one Module node named 'Flyable', but found {rows[0]['c'] if rows else 0}."
```
--------------------------------------------------------------------------------
/tests/sample_project_java/src/com/example/app/Main.java:
--------------------------------------------------------------------------------
```java
package com.example.app;
import com.example.app.model.Role;
import com.example.app.model.User;
import com.example.app.service.GreetingService;
import com.example.app.service.impl.GreetingServiceImpl;
import com.example.app.util.CollectionUtils;
import com.example.app.util.IOHelper;
import java.util.List;
public class Main {
public static void main(String[] args) {
GreetingService svc = new GreetingServiceImpl();
User u = new User("Priya", Role.ADMIN);
System.out.println(svc.greet(u));
int sumSquares = CollectionUtils.sumOfSquares(List.of(1, 2, 3, 4, 5));
System.out.println("sumSquares=" + sumSquares);
try {
String first = IOHelper.readFirstLine("README.md");
System.out.println("firstLine=" + first);
} catch (RuntimeException e) {
System.out.println("IO failed: " + e.getMessage());
}
com.example.app.misc.Outer outer = new com.example.app.misc.Outer("outer");
com.example.app.misc.Outer.Inner inner = outer.new Inner("inner");
System.out.println(inner.combine());
}
}
```
--------------------------------------------------------------------------------
/website/src/components/ShowDownloads.tsx:
--------------------------------------------------------------------------------
```typescript
import { useEffect, useState } from "react";
type PypiStats = {
data: {
last_day: number;
last_month: number;
last_week: number;
};
package: string;
type: string;
};
export default function ShowDownloads() {
const [stats, setStats] = useState<PypiStats | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function fetchStats() {
try {
const res = await fetch("/api/pypi/packages/codegraphcontext/recent");
if (!res.ok) {
throw new Error(`API error: ${res.status}`);
}
const data = await res.json();
setStats(data);
} catch (err: unknown) {
setError((err as Error).message);
}
}
fetchStats();
}, []);
if (error) return <p className="text-red-500">Error: {error}</p>;
if (!stats) return <p>Loading stats...</p>;
return (
<div data-aos="fade-in">
{stats?.data ? (
<>
<p>Last month downloads: {stats.data.last_month.toLocaleString()}+</p>
</>
) : (
<p>No data available yet for this package</p>
)}
</div>
);
}
```
--------------------------------------------------------------------------------
/website/index.html:
--------------------------------------------------------------------------------
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CodeGraphContext - AI-Powered Code Knowledge Graphs</title>
<meta name="description" content="Transform your codebase into an intelligent knowledge graph for AI assistants. Index Python code, analyze relationships, and provide context with CodeGraphContext MCP server." />
<meta name="author" content="Shashank Shekhar Singh" />
<meta name="keywords" content="code analysis, knowledge graph, AI assistant, MCP server, Python, Neo4j, code indexing" />
<meta property="og:title" content="CodeGraphContext - AI-Powered Code Knowledge Graphs" />
<meta property="og:description" content="Transform your codebase into an intelligent knowledge graph for AI assistants. Index Python code, analyze relationships, and provide context." />
<meta property="og:type" content="website" />
<meta name="twitter:card" content="summary_large_image" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
```
--------------------------------------------------------------------------------
/website/src/components/ui/switch.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as SwitchPrimitives from "@radix-ui/react-switch";
import { cn } from "@/lib/utils";
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0",
)}
/>
</SwitchPrimitives.Root>
));
Switch.displayName = SwitchPrimitives.Root.displayName;
export { Switch };
```
--------------------------------------------------------------------------------
/website/src/components/ui/tooltip.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "@/lib/utils";
const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
));
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
```
--------------------------------------------------------------------------------
/website/src/components/ThemeToggle.tsx:
--------------------------------------------------------------------------------
```typescript
"use client"
import * as React from "react"
import { Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"
import { Button } from "@/components/ui/button"
import { motion, AnimatePresence } from "framer-motion"
export function ThemeToggle() {
const { setTheme, theme } = useTheme()
const toggleTheme = () => {
setTheme(theme === 'dark' ? 'light' : 'dark')
}
return (
<Button variant="outline" size="icon" onClick={toggleTheme} className="relative overflow-hidden">
<AnimatePresence initial={false} mode="wait">
<motion.div
key={theme === 'dark' ? 'sun' : 'moon'}
initial={{ y: 20, opacity: 0, rotate: -90 }}
animate={{ y: 0, opacity: 1, rotate: 0 }}
exit={{ y: -20, opacity: 0, rotate: 90 }}
transition={{ duration: 0.3 }}
className="absolute"
>
{theme === 'dark' ? (
<Sun className="h-[1.2rem] w-[1.2rem]" />
) : (
<Moon className="h-[1.2rem] w-[1.2rem]" />
)}
</motion.div>
</AnimatePresence>
<span className="sr-only">Toggle theme</span>
</Button>
)
}
```
--------------------------------------------------------------------------------
/website/src/components/ui/hover-card.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as HoverCardPrimitive from "@radix-ui/react-hover-card";
import { cn } from "@/lib/utils";
const HoverCard = HoverCardPrimitive.Root;
const HoverCardTrigger = HoverCardPrimitive.Trigger;
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<HoverCardPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
));
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName;
export { HoverCard, HoverCardTrigger, HoverCardContent };
```
--------------------------------------------------------------------------------
/tests/sample_project_rust/src/lib.rs:
--------------------------------------------------------------------------------
```rust
// lib.rs - Main library file for Rust sample project
pub mod basic_functions;
pub mod structs_enums;
pub mod traits;
pub mod error_handling;
pub mod lifetimes_references;
pub mod generics;
pub mod concurrency;
pub mod iterators_closures;
pub mod smart_pointers;
pub mod modules;
// Re-exports for convenience
pub use basic_functions::*;
pub use structs_enums::{Person, Status};
pub use traits::{Describable, Area};
/// Library-level documentation
///
/// This is a comprehensive Rust sample project demonstrating:
/// - Basic and advanced function patterns
/// - Structs, enums, and their implementations
/// - Traits and trait implementations
/// - Error handling with Result and custom errors
/// - Lifetimes and references
/// - Generics and type parameters
/// - Concurrency with threads and channels
/// - Iterators and closures
/// - Smart pointers (Box, Rc, Arc, RefCell)
/// - Module organization
#[cfg(test)]
mod integration_tests {
use super::*;
#[test]
fn test_basic_workflow() {
let result = simple_function(5);
assert_eq!(result, 10);
let person = Person::new("Alice".to_string(), 30);
assert_eq!(person.name, "Alice");
}
}
```
--------------------------------------------------------------------------------
/website/src/components/ui/popover.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/utils";
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent };
```
--------------------------------------------------------------------------------
/website/src/pages/Index.tsx:
--------------------------------------------------------------------------------
```typescript
import HeroSection from "../components/HeroSection";
import FeaturesSection from "../components/FeaturesSection";
import InstallationSection from "../components/InstallationSection";
import DemoSection from "../components/DemoSection";
import ExamplesSection from "../components/ExamplesSection";
import CookbookSection from "../components/CookbookSection";
import Footer from "../components/Footer";
import TestimonialSection from "../components/TestimonialSection";
import ComparisonTable from "../components/ComparisonTable";
const Index = () => {
return (
<main className="min-h-screen overflow-x-hidden">
<div data-aos="fade-in">
<HeroSection />
</div>
<div data-aos="fade-up">
<DemoSection />
</div>
<div data-aos="fade-up">
<ComparisonTable />
</div>
<div data-aos="fade-up">
<FeaturesSection />
</div>
<div data-aos="fade-up">
<InstallationSection />
</div>
<div data-aos="fade-up">
<ExamplesSection />
</div>
<div data-aos="fade-up">
<TestimonialSection />
</div>
<div data-aos="fade-up">
<CookbookSection />
</div>
<div data-aos="fade-up" data-aos-anchor-placement="top-bottom">
<Footer />
</div>
</main>
);
};
export default Index;
```
--------------------------------------------------------------------------------
/website/src/components/ui/avatar.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { cn } from "@/lib/utils";
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className)}
{...props}
/>
));
Avatar.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image ref={ref} className={cn("aspect-square h-full w-full", className)} {...props} />
));
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn("flex h-full w-full items-center justify-center rounded-full bg-muted", className)}
{...props}
/>
));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { Avatar, AvatarImage, AvatarFallback };
```
--------------------------------------------------------------------------------
/.github/workflows/post_discord_invite.yml:
--------------------------------------------------------------------------------
```yaml
name: Post Discord Invite on Issue or PR
permissions:
issues: write
pull-requests: write
on:
issues:
types: [opened]
pull_request:
types: [opened]
jobs:
post_discord_invite:
# Skip if the event is a PR from a fork; still run for issues and in-repo PRs
if: ${{ github.event_name == 'issues' || (github.event_name == 'pull_request' && !github.event.pull_request.head.repo.fork) }}
runs-on: ubuntu-latest
steps:
- name: Post Discord Invite Comment
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const discord_link = "https://discord.gg/dR4QY32uYQ";
let number;
if (context.payload.issue) {
number = context.payload.issue.number;
} else if (context.payload.pull_request) {
number = context.payload.pull_request.number;
} else {
console.log("No issue or PR found. Exiting.");
return;
}
console.log("Detected issue/PR number:", number);
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: number,
body: `Hi! 👋 Join our CodeGraphContext Discord channel to collaborate: ${discord_link}`
});
```
--------------------------------------------------------------------------------
/website/src/components/ui/toggle.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as TogglePrimitive from "@radix-ui/react-toggle";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const toggleVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
{
variants: {
variant: {
default: "bg-transparent",
outline: "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-10 px-3",
sm: "h-9 px-2.5",
lg: "h-11 px-5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
const Toggle = React.forwardRef<
React.ElementRef<typeof TogglePrimitive.Root>,
React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants>
>(({ className, variant, size, ...props }, ref) => (
<TogglePrimitive.Root ref={ref} className={cn(toggleVariants({ variant, size, className }))} {...props} />
));
Toggle.displayName = TogglePrimitive.Root.displayName;
export { Toggle, toggleVariants };
```
--------------------------------------------------------------------------------
/website/src/components/ui/radio-group.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
import { Circle } from "lucide-react";
import { cn } from "@/lib/utils";
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return <RadioGroupPrimitive.Root className={cn("grid gap-2", className)} {...props} ref={ref} />;
});
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName;
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
"aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
);
});
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName;
export { RadioGroup, RadioGroupItem };
```
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
```toml
[project]
name = "codegraphcontext"
version = "0.1.17"
description = "An MCP server that indexes local code into a graph database to provide context to AI assistants."
authors = [{ name = "Shashank Shekhar Singh", email = "[email protected]" }]
readme = "README.md"
license = { file = "LICENSE" }
requires-python = ">=3.9"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries :: Application Frameworks",
]
dependencies = [
"neo4j>=5.15.0",
"watchdog>=3.0.0",
"requests>=2.31.0",
"stdlibs>=2023.11.18",
"typer[all]>=0.9.0",
"rich>=13.7.0",
"inquirerpy>=0.3.4",
"python-dotenv>=1.0.0",
"tree-sitter==0.20.4",
"tree-sitter-languages==1.10.2",
"pyyaml",
"pytest",
"nbformat",
"nbconvert>=7.16.6",
"pathspec>=0.12.1"
]
[project.urls]
"Homepage" = "https://github.com/Shashankss1205/CodeGraphContext"
"Bug Tracker" = "https://github.com/Shashankss1205/CodeGraphContext/issues"
[project.scripts]
cgc = "codegraphcontext.cli.main:app"
codegraphcontext = "codegraphcontext.cli.main:app"
[project.optional-dependencies]
dev = [
"pytest>=7.4.0",
"black>=23.11.0",
"pytest-asyncio>=0.21.0",
]
[tool.setuptools]
package-dir = { "" = "src" }
[tool.setuptools.packages.find]
where = ["src"]
include = ["codegraphcontext*"]
```
--------------------------------------------------------------------------------
/website/src/components/ui/alert.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
},
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div ref={ref} role="alert" className={cn(alertVariants({ variant }), className)} {...props} />
));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h5 ref={ref} className={cn("mb-1 font-medium leading-none tracking-tight", className)} {...props} />
),
);
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("text-sm [&_p]:leading-relaxed", className)} {...props} />
),
);
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription };
```
--------------------------------------------------------------------------------
/website/src/components/ui/scroll-area.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import { cn } from "@/lib/utils";
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root ref={ref} className={cn("relative overflow-hidden", className)} {...props}>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">{children}</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
));
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" && "h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" && "h-2.5 flex-col border-t border-t-transparent p-[1px]",
className,
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
));
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
export { ScrollArea, ScrollBar };
```
--------------------------------------------------------------------------------
/website/src/App.tsx:
--------------------------------------------------------------------------------
```typescript
import { useEffect } from "react";
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { ThemeProvider } from "@/components/ThemeProvider";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Index from "./pages/Index";
import NotFound from "./pages/NotFound";
import MoveToTop from "./components/MoveToTop";
// ✅ Import AOS library and CSS
import AOS from "aos";
import "aos/dist/aos.css";
const queryClient = new QueryClient();
const App: React.FC = () => {
// ✅ Initialize AOS once on mount
useEffect(() => {
AOS.init({
duration: 800, // Animation duration (ms)
easing: "ease-in-out", // Smooth transition
once: true, // Run animation only once
mirror: false, // Do not animate when scrolling back up
});
}, []);
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider
attribute="class"
defaultTheme="dark"
enableSystem
disableTransitionOnChange
>
<TooltipProvider>
<Toaster />
<Sonner />
<BrowserRouter>
<Routes>
<Route path="/" element={<Index />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
{/* Move to Top button */}
<MoveToTop />
</TooltipProvider>
</ThemeProvider>
</QueryClientProvider>
);
};
export default App;
```
--------------------------------------------------------------------------------
/website/src/components/ui/resizable.tsx:
--------------------------------------------------------------------------------
```typescript
import { GripVertical } from "lucide-react";
import * as ResizablePrimitive from "react-resizable-panels";
import { cn } from "@/lib/utils";
const ResizablePanelGroup = ({ className, ...props }: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (
<ResizablePrimitive.PanelGroup
className={cn("flex h-full w-full data-[panel-group-direction=vertical]:flex-col", className)}
{...props}
/>
);
const ResizablePanel = ResizablePrimitive.Panel;
const ResizableHandle = ({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean;
}) => (
<ResizablePrimitive.PanelResizeHandle
className={cn(
"relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 [&[data-panel-group-direction=vertical]>div]:rotate-90",
className,
)}
{...props}
>
{withHandle && (
<div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
<GripVertical className="h-2.5 w-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
);
export { ResizablePanelGroup, ResizablePanel, ResizableHandle };
```
--------------------------------------------------------------------------------
/website/src/components/ui/toggle-group.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group";
import { type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { toggleVariants } from "@/components/ui/toggle";
const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
size: "default",
variant: "default",
});
const ToggleGroup = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> & VariantProps<typeof toggleVariants>
>(({ className, variant, size, children, ...props }, ref) => (
<ToggleGroupPrimitive.Root ref={ref} className={cn("flex items-center justify-center gap-1", className)} {...props}>
<ToggleGroupContext.Provider value={{ variant, size }}>{children}</ToggleGroupContext.Provider>
</ToggleGroupPrimitive.Root>
));
ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName;
const ToggleGroupItem = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> & VariantProps<typeof toggleVariants>
>(({ className, children, variant, size, ...props }, ref) => {
const context = React.useContext(ToggleGroupContext);
return (
<ToggleGroupPrimitive.Item
ref={ref}
className={cn(
toggleVariants({
variant: context.variant || variant,
size: context.size || size,
}),
className,
)}
{...props}
>
{children}
</ToggleGroupPrimitive.Item>
);
});
ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName;
export { ToggleGroup, ToggleGroupItem };
```
--------------------------------------------------------------------------------
/website/src/components/ui/orbiting-circles.tsx:
--------------------------------------------------------------------------------
```typescript
import React from "react"
import { cn } from "@/lib/utils"
export interface OrbitingCirclesProps
extends React.HTMLAttributes<HTMLDivElement> {
className?: string
children?: React.ReactNode
reverse?: boolean
duration?: number
delay?: number
radius?: number
path?: boolean
iconSize?: number
speed?: number
}
export function OrbitingCircles({
className,
children,
reverse,
duration = 20,
radius = 160,
path = true,
iconSize = 30,
speed = 1,
...props
}: OrbitingCirclesProps) {
const calculatedDuration = duration / speed
return (
<>
{path && (
<svg
xmlns="http://www.w3.org/2000/svg"
version="1.1"
className="pointer-events-none absolute inset-0 size-full"
>
<circle
className="stroke-black/10 stroke-1 dark:stroke-white/10"
cx="50%"
cy="50%"
r={radius}
fill="none"
/>
</svg>
)}
{React.Children.map(children, (child, index) => {
const angle = (360 / React.Children.count(children)) * index
return (
<div
style={
{
"--duration": calculatedDuration,
"--radius": radius,
"--angle": angle,
"--icon-size": `${iconSize}px`,
} as React.CSSProperties
}
className={cn(
`animate-orbit absolute flex size-[var(--icon-size)] transform-gpu items-center justify-center rounded-full`,
{ "[animation-direction:reverse]": reverse },
className
)}
{...props}
>
{child}
</div>
)
})}
</>
)
}
```
--------------------------------------------------------------------------------
/tests/sample_project/edge_cases/long_functions.py:
--------------------------------------------------------------------------------
```python
def long_loop_example(n):
result = []
for i in range(n):
if i % 2 == 0:
result.append(i * 2)
else:
result.append(i + 3)
if i % 5 == 0:
result.append(i - 1)
if i % 7 == 0:
result.append(i * i)
if i % 3 == 0:
result.append(i // 2)
if i % 4 == 0:
result.append(i + 10)
if i % 6 == 0:
result.append(i - 5)
if i % 8 == 0:
result.append(i * 3)
if i % 9 == 0:
result.append(i + 7)
if i % 10 == 0:
result.append(i - 2)
return result
def verbose_conditions(x, y):
if x > 0:
a = x + y
else:
a = x - y
if y > 0:
b = y * 2
else:
b = y // 2
if x == y:
c = x * y
else:
c = x + y
if x % 2 == 0:
d = x // 2
else:
d = x * 2
if y % 3 == 0:
e = y // 3
else:
e = y * 3
if x > 10:
f = x - 10
else:
f = x + 10
return a + b + c + d + e + f
def extended_try_except(val):
try:
if val < 0:
raise ValueError("Negative value")
elif val == 0:
raise ZeroDivisionError("Zero value")
elif val > 100:
raise OverflowError("Too large")
result = val * 2
for i in range(5):
result += i
if result % 2 == 0:
result //= 2
else:
result += 1
return result
except ValueError as ve:
return str(ve)
except ZeroDivisionError as zde:
return str(zde)
except OverflowError as oe:
return str(oe)
except Exception as e:
return "Unknown error: " + str(e)
finally:
_ = "done"
```
--------------------------------------------------------------------------------
/website/src/components/ui/card.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)} {...props} />
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
),
);
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h3 ref={ref} className={cn("text-2xl font-semibold leading-none tracking-tight", className)} {...props} />
),
);
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => (
<p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
),
);
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />,
);
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
),
);
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
```
--------------------------------------------------------------------------------
/website/src/components/ui/button.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
},
);
Button.displayName = "Button";
export { Button, buttonVariants };
```
--------------------------------------------------------------------------------
/website/src/components/ui/tabs.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as TabsPrimitive from "@radix-ui/react-tabs";
import { cn } from "@/lib/utils";
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className,
)}
{...props}
/>
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
className,
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className,
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };
```
--------------------------------------------------------------------------------
/tests/sample_project_misc/tables.html:
--------------------------------------------------------------------------------
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hacktoberfest Contributors</title>
<link rel="stylesheet" href="tables.css">
</head>
<body>
<h1>Hacktoberfest 2025 Contributors</h1>
<table>
<caption>Open Source Contributors</caption>
<thead>
<tr>
<th>Contributor</th>
<th>Project</th>
<th>Pull Requests</th>
<th>Contribution Type</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Nureni Jamiu</td>
<td>CodeGraphContext</td>
<td>2</td>
<td>Indexing Pipeline</td>
<td>Completed</td>
</tr>
<tr>
<td>Alex Chen</td>
<td>PyViz</td>
<td>3</td>
<td>Bug Fixes</td>
<td>In Progress</td>
</tr>
<tr>
<td>Maria Garcia</td>
<td>WebTools</td>
<td>5</td>
<td>Feature</td>
<td>Completed</td>
</tr>
<tr>
<td>James Wilson</td>
<td>DataFlow</td>
<td>2</td>
<td>Testing</td>
<td>In Progress</td>
</tr>
<tr>
<td>Aisha Patel</td>
<td>UIKit</td>
<td>4</td>
<td>Enhancement</td>
<td>Completed</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="2">Total Contributions:</th>
<td>18</td>
<td colspan="2">80% Complete</td>
</tr>
</tfoot>
</table>
</body>
</html>
```
--------------------------------------------------------------------------------
/website/src/components/ui/accordion.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
const Accordion = AccordionPrimitive.Root;
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item ref={ref} className={cn("border-b", className)} {...props} />
));
AccordionItem.displayName = "AccordionItem";
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
className={cn(
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
className,
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
));
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
));
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
```
--------------------------------------------------------------------------------
/tests/sample_project_cpp/types_variable_assignments.cpp:
--------------------------------------------------------------------------------
```cpp
#include <iostream>
#include <string>
#include <vector>
// --- Demo class ---
class Demo {
public:
int member; // non-static member
static int static_member; // static member
const char* name = "Demo";
void setMember(int value) { member = value; }
};
int Demo::static_member = 100;
// --- Point struct for structured bindings ---
struct Point {
int x;
int y;
};
// --- Global variable declarations ---
int global_int = 10;
double global_double(3.14);
std::string global_str = "Hello";
const int CONST_VAL = 42;
int *global_ptr = &global_int;
int global_arr[5] = {1, 2, 3, 4, 5};
// --- Function demonstrating variable declarations ---
void testVariables() {
// Basic declarations
int a = 5;
float b = 2.5f;
double c(9.81);
bool flag = true;
char ch = 'A';
std::string s = "Tree-sitter";
// Pointer and reference
int x = 10;
int *p = &x;
int &ref = x;
const int *const_ptr = &x;
// Arrays
int nums[3] = {1, 2, 3};
char letters[] = {'a', 'b', 'c'};
std::string words[2] = {"hello", "world"};
// Vector and auto type
std::vector<int> vec = {1, 2, 3, 4};
auto val = vec[2];
// Structured bindings (C++17)
Point pt = {10, 20};
auto [px, py] = pt;
// Assignments and compound ops
a = 10;
a += 5;
b *= 3.0f;
c /= 2;
flag = !flag;
s += " test";
x = a + b - c;
// Expressions and function calls
std::cout << "Sum: " << (a + b + c) << std::endl;
// Dynamic allocation
int *dyn = new int(99);
delete dyn;
// Static and const local variables
static int counter = 0;
const double PI = 3.14159;
// Lambda with captured variable
auto lambda = [=]() { return PI * a; };
double result = lambda();
// Object and member assignments
Demo d;
d.member = 50;
d.setMember(25);
Demo::static_member = 200;
}
int main() {
testVariables();
return 0;
}
```
--------------------------------------------------------------------------------
/website/src/components/MoveToTop.tsx:
--------------------------------------------------------------------------------
```typescript
import React, { useState, useEffect } from "react";
const MoveToTop: React.FC = () => {
const [showButton, setShowButton] = useState<boolean>(false);
useEffect(() => {
const handleScroll = () => {
if (window.scrollY > window.innerHeight * 0.05) {
setShowButton(true);
} else {
setShowButton(false);
}
};
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
const scrollToTop = () => {
window.scrollTo({ top: 0, behavior: "smooth" });
};
return (
<>
{showButton && (
<button
onClick={scrollToTop}
data-aos="fade-in"
data-aos-duration="300"
style={{
position: "fixed",
bottom: "40px",
right: "40px",
width: "40px",
height: "40px",
borderRadius: "50%",
border: "none",
background: "linear-gradient(135deg, hsl(263 70% 65%), hsl(180 100% 70%))",
color: "#fff",
cursor: "pointer",
zIndex: 99,
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: 0,
}}
>
<div
style={{
width: "14px",
height: "14px",
borderTop: "1.5px solid black",
borderLeft: "1.5px solid black",
transform: "rotate(45deg) translateY(3px) translateX(2px)",
}}
></div>
</button>
)}
</>
);
};
export default MoveToTop;
```
--------------------------------------------------------------------------------
/tests/sample_project_go/basic_functions.go:
--------------------------------------------------------------------------------
```go
// basic_functions.go - Demonstrates basic Go function patterns
package main
import (
"fmt"
"math"
)
// SimpleFunction is a basic function with single return
func SimpleFunction(x int) int {
return x * 2
}
// MultipleReturns demonstrates multiple return values
func MultipleReturns(a, b int) (int, int, error) {
if b == 0 {
return 0, 0, fmt.Errorf("division by zero")
}
return a + b, a - b, nil
}
// NamedReturns uses named return values
func NamedReturns(x, y int) (sum int, product int) {
sum = x + y
product = x * y
return // naked return
}
// VariadicFunction accepts variable number of arguments
func VariadicFunction(prefix string, numbers ...int) string {
result := prefix
for _, num := range numbers {
result += fmt.Sprintf(" %d", num)
}
return result
}
// HigherOrderFunction takes a function as parameter
func HigherOrderFunction(fn func(int) int, value int) int {
return fn(value) + 10
}
// FunctionReturningFunction returns a closure
func FunctionReturningFunction(multiplier int) func(int) int {
return func(x int) int {
return x * multiplier
}
}
// RecursiveFunction demonstrates recursion
func RecursiveFunction(n int) int {
if n <= 1 {
return 1
}
return n * RecursiveFunction(n-1)
}
// DeferExample shows defer usage
func DeferExample() string {
defer fmt.Println("This runs last")
fmt.Println("This runs first")
return "Function complete"
}
// PanicRecoverExample demonstrates panic and recover
func PanicRecoverExample(shouldPanic bool) (result string) {
defer func() {
if r := recover(); r != nil {
result = fmt.Sprintf("Recovered from: %v", r)
}
}()
if shouldPanic {
panic("something went wrong")
}
result = "No panic occurred"
return
}
// MathHelper calls external package function
func MathHelper(x float64) float64 {
return math.Sqrt(x)
}
// init function runs before main
func init() {
fmt.Println("Initializing basic_functions package")
}
func main() {
fmt.Println(SimpleFunction(5))
sum, diff, _ := MultipleReturns(10, 3)
fmt.Println(sum, diff)
doubler := FunctionReturningFunction(2)
fmt.Println(doubler(5))
}
```
--------------------------------------------------------------------------------
/website/src/components/ui/input-otp.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { Dot } from "lucide-react";
import { cn } from "@/lib/utils";
const InputOTP = React.forwardRef<React.ElementRef<typeof OTPInput>, React.ComponentPropsWithoutRef<typeof OTPInput>>(
({ className, containerClassName, ...props }, ref) => (
<OTPInput
ref={ref}
containerClassName={cn("flex items-center gap-2 has-[:disabled]:opacity-50", containerClassName)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
),
);
InputOTP.displayName = "InputOTP";
const InputOTPGroup = React.forwardRef<React.ElementRef<"div">, React.ComponentPropsWithoutRef<"div">>(
({ className, ...props }, ref) => <div ref={ref} className={cn("flex items-center", className)} {...props} />,
);
InputOTPGroup.displayName = "InputOTPGroup";
const InputOTPSlot = React.forwardRef<
React.ElementRef<"div">,
React.ComponentPropsWithoutRef<"div"> & { index: number }
>(({ index, className, ...props }, ref) => {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index];
return (
<div
ref={ref}
className={cn(
"relative flex h-10 w-10 items-center justify-center border-y border-r border-input text-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
isActive && "z-10 ring-2 ring-ring ring-offset-background",
className,
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="animate-caret-blink h-4 w-px bg-foreground duration-1000" />
</div>
)}
</div>
);
});
InputOTPSlot.displayName = "InputOTPSlot";
const InputOTPSeparator = React.forwardRef<React.ElementRef<"div">, React.ComponentPropsWithoutRef<"div">>(
({ ...props }, ref) => (
<div ref={ref} role="separator" {...props}>
<Dot />
</div>
),
);
InputOTPSeparator.displayName = "InputOTPSeparator";
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };
```
--------------------------------------------------------------------------------
/docs/docs/core.md:
--------------------------------------------------------------------------------
```markdown
# Core Concepts
The core of CodeGraphContext is built upon a few key components that manage the database connection, handle background tasks, and watch for file system changes.
## `DatabaseManager`
The `DatabaseManager` class in `database.py` is a thread-safe singleton responsible for managing the connection to the Neo4j database. This ensures that only one connection pool is created and shared across the application, which is crucial for performance and resource management.
### Key Methods
- `get_driver()`: Returns the active Neo4j Driver instance, creating it if it doesn't exist.
- `close_driver()`: Closes the Neo4j driver connection.
- `is_connected()`: Checks if the database connection is currently active.
## `JobManager`
The `JobManager` class in `jobs.py` handles long-running, background jobs, such as code indexing. It stores job information in memory and provides a thread-safe way to create, update, and retrieve information about these jobs.
### `JobStatus`
An enumeration for the possible statuses of a background job:
- `PENDING`
- `RUNNING`
- `COMPLETED`
- `FAILED`
- `CANCELLED`
### `JobInfo`
A data class that holds all information about a single background job, including its ID, status, start/end times, progress, and any errors.
### Key Methods
- `create_job()`: Creates a new job with a unique ID.
- `update_job()`: Updates the information for a specific job.
- `get_job()`: Retrieves the information for a single job.
- `list_jobs()`: Returns a list of all jobs.
- `cleanup_old_jobs()`: Removes old, completed jobs from memory.
## `CodeWatcher`
The `CodeWatcher` class in `watcher.py` implements the live file-watching functionality using the `watchdog` library. It observes directories for changes and triggers updates to the code graph.
### `RepositoryEventHandler`
A dedicated event handler for a single repository. It performs an initial scan and then uses a debouncing mechanism to efficiently handle file changes, creations, or deletions.
### Key Methods
- `watch_directory()`: Schedules a directory to be watched for changes.
- `unwatch_directory()`: Stops watching a directory.
- `list_watched_paths()`: Returns a list of all currently watched directory paths.
- `start()`: Starts the observer thread.
- `stop()`: Stops the observer thread gracefully.
```
--------------------------------------------------------------------------------
/organizer/Tools_Exploration.md:
--------------------------------------------------------------------------------
```markdown
# Tools Exploration
There are a total of 14 tools available to the users, and here we have attached illustrative demos for each one of them.
## find_code Tool
The `find_code` tool allows users to search for code snippets, functions, classes, and variables within the codebase using natural language queries. This tool helps developers understand and navigate large codebases efficiently.
Below is an embedded link to a demo video showcasing the usage of the `find_code` tool in action.
[](https://drive.google.com/file/d/1ojCDIIAwcir9e3jgHHIVC5weZ9nuIQcs/view?usp=drive_link)
---
## watch_directory Tool
The `watch_directory` tool allows users to monitor a specified directory for file changes, additions, or deletions in real-time. It helps developers automate workflows such as triggering scripts, updating indexes, or syncing files whenever changes occur in the directory.
Below is an embedded link to a demo video showcasing the usage of the `watch_directory` tool in a development environment.
[](https://drive.google.com/file/d/1OEjcS2iwwymss99zLidbeBjcblferKBX/view?usp=drive_link)
---
## analyze_code_relationships Tool
The `analyze_code_relationships` tool in CodeGraphContext is designed to let users query and explore the various relationships between code elements in a codebase, represented as a graph in Neo4j.
### Relationship Types That Can Be Analyzed
- **CALLS:** Finds which functions call or are called by a function.
- **CALLED_BY:** Finds all functions that directly or indirectly call a target function (inverse of CALLS).
- **INHERITS_FROM:** Finds class inheritance relationships; which classes inherit from which.
- **CONTAINS:** Shows containment (which classes/functions are inside which modules or files).
- **IMPLEMENTS:** Shows which classes implement an interface.
- **IMPORTS:** Identifies which files or modules import a specific module.
- **DEFINED_IN:** Locates where an entity (function/class) is defined.
- **HAS_ARGUMENT:** Shows relationships from functions to their arguments.
- **DECLARES:** Finds variables declared in functions or classes.
Below is an embedded link to a demo video showcasing the usage of the `analyse_code_relationships` tool.
[](https://drive.google.com/file/d/154M_lTPbg9_Gj9bd2ErnAVbJArSbcb2M/view?usp=drive_link)
---
```