This is page 1 of 17. Use http://codebase.md/shashankss1205/codegraphcontext?page={x} to view the full context.
# Directory Structure
```
├── .cgcignore
├── .github
│ ├── FUNDING.yml
│ └── workflows
│ ├── e2e-tests.yml
│ ├── post_discord_invite.yml
│ ├── test.yml
│ └── update-contributors.yml
├── .gitignore
├── CLI_Commands.md
├── 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
│ │ └── watching.md
│ ├── mkdocs.yml
│ └── site
│ ├── 404.html
│ ├── architecture
│ │ └── index.html
│ ├── assets
│ │ ├── images
│ │ │ └── favicon.png
│ │ ├── javascripts
│ │ │ ├── bundle.79ae519e.min.js
│ │ │ ├── bundle.79ae519e.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.2c215733.min.js
│ │ │ └── search.2c215733.min.js.map
│ │ └── stylesheets
│ │ ├── main.484c7ddc.min.css
│ │ ├── main.484c7ddc.min.css.map
│ │ ├── palette.ab4e12ef.min.css
│ │ └── palette.ab4e12ef.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
│ └── watching
│ └── index.html
├── funding.json
├── 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
├── pyproject.toml
├── README.md
├── scripts
│ ├── generate_lang_contributors.py
│ ├── post_install_fix.sh
│ ├── test_all_parsers.py
│ └── update_language_parsers.py
├── SECURITY.md
├── src
│ └── codegraphcontext
│ ├── __init__.py
│ ├── __main__.py
│ ├── cli
│ │ ├── __init__.py
│ │ ├── cli_helpers.py
│ │ ├── config_manager.py
│ │ ├── main.py
│ │ ├── setup_macos.py
│ │ └── setup_wizard.py
│ ├── core
│ │ ├── __init__.py
│ │ ├── database_falkordb.py
│ │ ├── database.py
│ │ ├── falkor_worker.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
│ │ │ ├── csharp.py
│ │ │ ├── go.py
│ │ │ ├── java.py
│ │ │ ├── javascript.py
│ │ │ ├── kotlin.py
│ │ │ ├── php.py
│ │ │ ├── python.py
│ │ │ ├── ruby.py
│ │ │ ├── rust.py
│ │ │ ├── scala.py
│ │ │ ├── swift.py
│ │ │ ├── typescript.py
│ │ │ └── typescriptjsx.py
│ │ ├── package_resolver.py
│ │ ├── query_tool_languages
│ │ │ ├── c_toolkit.py
│ │ │ ├── cpp_toolkit.py
│ │ │ ├── csharp_toolkit.py
│ │ │ ├── go_toolkit.py
│ │ │ ├── java_toolkit.py
│ │ │ ├── javascript_toolkit.py
│ │ │ ├── python_toolkit.py
│ │ │ ├── ruby_toolkit.py
│ │ │ ├── rust_toolkit.py
│ │ │ ├── scala_toolkit.py
│ │ │ ├── swift_toolkit.py
│ │ │ └── typescript_toolkit.py
│ │ └── system.py
│ └── utils
│ ├── debug_log.py
│ └── tree_sitter_manager.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_csharp
│ │ ├── README.md
│ │ └── src
│ │ └── Example.App
│ │ ├── Attributes
│ │ │ └── CustomAttributes.cs
│ │ ├── Example.App.csproj
│ │ ├── Models
│ │ │ ├── Person.cs
│ │ │ ├── Point.cs
│ │ │ ├── Role.cs
│ │ │ └── User.cs
│ │ ├── OuterClass.cs
│ │ ├── Program.cs
│ │ ├── Services
│ │ │ ├── GreetingService.cs
│ │ │ ├── IGreetingService.cs
│ │ │ └── LegacyService.cs
│ │ └── Utils
│ │ ├── CollectionHelper.cs
│ │ └── FileHelper.cs
│ ├── 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_kotlin
│ │ ├── AdvancedClasses.kt
│ │ ├── Annotations.kt
│ │ ├── Coroutines.kt
│ │ ├── EdgeCases.kt
│ │ ├── Functions.kt
│ │ ├── Main.kt
│ │ ├── Properties.kt
│ │ └── User.kt
│ ├── 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_scala
│ │ ├── Animals.scala
│ │ ├── Complex.scala
│ │ ├── Functional.scala
│ │ ├── Geometry.scala
│ │ ├── Main.scala
│ │ ├── PackageObject.scala
│ │ ├── Script.sc
│ │ ├── Services.scala
│ │ ├── Shapes.scala
│ │ ├── Utils.scala
│ │ └── Variables.scala
│ ├── sample_project_swift
│ │ ├── Generics.swift
│ │ ├── Main.swift
│ │ ├── README.md
│ │ ├── Shapes.swift
│ │ ├── User.swift
│ │ └── Vehicles.swift
│ ├── sample_project_typescript
│ │ ├── package.json
│ │ ├── README.md
│ │ ├── sample_tsx.tsx
│ │ ├── 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_kotlin_parser.py
│ ├── test_swift_parser.py
│ ├── test_tree_sitter
│ │ ├── __init__.py
│ │ ├── class_instantiation.py
│ │ ├── complex_classes.py
│ │ └── test_file.py
│ ├── test_tree_sitter_manager.py
│ └── test_typescript_parser.py
├── visualize_graph.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
│ │ │ ├── SocialMentionsTimeline.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
└── windows_setup_guide.md
```
# 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
# temporary files
*.temp
*.tmp
*.log
temporaryFiles
codegraph_viz.html
Temp
```
--------------------------------------------------------------------------------
/.cgcignore:
--------------------------------------------------------------------------------
```
website/
docs/
# 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
# temporary files
*.temp
*.tmp
*.log
temporaryFiles
codegraph_viz.html
Temp
```
--------------------------------------------------------------------------------
/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_swift/README.md:
--------------------------------------------------------------------------------
```markdown
# Swift Sample Project
This is a sample Swift project for testing the CodeGraphContext Swift parser.
## Files
### Main.swift
- **Main** class with a `run()` method
- **Calculator** class with basic arithmetic operations
- Demonstrates class instantiation and method calls
### User.swift
- **Greeter** protocol defining a greeting interface
- **User** struct conforming to the Greeter protocol
- Extension on User struct adding additional functionality
- Demonstrates protocols, structs, and extensions
### Shapes.swift
- **Shape** protocol defining area and perimeter methods
- **Circle** class implementing Shape
- **Rectangle** struct implementing Shape
- **Triangle** class implementing Shape
- Demonstrates protocol conformance with multiple types
### Vehicles.swift
- **VehicleType** enum with different vehicle types
- **Result** enum with associated values (generic)
- **Vehicle** base class
- **Car** class inheriting from Vehicle
- Demonstrates enums, inheritance, and method overriding
### Generics.swift
- **Stack** generic class implementing a stack data structure
- Generic `swap` function
- **Container** protocol with associated type
- **IntCollection** struct conforming to Container
- Demonstrates Swift generics and protocols with associated types
## Features Tested
- ✅ Classes and structs
- ✅ Protocols and protocol conformance
- ✅ Enums (simple and with associated values)
- ✅ Inheritance
- ✅ Extensions
- ✅ Generics
- ✅ Functions and methods
- ✅ Initializers
- ✅ Properties
- ✅ Method calls
- ✅ Imports
```
--------------------------------------------------------------------------------
/tests/sample_project_csharp/README.md:
--------------------------------------------------------------------------------
```markdown
# Sample C# Project for CodeGraphContext
This is a sample C# project used for testing the CodeGraphContext C# parser.
## Project Structure
```
sample_project_csharp/
├── src/
│ └── Example.App/
│ ├── Program.cs # Main entry point
│ ├── OuterClass.cs # Nested class example
│ ├── Models/
│ │ ├── User.cs # User class
│ │ ├── Role.cs # Role enum
│ │ ├── Person.cs # Record types
│ │ └── Point.cs # Struct types
│ ├── Services/
│ │ ├── IGreetingService.cs # Interface
│ │ ├── GreetingService.cs # Service implementation
│ │ └── LegacyService.cs # Service with attributes
│ ├── Utils/
│ │ ├── CollectionHelper.cs # Collection utilities
│ │ └── FileHelper.cs # File I/O utilities
│ └── Attributes/
│ └── CustomAttributes.cs # Custom attribute definitions
└── README.md # This file
```
## Features Demonstrated
### Language Constructs
- **Classes**: Regular classes with constructors, methods, and properties
- **Interfaces**: Interface definitions and implementations
- **Enums**: Enumeration types
- **Records**: C# 9.0+ record types with inheritance
- **Structs**: Value types including readonly structs
- **Nested Classes**: Inner classes with access to outer class members
- **Static Classes**: Utility classes with static methods
### Advanced Features
- **Custom Attributes**: Attribute definitions and usage
- **Generics**: Generic collections (IEnumerable<T>)
- **LINQ**: Language Integrated Query operations
- **Properties**: Auto-properties and computed properties
- **Operator Overloading**: Custom operators for structs
- **Pattern Matching**: Switch expressions
- **Namespaces**: Organized code structure
### Method Types
- Constructors (default and parameterized)
- Instance methods
- Static methods
- Private helper methods
- Methods with attributes
### Dependencies
- System namespaces (System, System.Collections.Generic, System.IO, System.Linq)
- Internal project references
## Purpose
This project is designed to test the C# parser's ability to:
1. Parse class, interface, struct, enum, and record declarations
2. Extract method signatures and parameters
3. Identify using directives and imports
4. Track method calls and object creation
5. Handle nested classes and namespaces
6. Recognize custom attributes
7. Build accurate code graphs for C# projects
```
--------------------------------------------------------------------------------
/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
```
--------------------------------------------------------------------------------
/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.*
```
--------------------------------------------------------------------------------
/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)
A powerful **MCP server** and **CLI toolkit** that indexes local code into a graph database to provide context to AI assistants and developers. Use it as a standalone CLI for comprehensive code analysis or connect it to your favorite AI IDE via MCP for AI-powered code understanding.
### Indexing a codebase

### Using the MCP server

## Project Details
- **Version:** 0.1.32
- **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 File Watching:** Watch directories for changes and automatically update the graph in real-time (`cgc watch`).
- **Interactive Setup:** A user-friendly command-line wizard for easy setup.
- **Dual Mode:** Works as a standalone **CLI toolkit** for developers and as an **MCP server** for AI agents.
- **Multi-Language Support:** Full support for 12 programming languages.
- **Flexible Database Backend:** FalkorDB Lite (default, inbuilt for Unix and through WSL for Windows) or Neo4j (all platforms via Docker/native).
## Supported Programming Languages
CodeGraphContext provides comprehensive parsing and analysis for the following languages:
- **Python** (`.py`) - Including Jupyter notebooks (`.ipynb`)
- **JavaScript** (`.js`)
- **TypeScript** (`.ts`)
- **Java** (`.java`)
- **C** (`.c`, `.h`)
- **C++** (`.cpp`, `.cc`, `.cxx`, `.hpp`, `.hxx`)
- **C#** (`.cs`) - Full support for classes, methods, namespaces, and inheritance
- **Go** (`.go`)
- **Rust** (`.rs`)
- **Ruby** (`.rb`)
- **PHP** (`.php`)
- **Kotlin** (`.kt`) - Full support for classes, objects, companions, functions, and coroutines
- **Swift** (`.swift`) - Full support for classes, structs, protocols, enums, and generics
Each language parser extracts functions, classes, methods, parameters, inheritance relationships, function calls, and imports to build a comprehensive code graph.
## Database Options
CodeGraphContext supports two graph database backends:
### FalkorDB Lite (Default for Unix/Linux/macOS)
- **Lightweight** in-memory graph database
- **No external dependencies** - runs entirely in-process
- **Inbuilt and enabled by default** for Unix-based systems (Linux, macOS)
- Available for **Python 3.12+** only
- Perfect for quick testing, development, and most use cases
- Automatically installed and configured when using Python 3.12 or higher on Unix systems
> ⚠️ **Windows Users:**
> FalkorDB Lite / redislite is **not supported on Windows**.
> You have three options:
> 1. Run the project under **WSL (Windows Subsystem for Linux)**: [WSL Install](https://learn.microsoft.com/en-us/windows/wsl/install)
> 2. Use **Docker** to run the project in a containerized Linux environment
> 3. Use **Neo4j** directly as your graph database (see below)
### Neo4j (Available for All Platforms)
- **Production-ready** and widely used graph database
- **Available on all operating systems**: Windows, Linux, macOS
- Can be installed via:
- **Docker** (recommended, cross-platform)
- **WSL** (for Windows users)
- **Native installation** (dedicated command for each OS)
- Supports local instances and cloud hosting (Neo4j AuraDB)
- Full Cypher query support for advanced graph analytics
- Recommended for Windows users and production deployments
The `cgc neo4j setup` wizard helps you configure the Neo4j database backend, while FalkorDB Lite is enabled by default on Unix systems with no configuration needed.
## 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`
- `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.21.0`
- `tree-sitter-language-pack>=0.6.0`
- `pyyaml`
- `pytest`
- `nbformat`
- `nbconvert>=7.16.6`
- `pathspec>=0.12.1`
**Note:** Python 3.10-3.14 is supported.
## Getting Started
### 📋 Understanding CodeGraphContext Modes
CodeGraphContext operates in **two modes**, and you can use either or both:
#### 🛠️ Mode 1: CLI Toolkit (Standalone)
Use CodeGraphContext as a **powerful command-line toolkit** for code analysis:
- Index and analyze codebases directly from your terminal
- Query code relationships, find dead code, analyze complexity
- Visualize code graphs and dependencies
- Perfect for developers who want direct control via CLI commands
#### 🤖 Mode 2: MCP Server (AI-Powered)
Use CodeGraphContext as an **MCP server** for AI assistants:
- Connect to AI IDEs (VS Code, Cursor, Windsurf, Claude, etc.)
- Let AI agents query your codebase using natural language
- Automatic code understanding and relationship analysis
- Perfect for AI-assisted development workflows
**You can use both modes!** Install once, then use CLI commands directly OR connect to your AI assistant.
---
### Installation (Both Modes)
1. **Install:** `pip install codegraphcontext`
<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>
2. **Database Setup (Automatic for Unix/WSL)**
- **FalkorDB Lite (Default):** If you're on Unix/Linux/macOS/WSL with Python 3.12+, you're done! FalkorDB Lite is already configured.
- **Neo4j (Optional/Windows):** To use Neo4j instead, or if you're on Windows without WSL, run: `cgc neo4j setup`
---
### 🛠️ For CLI Toolkit Mode
**Start using immediately with CLI commands:**
```bash
# Index your current directory
cgc index .
# List all indexed repositories
cgc list
# Analyze who calls a function
cgc analyze callers my_function
# Find complex code
cgc analyze complexity --threshold 10
# Find dead code
cgc analyze dead-code
# Watch for live changes (optional)
cgc watch .
# See all commands
cgc help
```
**See the full [CLI Commands Guide](CLI_Commands.md) for all available commands and usage scenarios.**
---
### 🤖 For MCP Server Mode
**Configure your AI assistant to use CodeGraphContext:**
1. **Setup:** Run the MCP setup wizard to configure your IDE/AI assistant:
```bash
cgc mcp setup
```
The wizard can automatically detect and configure:
* VS Code
* Cursor
* Windsurf
* Claude
* Gemini CLI
* ChatGPT Codex
* Cline
* RooCode
* Amazon Q Developer
Upon successful configuration, `cgc mcp setup` will generate and place the necessary configuration files:
* It creates an `mcp.json` file in your current directory for reference.
* It stores your database 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`).
2. **Start:** Launch the MCP server:
```bash
cgc mcp start
```
3. **Use:** Now interact with your codebase through your AI assistant using natural language! See examples below.
## 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 mcp 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": [
"mcp",
"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.
```
--------------------------------------------------------------------------------
/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" />
```
--------------------------------------------------------------------------------
/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_csharp/src/Example.App/Models/Role.cs:
--------------------------------------------------------------------------------
```csharp
namespace Example.App.Models
{
/// <summary>
/// User role enumeration
/// </summary>
public enum Role
{
Guest,
User,
Admin,
SuperAdmin
}
}
```
--------------------------------------------------------------------------------
/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/scala_toolkit.py:
--------------------------------------------------------------------------------
```python
class ScalaToolkit:
"""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/swift_toolkit.py:
--------------------------------------------------------------------------------
```python
class SwiftToolkit:
"""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/csharp_toolkit.py:
--------------------------------------------------------------------------------
```python
class CSharpToolkit:
"""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_csharp/src/Example.App/Services/IGreetingService.cs:
--------------------------------------------------------------------------------
```csharp
using Example.App.Models;
namespace Example.App.Services
{
/// <summary>
/// Interface for greeting services
/// </summary>
public interface IGreetingService
{
string Greet(User user);
}
}
```
--------------------------------------------------------------------------------
/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_kotlin/User.kt:
--------------------------------------------------------------------------------
```kotlin
package com.example.project
interface Greeter {
fun greet(): String
}
data class User(val name: String, val age: Int) : Greeter {
override fun greet(): String {
return "Hello, my name is $name and I am $age years old."
}
}
```
--------------------------------------------------------------------------------
/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_typescript/sample_tsx.tsx:
--------------------------------------------------------------------------------
```typescript
import React from 'react';
export interface SampleProps {
title: string;
}
export const SampleComponent: React.FC<SampleProps> = ({ title }) => {
return <div>{title}</div>;
};
export function helperFunction(x: number): number {
return x * 2;
}
export default SampleComponent;
```
--------------------------------------------------------------------------------
/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_kotlin/Annotations.kt:
--------------------------------------------------------------------------------
```kotlin
package com.example.project.annotations
annotation class Fancy(val id: Int)
@Fancy(1)
class Foo {
@Fancy(2)
fun baz(@Fancy(3) foo: Int): Int {
return 1
}
}
// Reflection usage
fun reflection() {
val c = Foo::class
for (a in c.annotations) {
println(a)
}
}
```
--------------------------------------------------------------------------------
/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_kotlin/Main.kt:
--------------------------------------------------------------------------------
```kotlin
package com.example.project
import com.example.project.User
class Main {
fun main(args: Array<String>) {
val user = User("Shashank", 30)
println(user.greet())
val calculator = Calculator()
println(calculator.add(5, 10))
}
}
class Calculator {
fun add(a: Int, b: Int): Int {
return a + b
}
}
```
--------------------------------------------------------------------------------
/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_kotlin/Properties.kt:
--------------------------------------------------------------------------------
```kotlin
package com.example.project.properties
class User {
var name: String = "John"
get() = field.uppercase()
set(value) {
field = value.trim()
}
val isValid: Boolean
get() = name.length > 0
lateinit var data: String
val lazyData: String by lazy {
println("Computing...")
"Heavy"
}
}
```
--------------------------------------------------------------------------------
/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_kotlin/Coroutines.kt:
--------------------------------------------------------------------------------
```kotlin
package com.example.project.coroutines
import kotlinx.coroutines.*
suspend fun doWorld() {
delay(1000L)
println("World!")
}
fun main() = runBlocking {
launch {
doWorld()
}
println("Hello")
}
class AsyncProcessor {
suspend fun process(): String = coroutineScope {
val deferred = async {
delay(500)
"Result"
}
deferred.await()
}
}
```
--------------------------------------------------------------------------------
/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_csharp/src/Example.App/Models/User.cs:
--------------------------------------------------------------------------------
```csharp
namespace Example.App.Models
{
/// <summary>
/// Represents a user in the system
/// </summary>
public class User
{
public string Name { get; set; }
public Role Role { get; set; }
public User(string name, Role role)
{
Name = name;
Role = role;
}
public string GetDisplayName()
{
return $"{Name} ({Role})";
}
}
}
```
--------------------------------------------------------------------------------
/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
```
--------------------------------------------------------------------------------
/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.
```
--------------------------------------------------------------------------------
/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
- Live Watching: watching.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_swift/User.swift:
--------------------------------------------------------------------------------
```swift
import Foundation
// Protocol for greeting
protocol Greeter {
func greet() -> String
}
// User struct conforming to Greeter protocol
struct User: Greeter {
let name: String
let age: Int
func greet() -> String {
return "Hello, my name is \(name) and I am \(age) years old."
}
func isAdult() -> Bool {
return age >= 18
}
}
// Extension to add additional functionality
extension User {
func birthYear(currentYear: Int) -> Int {
return currentYear - age
}
}
```
--------------------------------------------------------------------------------
/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.12'
- 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.12"
- 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_swift/Main.swift:
--------------------------------------------------------------------------------
```swift
import Foundation
// Main entry point
class Main {
func run() {
let user = User(name: "Shashank", age: 30)
print(user.greet())
let calculator = Calculator()
print(calculator.add(a: 5, b: 10))
let shape = Circle(radius: 5.0)
print("Area: \(shape.area())")
}
}
// Simple calculator class
class Calculator {
func add(a: Int, b: Int) -> Int {
return a + b
}
func subtract(a: Int, b: Int) -> Int {
return a - b
}
func multiply(a: Int, b: Int) -> Int {
return a * b
}
}
// Entry point
let main = Main()
main.run()
```
--------------------------------------------------------------------------------
/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"]
}
```
--------------------------------------------------------------------------------
/tests/sample_project_csharp/src/Example.App/Models/Person.cs:
--------------------------------------------------------------------------------
```csharp
using System;
namespace Example.App.Models
{
/// <summary>
/// Record type for immutable person data (C# 9.0+)
/// </summary>
public record Person(string FirstName, string LastName, int Age)
{
public string FullName => $"{FirstName} {LastName}";
public bool IsAdult() => Age >= 18;
}
/// <summary>
/// Record class with custom constructor
/// </summary>
public record Employee(string FirstName, string LastName, int Age, string Department)
: Person(FirstName, LastName, Age)
{
public string GetEmployeeInfo()
{
return $"{FullName} works in {Department}";
}
}
}
```
--------------------------------------------------------------------------------
/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 };
```
--------------------------------------------------------------------------------
/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
class WithMeta2(metaclass=Meta):
def __init__(self):
self.value = 42
def __str__(self):
return f"WithMeta2(value={self.value})"
def change_value(self, new_value):
self.value = new_value
```
--------------------------------------------------------------------------------
/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 };
```
--------------------------------------------------------------------------------
/tests/sample_project_csharp/src/Example.App/Services/LegacyService.cs:
--------------------------------------------------------------------------------
```csharp
using System;
using Example.App.Attributes;
namespace Example.App.Services
{
/// <summary>
/// Service demonstrating use of custom attributes
/// </summary>
public class LegacyService
{
[Deprecated("This method is deprecated. Use NewMethod instead.", AlternativeMethod = "NewMethod")]
public void OldMethod()
{
Console.WriteLine("This is the old method");
}
[Log("Info")]
public void NewMethod()
{
Console.WriteLine("This is the new method");
}
[Log("Debug")]
[Log("Trace")]
public void MethodWithMultipleAttributes()
{
Console.WriteLine("Method with multiple log attributes");
}
}
}
```
--------------------------------------------------------------------------------
/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))}}}});
```
--------------------------------------------------------------------------------
/tests/sample_project_csharp/src/Example.App/Attributes/CustomAttributes.cs:
--------------------------------------------------------------------------------
```csharp
using System;
namespace Example.App.Attributes
{
/// <summary>
/// Custom attribute for marking deprecated methods
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class DeprecatedAttribute : Attribute
{
public string Message { get; }
public string AlternativeMethod { get; set; }
public DeprecatedAttribute(string message)
{
Message = message;
}
}
/// <summary>
/// Custom attribute for logging
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class LogAttribute : Attribute
{
public string LogLevel { get; }
public LogAttribute(string logLevel = "Info")
{
LogLevel = logLevel;
}
}
}
```
--------------------------------------------------------------------------------
/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;
}
}
```
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
```yaml
# These are supported funding model platforms
github: Shashankss1205 # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
```
--------------------------------------------------------------------------------
/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"
]
}
```
--------------------------------------------------------------------------------
/tests/sample_project_csharp/src/Example.App/OuterClass.cs:
--------------------------------------------------------------------------------
```csharp
namespace Example.App
{
/// <summary>
/// Demonstrates nested classes in C#
/// </summary>
public class OuterClass
{
private string _outerValue;
public OuterClass(string value)
{
_outerValue = value;
}
public InnerClass CreateInner(string innerValue)
{
return new InnerClass(this, innerValue);
}
/// <summary>
/// Inner class that can access outer class members
/// </summary>
public class InnerClass
{
private OuterClass _outer;
private string _innerValue;
public InnerClass(OuterClass outer, string value)
{
_outer = outer;
_innerValue = value;
}
public string Combine()
{
return $"{_outer._outerValue}-{_innerValue}";
}
}
}
}
```
--------------------------------------------------------------------------------
/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());
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_kotlin/AdvancedClasses.kt:
--------------------------------------------------------------------------------
```kotlin
package com.example.project.advanced
// Abstract class hierarchy
abstract class Shape {
abstract fun area(): Double
open fun description(): String = "Unknown Shape"
}
class Circle(val radius: Double) : Shape() {
override fun area(): Double = Math.PI * radius * radius
override fun description(): String = "Circle with radius $radius"
}
// Sealed class hierarchy
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()
object Loading : Result()
}
// Nested and Inner classes
class Outer {
private val bar: Int = 1
class Nested {
fun foo() = 2
}
inner class Inner {
fun foo() = bar
}
}
// Companion Object
class DatabaseConnection {
companion object Factory {
fun create(): DatabaseConnection = DatabaseConnection()
const val TIMEOUT = 3000
}
}
// Object declaration (Singleton)
object Configuration {
var host: String = "localhost"
var port: Int = 8080
}
interface Clickable {
fun click()
fun doubleClick() {
click()
click()
}
}
```
--------------------------------------------------------------------------------
/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>
)
}
```
--------------------------------------------------------------------------------
/tests/sample_project_swift/Generics.swift:
--------------------------------------------------------------------------------
```swift
import Foundation
// Generic data structure
class Stack<T> {
private var items: [T] = []
func push(_ item: T) {
items.append(item)
}
func pop() -> T? {
return items.isEmpty ? nil : items.removeLast()
}
func peek() -> T? {
return items.last
}
var count: Int {
return items.count
}
var isEmpty: Bool {
return items.isEmpty
}
}
// Generic function
func swap<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
// Protocol with associated type
protocol Container {
associatedtype Item
mutating func append(_ item: Item)
var count: Int { get }
subscript(i: Int) -> Item { get }
}
// Array extension conforming to Container
extension Array: Container {
// Array already has append, count, and subscript
}
// Custom collection
struct IntCollection: Container {
typealias Item = Int
private var items: [Int] = []
mutating func append(_ item: Int) {
items.append(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Int {
return items[i]
}
}
```
--------------------------------------------------------------------------------
/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");
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_csharp/src/Example.App/Models/Point.cs:
--------------------------------------------------------------------------------
```csharp
using System;
namespace Example.App.Models
{
/// <summary>
/// Struct for representing a 2D point
/// </summary>
public struct Point
{
public double X { get; set; }
public double Y { get; set; }
public Point(double x, double y)
{
X = x;
Y = y;
}
public double DistanceFromOrigin()
{
return Math.Sqrt(X * X + Y * Y);
}
public static Point operator +(Point a, Point b)
{
return new Point(a.X + b.X, a.Y + b.Y);
}
public override string ToString()
{
return $"({X}, {Y})";
}
}
/// <summary>
/// Readonly struct for immutable coordinates
/// </summary>
public readonly struct Coordinate
{
public double Latitude { get; }
public double Longitude { get; }
public Coordinate(double latitude, double longitude)
{
Latitude = latitude;
Longitude = longitude;
}
public override string ToString()
{
return $"Lat: {Latitude}, Lon: {Longitude}";
}
}
}
```
--------------------------------------------------------------------------------
/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 };
```
--------------------------------------------------------------------------------
/tests/sample_project_csharp/src/Example.App/Services/GreetingService.cs:
--------------------------------------------------------------------------------
```csharp
using System;
using Example.App.Models;
namespace Example.App.Services
{
/// <summary>
/// Implementation of greeting service
/// </summary>
public class GreetingService : IGreetingService
{
private readonly string _defaultGreeting = "Hello";
public GreetingService()
{
}
public GreetingService(string defaultGreeting)
{
_defaultGreeting = defaultGreeting;
}
public string Greet(User user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return FormatGreeting(user);
}
private string FormatGreeting(User user)
{
string rolePrefix = GetRolePrefix(user.Role);
return $"{_defaultGreeting}, {rolePrefix}{user.Name}!";
}
private string GetRolePrefix(Role role)
{
return role switch
{
Role.Admin => "Administrator ",
Role.SuperAdmin => "Super Admin ",
Role.User => "",
Role.Guest => "Guest ",
_ => ""
};
}
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_csharp/src/Example.App/Utils/CollectionHelper.cs:
--------------------------------------------------------------------------------
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace Example.App.Utils
{
/// <summary>
/// Helper class for collection operations
/// </summary>
public static class CollectionHelper
{
/// <summary>
/// Calculates the sum of squares of all numbers in the collection
/// </summary>
public static int SumOfSquares(IEnumerable<int> numbers)
{
if (numbers == null)
{
throw new ArgumentNullException(nameof(numbers));
}
return numbers.Select(n => n * n).Sum();
}
/// <summary>
/// Filters even numbers from the collection
/// </summary>
public static IEnumerable<int> FilterEven(IEnumerable<int> numbers)
{
return numbers.Where(n => n % 2 == 0);
}
/// <summary>
/// Finds the maximum value in the collection
/// </summary>
public static int FindMax(IEnumerable<int> numbers)
{
if (!numbers.Any())
{
throw new InvalidOperationException("Collection is empty");
}
return numbers.Max();
}
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_swift/Shapes.swift:
--------------------------------------------------------------------------------
```swift
import Foundation
// Protocol for shapes
protocol Shape {
func area() -> Double
func perimeter() -> Double
}
// Circle class implementing Shape
class Circle: Shape {
let radius: Double
init(radius: Double) {
self.radius = radius
}
func area() -> Double {
return Double.pi * radius * radius
}
func perimeter() -> Double {
return 2 * Double.pi * radius
}
}
// Rectangle struct implementing Shape
struct Rectangle: Shape {
let width: Double
let height: Double
func area() -> Double {
return width * height
}
func perimeter() -> Double {
return 2 * (width + height)
}
func isSquare() -> Bool {
return width == height
}
}
// Triangle class implementing Shape
class Triangle: Shape {
let base: Double
let height: Double
let sideA: Double
let sideB: Double
init(base: Double, height: Double, sideA: Double, sideB: Double) {
self.base = base
self.height = height
self.sideA = sideA
self.sideB = sideB
}
func area() -> Double {
return 0.5 * base * height
}
func perimeter() -> Double {
return base + sideA + sideB
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_kotlin/Functions.kt:
--------------------------------------------------------------------------------
```kotlin
package com.example.project.functions
// Higher-Order Function
fun <T> List<T>.customFilter(predicate: (T) -> Boolean): List<T> {
val result = ArrayList<T>()
for (item in this) {
if (predicate(item)) {
result.add(item)
}
}
return result
}
// Extension Function
fun String.removeSpaces(): String {
return this.replace(" ", "")
}
// Inline Function
inline fun <T> lock(lock: Any, body: () -> T): T {
// simulated lock
return body()
}
// Function with default args
fun join(
elements: List<String>,
separator: String = ", ",
prefix: String = "",
postfix: String = ""
): String {
return prefix + elements.joinToString(separator) + postfix
}
// Single Expression Function
fun double(x: Int): Int = x * 2
class Calculator {
// Operator overloading
operator fun plus(other: Calculator): Calculator = Calculator()
// Infix function
infix fun add(x: Int): Int {
return x + 10
}
}
fun usage() {
val list = listOf(1, 2, 3)
val filtered = list.customFilter { it > 1 }
val text = "Hello World"
println(text.removeSpaces())
val calc = Calculator()
val res = calc add 5
lock(calc) {
println("Inside lock")
}
}
```
--------------------------------------------------------------------------------
/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 };
```
--------------------------------------------------------------------------------
/tests/sample_project_csharp/src/Example.App/Program.cs:
--------------------------------------------------------------------------------
```csharp
using System;
using System.Collections.Generic;
using Example.App.Models;
using Example.App.Services;
using Example.App.Utils;
namespace Example.App
{
/// <summary>
/// Main program entry point
/// </summary>
public class Program
{
public static void Main(string[] args)
{
// Create a greeting service
IGreetingService greetingService = new GreetingService();
// Create a user
var user = new User("Alice", Role.Admin);
// Greet the user
string greeting = greetingService.Greet(user);
Console.WriteLine(greeting);
// Use collection utilities
var numbers = new List<int> { 1, 2, 3, 4, 5 };
int sumOfSquares = CollectionHelper.SumOfSquares(numbers);
Console.WriteLine($"Sum of squares: {sumOfSquares}");
// Use file helper
try
{
string firstLine = FileHelper.ReadFirstLine("README.md");
Console.WriteLine($"First line: {firstLine}");
}
catch (Exception ex)
{
Console.WriteLine($"File read failed: {ex.Message}");
}
// Demonstrate nested class
var outer = new OuterClass("outer");
var inner = outer.CreateInner("inner");
Console.WriteLine(inner.Combine());
}
}
}
```
--------------------------------------------------------------------------------
/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 SocialMentionsTimeline from "../components/SocialMentionsTimeline";
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">
<SocialMentionsTimeline />
</div>
<div data-aos="fade-up" data-aos-anchor-placement="top-bottom">
<Footer />
</div>
</main>
);
};
export default Index;
```
--------------------------------------------------------------------------------
/tests/sample_project_csharp/src/Example.App/Utils/FileHelper.cs:
--------------------------------------------------------------------------------
```csharp
using System;
using System.IO;
namespace Example.App.Utils
{
/// <summary>
/// Helper class for file I/O operations
/// </summary>
public static class FileHelper
{
/// <summary>
/// Reads the first line from a file
/// </summary>
public static string ReadFirstLine(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentException("File path cannot be null or empty", nameof(filePath));
}
if (!File.Exists(filePath))
{
throw new FileNotFoundException($"File not found: {filePath}");
}
using (var reader = new StreamReader(filePath))
{
return reader.ReadLine() ?? string.Empty;
}
}
/// <summary>
/// Writes text to a file
/// </summary>
public static void WriteToFile(string filePath, string content)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentException("File path cannot be null or empty", nameof(filePath));
}
File.WriteAllText(filePath, content);
}
/// <summary>
/// Checks if a file exists
/// </summary>
public static bool FileExists(string filePath)
{
return !string.IsNullOrEmpty(filePath) && File.Exists(filePath);
}
}
}
```
--------------------------------------------------------------------------------
/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 };
```
--------------------------------------------------------------------------------
/tests/sample_project_swift/Vehicles.swift:
--------------------------------------------------------------------------------
```swift
import Foundation
// Enum for different types of vehicles
enum VehicleType {
case car
case truck
case motorcycle
case bicycle
func description() -> String {
switch self {
case .car:
return "Four-wheeled vehicle"
case .truck:
return "Large cargo vehicle"
case .motorcycle:
return "Two-wheeled motorized vehicle"
case .bicycle:
return "Two-wheeled pedal vehicle"
}
}
}
// Enum with associated values
enum Result<T> {
case success(T)
case failure(Error)
func getValue() -> T? {
switch self {
case .success(let value):
return value
case .failure:
return nil
}
}
}
// Vehicle class
class Vehicle {
let type: VehicleType
var speed: Double
init(type: VehicleType, speed: Double = 0.0) {
self.type = type
self.speed = speed
}
func accelerate(by amount: Double) {
speed += amount
}
func brake(by amount: Double) {
speed = max(0, speed - amount)
}
func getInfo() -> String {
return "\(type.description()) traveling at \(speed) km/h"
}
}
// Car class inheriting from Vehicle
class Car: Vehicle {
let numberOfDoors: Int
init(numberOfDoors: Int, speed: Double = 0.0) {
self.numberOfDoors = numberOfDoors
super.init(type: .car, speed: speed)
}
override func getInfo() -> String {
return "\(numberOfDoors)-door car traveling at \(speed) km/h"
}
}
```
--------------------------------------------------------------------------------
/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 };
```
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
```toml
[project]
name = "codegraphcontext"
version = "0.1.32"
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.10"
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",
"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.21.0",
"tree-sitter-language-pack>=0.6.0",
"pyyaml",
"pytest",
"nbformat",
"nbconvert>=7.16.6",
"pathspec>=0.12.1",
"falkordblite>=0.1.0; sys_platform != 'win32' and python_version >= '3.12'"
]
[project.optional-dependencies]
parsing = [
"tree-sitter>=0.21.0",
"tree-sitter-language-pack>=0.6.0",
]
dev = [
"pytest>=7.4.0",
"black>=23.11.0",
"pytest-asyncio>=0.21.0",
]
[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"
[tool.setuptools]
package-dir = { "" = "src" }
[tool.setuptools.packages.find]
where = ["src"]
include = ["codegraphcontext*"]
```