This is page 3 of 14. Use http://codebase.md/shashankss1205/codegraphcontext?page={x} to view the full context.
# Directory Structure
```
├── .github
│ └── workflows
│ ├── e2e-tests.yml
│ ├── post_discord_invite.yml
│ ├── test.yml
│ └── update-contributors.yml
├── .gitignore
├── CONTRIBUTING.md
├── contributors.md
├── docs
│ ├── docs
│ │ ├── architecture.md
│ │ ├── cli.md
│ │ ├── contributing_languages.md
│ │ ├── contributing.md
│ │ ├── cookbook.md
│ │ ├── core.md
│ │ ├── future_work.md
│ │ ├── images
│ │ │ ├── 1.png
│ │ │ ├── 11.png
│ │ │ ├── 12.png
│ │ │ ├── 13.png
│ │ │ ├── 14.png
│ │ │ ├── 16.png
│ │ │ ├── 19.png
│ │ │ ├── 2.png
│ │ │ ├── 20.png
│ │ │ ├── 21.png
│ │ │ ├── 22.png
│ │ │ ├── 23.png
│ │ │ ├── 24.png
│ │ │ ├── 26.png
│ │ │ ├── 28.png
│ │ │ ├── 29.png
│ │ │ ├── 3.png
│ │ │ ├── 30.png
│ │ │ ├── 31.png
│ │ │ ├── 32.png
│ │ │ ├── 33.png
│ │ │ ├── 34.png
│ │ │ ├── 35.png
│ │ │ ├── 36.png
│ │ │ ├── 38.png
│ │ │ ├── 39.png
│ │ │ ├── 4.png
│ │ │ ├── 40.png
│ │ │ ├── 41.png
│ │ │ ├── 42.png
│ │ │ ├── 43.png
│ │ │ ├── 44.png
│ │ │ ├── 5.png
│ │ │ ├── 6.png
│ │ │ ├── 7.png
│ │ │ ├── 8.png
│ │ │ ├── 9.png
│ │ │ ├── Indexing.gif
│ │ │ ├── tool_images
│ │ │ │ ├── 1.png
│ │ │ │ ├── 2.png
│ │ │ │ └── 3.png
│ │ │ └── Usecase.gif
│ │ ├── index.md
│ │ ├── installation.md
│ │ ├── license.md
│ │ ├── server.md
│ │ ├── tools.md
│ │ ├── troubleshooting.md
│ │ └── use_cases.md
│ ├── mkdocs.yml
│ └── site
│ ├── 404.html
│ ├── architecture
│ │ └── index.html
│ ├── assets
│ │ ├── images
│ │ │ └── favicon.png
│ │ ├── javascripts
│ │ │ ├── bundle.f55a23d4.min.js
│ │ │ ├── bundle.f55a23d4.min.js.map
│ │ │ ├── lunr
│ │ │ │ ├── min
│ │ │ │ │ ├── lunr.ar.min.js
│ │ │ │ │ ├── lunr.da.min.js
│ │ │ │ │ ├── lunr.de.min.js
│ │ │ │ │ ├── lunr.du.min.js
│ │ │ │ │ ├── lunr.el.min.js
│ │ │ │ │ ├── lunr.es.min.js
│ │ │ │ │ ├── lunr.fi.min.js
│ │ │ │ │ ├── lunr.fr.min.js
│ │ │ │ │ ├── lunr.he.min.js
│ │ │ │ │ ├── lunr.hi.min.js
│ │ │ │ │ ├── lunr.hu.min.js
│ │ │ │ │ ├── lunr.hy.min.js
│ │ │ │ │ ├── lunr.it.min.js
│ │ │ │ │ ├── lunr.ja.min.js
│ │ │ │ │ ├── lunr.jp.min.js
│ │ │ │ │ ├── lunr.kn.min.js
│ │ │ │ │ ├── lunr.ko.min.js
│ │ │ │ │ ├── lunr.multi.min.js
│ │ │ │ │ ├── lunr.nl.min.js
│ │ │ │ │ ├── lunr.no.min.js
│ │ │ │ │ ├── lunr.pt.min.js
│ │ │ │ │ ├── lunr.ro.min.js
│ │ │ │ │ ├── lunr.ru.min.js
│ │ │ │ │ ├── lunr.sa.min.js
│ │ │ │ │ ├── lunr.stemmer.support.min.js
│ │ │ │ │ ├── lunr.sv.min.js
│ │ │ │ │ ├── lunr.ta.min.js
│ │ │ │ │ ├── lunr.te.min.js
│ │ │ │ │ ├── lunr.th.min.js
│ │ │ │ │ ├── lunr.tr.min.js
│ │ │ │ │ ├── lunr.vi.min.js
│ │ │ │ │ └── lunr.zh.min.js
│ │ │ │ ├── tinyseg.js
│ │ │ │ └── wordcut.js
│ │ │ └── workers
│ │ │ ├── search.973d3a69.min.js
│ │ │ └── search.973d3a69.min.js.map
│ │ └── stylesheets
│ │ ├── main.2a3383ac.min.css
│ │ ├── main.2a3383ac.min.css.map
│ │ ├── palette.06af60db.min.css
│ │ └── palette.06af60db.min.css.map
│ ├── cli
│ │ └── index.html
│ ├── contributing
│ │ └── index.html
│ ├── contributing_languages
│ │ └── index.html
│ ├── cookbook
│ │ └── index.html
│ ├── core
│ │ └── index.html
│ ├── future_work
│ │ └── index.html
│ ├── images
│ │ ├── 1.png
│ │ ├── 11.png
│ │ ├── 12.png
│ │ ├── 13.png
│ │ ├── 14.png
│ │ ├── 16.png
│ │ ├── 19.png
│ │ ├── 2.png
│ │ ├── 20.png
│ │ ├── 21.png
│ │ ├── 22.png
│ │ ├── 23.png
│ │ ├── 24.png
│ │ ├── 26.png
│ │ ├── 28.png
│ │ ├── 29.png
│ │ ├── 3.png
│ │ ├── 30.png
│ │ ├── 31.png
│ │ ├── 32.png
│ │ ├── 33.png
│ │ ├── 34.png
│ │ ├── 35.png
│ │ ├── 36.png
│ │ ├── 38.png
│ │ ├── 39.png
│ │ ├── 4.png
│ │ ├── 40.png
│ │ ├── 41.png
│ │ ├── 42.png
│ │ ├── 43.png
│ │ ├── 44.png
│ │ ├── 5.png
│ │ ├── 6.png
│ │ ├── 7.png
│ │ ├── 8.png
│ │ ├── 9.png
│ │ ├── Indexing.gif
│ │ ├── tool_images
│ │ │ ├── 1.png
│ │ │ ├── 2.png
│ │ │ └── 3.png
│ │ └── Usecase.gif
│ ├── index.html
│ ├── installation
│ │ └── index.html
│ ├── license
│ │ └── index.html
│ ├── search
│ │ └── search_index.json
│ ├── server
│ │ └── index.html
│ ├── sitemap.xml
│ ├── sitemap.xml.gz
│ ├── tools
│ │ └── index.html
│ ├── troubleshooting
│ │ └── index.html
│ └── use_cases
│ └── index.html
├── images
│ ├── 1.png
│ ├── 11.png
│ ├── 12.png
│ ├── 13.png
│ ├── 14.png
│ ├── 16.png
│ ├── 19.png
│ ├── 2.png
│ ├── 20.png
│ ├── 21.png
│ ├── 22.png
│ ├── 23.png
│ ├── 24.png
│ ├── 26.png
│ ├── 28.png
│ ├── 29.png
│ ├── 3.png
│ ├── 30.png
│ ├── 31.png
│ ├── 32.png
│ ├── 33.png
│ ├── 34.png
│ ├── 35.png
│ ├── 36.png
│ ├── 38.png
│ ├── 39.png
│ ├── 4.png
│ ├── 40.png
│ ├── 41.png
│ ├── 42.png
│ ├── 43.png
│ ├── 44.png
│ ├── 5.png
│ ├── 6.png
│ ├── 7.png
│ ├── 8.png
│ ├── 9.png
│ ├── Indexing.gif
│ ├── tool_images
│ │ ├── 1.png
│ │ ├── 2.png
│ │ └── 3.png
│ └── Usecase.gif
├── LICENSE
├── MANIFEST.in
├── organizer
│ ├── CONTRIBUTING_LANGUAGES.md
│ ├── cookbook.md
│ ├── docs.md
│ ├── language_specific_nodes.md
│ ├── Tools_Exploration.md
│ └── troubleshoot.md
├── package-lock.json
├── pyproject.toml
├── README.md
├── scripts
│ ├── generate_lang_contributors.py
│ └── post_install_fix.sh
├── SECURITY.md
├── src
│ └── codegraphcontext
│ ├── __init__.py
│ ├── __main__.py
│ ├── cli
│ │ ├── __init__.py
│ │ ├── cli_helpers.py
│ │ ├── main.py
│ │ ├── setup_macos.py
│ │ └── setup_wizard.py
│ ├── core
│ │ ├── __init__.py
│ │ ├── database.py
│ │ ├── jobs.py
│ │ └── watcher.py
│ ├── prompts.py
│ ├── server.py
│ ├── tools
│ │ ├── __init__.py
│ │ ├── advanced_language_query_tool.py
│ │ ├── code_finder.py
│ │ ├── graph_builder.py
│ │ ├── languages
│ │ │ ├── c.py
│ │ │ ├── cpp.py
│ │ │ ├── go.py
│ │ │ ├── java.py
│ │ │ ├── javascript.py
│ │ │ ├── python.py
│ │ │ ├── ruby.py
│ │ │ ├── rust.py
│ │ │ └── typescript.py
│ │ ├── package_resolver.py
│ │ ├── query_tool_languages
│ │ │ ├── c_toolkit.py
│ │ │ ├── cpp_toolkit.py
│ │ │ ├── go_toolkit.py
│ │ │ ├── java_toolkit.py
│ │ │ ├── javascript_toolkit.py
│ │ │ ├── python_toolkit.py
│ │ │ ├── ruby_toolkit.py
│ │ │ ├── rust_toolkit.py
│ │ │ └── typescript_toolkit.py
│ │ └── system.py
│ └── utils
│ └── debug_log.py
├── tests
│ ├── __init__.py
│ ├── conftest.py
│ ├── sample_project
│ │ ├── advanced_calls.py
│ │ ├── advanced_classes.py
│ │ ├── advanced_classes2.py
│ │ ├── advanced_functions.py
│ │ ├── advanced_imports.py
│ │ ├── async_features.py
│ │ ├── callbacks_decorators.py
│ │ ├── circular1.py
│ │ ├── circular2.py
│ │ ├── class_instantiation.py
│ │ ├── cli_and_dunder.py
│ │ ├── complex_classes.py
│ │ ├── comprehensions_generators.py
│ │ ├── context_managers.py
│ │ ├── control_flow.py
│ │ ├── datatypes.py
│ │ ├── dynamic_dispatch.py
│ │ ├── dynamic_imports.py
│ │ ├── edge_cases
│ │ │ ├── comments_only.py
│ │ │ ├── docstring_only.py
│ │ │ ├── empty.py
│ │ │ ├── hardcoded_secrets.py
│ │ │ ├── long_functions.py
│ │ │ └── syntax_error.py
│ │ ├── function_chains.py
│ │ ├── generators.py
│ │ ├── import_reexports.py
│ │ ├── mapping_calls.py
│ │ ├── module_a.py
│ │ ├── module_b.py
│ │ ├── module_c
│ │ │ ├── __init__.py
│ │ │ ├── submodule1.py
│ │ │ └── submodule2.py
│ │ ├── namespace_pkg
│ │ │ └── ns_module.py
│ │ ├── pattern_matching.py
│ │ └── typing_examples.py
│ ├── sample_project_c
│ │ ├── cgc_sample
│ │ ├── include
│ │ │ ├── config.h
│ │ │ ├── math
│ │ │ │ └── vec.h
│ │ │ ├── module.h
│ │ │ ├── platform.h
│ │ │ └── util.h
│ │ ├── Makefile
│ │ ├── README.md
│ │ └── src
│ │ ├── main.c
│ │ ├── math
│ │ │ └── vec.c
│ │ ├── module.c
│ │ └── util.c
│ ├── sample_project_cpp
│ │ ├── class_features.cpp
│ │ ├── classes.cpp
│ │ ├── control_flow.cpp
│ │ ├── edge_cases.cpp
│ │ ├── enum_struct_union.cpp
│ │ ├── exceptions.cpp
│ │ ├── file_io.cpp
│ │ ├── function_chain.cpp
│ │ ├── function_chain.h
│ │ ├── function_types.cpp
│ │ ├── main.cpp
│ │ ├── main.exe
│ │ ├── namespaces.cpp
│ │ ├── raii_example.cpp
│ │ ├── README.md
│ │ ├── sample_project.exe
│ │ ├── stl_usage.cpp
│ │ ├── templates.cpp
│ │ └── types_variable_assignments.cpp
│ ├── sample_project_go
│ │ ├── advanced_types.go
│ │ ├── basic_functions.go
│ │ ├── embedded_composition.go
│ │ ├── error_handling.go
│ │ ├── generics.go
│ │ ├── go.mod
│ │ ├── goroutines_channels.go
│ │ ├── interfaces.go
│ │ ├── packages_imports.go
│ │ ├── README.md
│ │ ├── structs_methods.go
│ │ └── util
│ │ └── helpers.go
│ ├── sample_project_java
│ │ ├── out
│ │ │ └── com
│ │ │ └── example
│ │ │ └── app
│ │ │ ├── annotations
│ │ │ │ └── Logged.class
│ │ │ ├── Main.class
│ │ │ ├── misc
│ │ │ │ ├── Outer.class
│ │ │ │ └── Outer$Inner.class
│ │ │ ├── model
│ │ │ │ ├── Role.class
│ │ │ │ └── User.class
│ │ │ ├── service
│ │ │ │ ├── AbstractGreeter.class
│ │ │ │ ├── GreetingService.class
│ │ │ │ └── impl
│ │ │ │ └── GreetingServiceImpl.class
│ │ │ └── util
│ │ │ ├── CollectionUtils.class
│ │ │ └── IOHelper.class
│ │ ├── README.md
│ │ ├── sources.txt
│ │ └── src
│ │ └── com
│ │ └── example
│ │ └── app
│ │ ├── annotations
│ │ │ └── Logged.java
│ │ ├── Main.java
│ │ ├── misc
│ │ │ └── Outer.java
│ │ ├── model
│ │ │ ├── Role.java
│ │ │ └── User.java
│ │ ├── service
│ │ │ ├── AbstractGreeter.java
│ │ │ ├── GreetingService.java
│ │ │ └── impl
│ │ │ └── GreetingServiceImpl.java
│ │ └── util
│ │ ├── CollectionUtils.java
│ │ └── IOHelper.java
│ ├── sample_project_javascript
│ │ ├── arrays.js
│ │ ├── asyncAwait.js
│ │ ├── classes.js
│ │ ├── dom.js
│ │ ├── errorHandling.js
│ │ ├── events.js
│ │ ├── exporter.js
│ │ ├── fetchAPI.js
│ │ ├── fixtures
│ │ │ └── js
│ │ │ └── accessors.js
│ │ ├── functions.js
│ │ ├── importer.js
│ │ ├── objects.js
│ │ ├── promises.js
│ │ ├── README.md
│ │ └── variables.js
│ ├── sample_project_misc
│ │ ├── index.html
│ │ ├── README.md
│ │ ├── styles.css
│ │ ├── tables.css
│ │ └── tables.html
│ ├── sample_project_php
│ │ ├── classes_objects.php
│ │ ├── database.php
│ │ ├── edgecases.php
│ │ ├── error_handling.php
│ │ ├── file_handling.php
│ │ ├── functions.php
│ │ ├── generators_iterators.php
│ │ ├── globals_superglobals.php
│ │ ├── Inheritance.php
│ │ ├── interface_traits.php
│ │ └── README.md
│ ├── sample_project_ruby
│ │ ├── class_example.rb
│ │ ├── enumerables.rb
│ │ ├── error_handling.rb
│ │ ├── file_io.rb
│ │ ├── inheritance_example.rb
│ │ ├── main.rb
│ │ ├── metaprogramming.rb
│ │ ├── mixins_example.rb
│ │ ├── module_example.rb
│ │ └── tests
│ │ ├── test_mixins.py
│ │ └── test_sample.rb
│ ├── sample_project_rust
│ │ ├── Cargo.toml
│ │ ├── README.md
│ │ └── src
│ │ ├── basic_functions.rs
│ │ ├── concurrency.rs
│ │ ├── error_handling.rs
│ │ ├── generics.rs
│ │ ├── iterators_closures.rs
│ │ ├── lib.rs
│ │ ├── lifetimes_references.rs
│ │ ├── modules.rs
│ │ ├── smart_pointers.rs
│ │ ├── structs_enums.rs
│ │ └── traits.rs
│ ├── sample_project_typescript
│ │ ├── package.json
│ │ ├── README.md
│ │ ├── src
│ │ │ ├── advanced-types.ts
│ │ │ ├── async-promises.ts
│ │ │ ├── classes-inheritance.ts
│ │ │ ├── decorators-metadata.ts
│ │ │ ├── error-validation.ts
│ │ │ ├── functions-generics.ts
│ │ │ ├── index.ts
│ │ │ ├── modules-namespaces.ts
│ │ │ ├── types-interfaces.ts
│ │ │ └── utilities-helpers.ts
│ │ └── tsconfig.json
│ ├── test_cpp_parser.py
│ ├── test_database_validation.py
│ ├── test_end_to_end.py
│ ├── test_graph_indexing_js.py
│ ├── test_graph_indexing.py
│ ├── test_tree_sitter
│ │ ├── __init__.py
│ │ ├── class_instantiation.py
│ │ ├── complex_classes.py
│ │ └── test_file.py
│ └── test_typescript_parser.py
└── website
├── .example.env
├── .gitignore
├── api
│ └── pypi.ts
├── bun.lockb
├── components.json
├── eslint.config.js
├── index.html
├── package-lock.json
├── package.json
├── postcss.config.js
├── public
│ ├── favicon.ico
│ ├── placeholder.svg
│ └── robots.txt
├── README.md
├── src
│ ├── App.css
│ ├── App.tsx
│ ├── assets
│ │ ├── function-calls.png
│ │ ├── graph-total.png
│ │ ├── hero-graph.jpg
│ │ └── hierarchy.png
│ ├── components
│ │ ├── ComparisonTable.tsx
│ │ ├── CookbookSection.tsx
│ │ ├── DemoSection.tsx
│ │ ├── ExamplesSection.tsx
│ │ ├── FeaturesSection.tsx
│ │ ├── Footer.tsx
│ │ ├── HeroSection.tsx
│ │ ├── InstallationSection.tsx
│ │ ├── MoveToTop.tsx
│ │ ├── ShowDownloads.tsx
│ │ ├── ShowStarGraph.tsx
│ │ ├── TestimonialSection.tsx
│ │ ├── ThemeProvider.tsx
│ │ ├── ThemeToggle.tsx
│ │ └── ui
│ │ ├── accordion.tsx
│ │ ├── alert-dialog.tsx
│ │ ├── alert.tsx
│ │ ├── aspect-ratio.tsx
│ │ ├── avatar.tsx
│ │ ├── badge.tsx
│ │ ├── breadcrumb.tsx
│ │ ├── button.tsx
│ │ ├── calendar.tsx
│ │ ├── card.tsx
│ │ ├── carousel.tsx
│ │ ├── chart.tsx
│ │ ├── checkbox.tsx
│ │ ├── collapsible.tsx
│ │ ├── command.tsx
│ │ ├── context-menu.tsx
│ │ ├── dialog.tsx
│ │ ├── drawer.tsx
│ │ ├── dropdown-menu.tsx
│ │ ├── form.tsx
│ │ ├── hover-card.tsx
│ │ ├── input-otp.tsx
│ │ ├── input.tsx
│ │ ├── label.tsx
│ │ ├── menubar.tsx
│ │ ├── navigation-menu.tsx
│ │ ├── orbiting-circles.tsx
│ │ ├── pagination.tsx
│ │ ├── popover.tsx
│ │ ├── progress.tsx
│ │ ├── radio-group.tsx
│ │ ├── resizable.tsx
│ │ ├── scroll-area.tsx
│ │ ├── select.tsx
│ │ ├── separator.tsx
│ │ ├── sheet.tsx
│ │ ├── sidebar.tsx
│ │ ├── skeleton.tsx
│ │ ├── slider.tsx
│ │ ├── sonner.tsx
│ │ ├── switch.tsx
│ │ ├── table.tsx
│ │ ├── tabs.tsx
│ │ ├── textarea.tsx
│ │ ├── toast.tsx
│ │ ├── toaster.tsx
│ │ ├── toggle-group.tsx
│ │ ├── toggle.tsx
│ │ ├── tooltip.tsx
│ │ └── use-toast.ts
│ ├── hooks
│ │ ├── use-mobile.tsx
│ │ └── use-toast.ts
│ ├── index.css
│ ├── lib
│ │ └── utils.ts
│ ├── main.tsx
│ ├── pages
│ │ ├── Index.tsx
│ │ └── NotFound.tsx
│ └── vite-env.d.ts
├── tailwind.config.ts
├── tsconfig.app.json
├── tsconfig.json
├── tsconfig.node.json
├── vercel.json
└── vite.config.ts
```
# Files
--------------------------------------------------------------------------------
/website/src/components/InstallationSection.tsx:
--------------------------------------------------------------------------------
```typescript
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Copy, Terminal, Play, Settings } from "lucide-react";
import { toast } from "sonner";
import ShowStarGraph from "@/components/ShowStarGraph";
const installSteps = [
{
step: "1",
title: "Install",
command: "pip install codegraphcontext",
description: "Install CodeGraphContext using pip."
},
{
step: "2",
title: "Setup",
command: "cgc setup",
description: "Interactive wizard to configure your Neo4j database."
},
{
step: "3",
title: "Start",
command: "cgc start",
description: "Launch the MCP server and begin indexing."
}
];
const setupOptions = [
{ icon: Terminal, title: "Docker (Recommended)", description: "Automated Neo4j setup using Docker containers.", color: "graph-node-1" },
{ icon: Play, title: "Linux Binary", description: "Direct installation on Debian-based systems.", color: "graph-node-2" },
{ icon: Settings, title: "Hosted Database", description: "Connect to Neo4j AuraDB or an existing instance.", color: "graph-node-3" }
];
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
toast.success("Copied to clipboard!");
};
const InstallationSection = () => {
return (
<>
<ShowStarGraph />
<section className="py-24 px-4 bg-muted/20" data-aos="fade-in">
<div className="container mx-auto max-w-5xl">
<div className="text-center mb-16" data-aos="fade-down">
<h2 className="text-4xl md:text-5xl font-bold mb-6 bg-gradient-to-r from-primary via-primary to-accent bg-clip-text text-transparent">
Get Started in Minutes
</h2>
<p className="text-xl text-muted-foreground">
Simple installation with automated setup for your database configuration.
</p>
</div>
<div className="grid gap-6 mb-12">
{installSteps.map((step, index) => (
<div key={index} data-aos="fade-up" data-aos-delay={index * 100}>
<Card className="transition-shadow duration-300 hover:shadow-lg bg-white/95 dark:bg-card/50">
<CardHeader className="pb-4">
<div className="flex items-center gap-4">
<Badge variant="secondary" className="text-lg font-bold w-9 h-9 flex items-center justify-center rounded-full bg-primary/10 text-primary">
{step.step}
</Badge>
<div>
<CardTitle className="text-xl">{step.title}</CardTitle>
<CardDescription>{step.description}</CardDescription>
</div>
</div>
</CardHeader>
<CardContent>
<div className="p-3 rounded-md bg-muted/40 flex items-center justify-between group border shadow-inner">
<code className="text-accent font-mono text-sm">$ {step.command}</code>
<Button variant="ghost" size="icon" onClick={() => copyToClipboard(step.command)} className="opacity-0 group-hover:opacity-100 transition-opacity h-8 w-8">
<Copy className="h-4 w-4" />
</Button>
</div>
</CardContent>
</Card>
</div>
))}
</div>
<div data-aos="fade-up" data-aos-delay="300">
<Card className="bg-white/95 dark:bg-card/50">
<CardHeader>
<CardTitle className="flex items-center gap-3"><Settings className="h-6 w-6 text-primary" />Setup Options</CardTitle>
<CardDescription>The setup wizard supports multiple Neo4j configurations.</CardDescription>
</CardHeader>
<CardContent>
<div className="grid md:grid-cols-3 gap-6">
{setupOptions.map((option, index) => (
<div key={index} className="text-center p-4 rounded-lg bg-muted/30">
<div className={`w-12 h-12 bg-${option.color}/10 rounded-lg flex items-center justify-center mx-auto mb-3`}>
<option.icon className={`h-6 w-6 text-${option.color}`} />
</div>
<h4 className="font-semibold mb-2">{option.title}</h4>
<p className="text-sm text-muted-foreground">{option.description}</p>
</div>
))}
</div>
</CardContent>
</Card>
</div>
</div>
</section>
</>
);
};
export default InstallationSection;
```
--------------------------------------------------------------------------------
/scripts/generate_lang_contributors.py:
--------------------------------------------------------------------------------
```python
import subprocess
import os
from collections import defaultdict
# Get the absolute path of the script's directory, then go up to the project root.
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
# Define files to track per language. Paths are relative to the project root.
files_by_lang = {
"c": ["src/codegraphcontext/tools/languages/c.py"],
"cpp": ["src/codegraphcontext/tools/languages/cpp.py"],
"go": ["src/codegraphcontext/tools/languages/go.py"],
"java": ["src/codegraphcontext/tools/languages/java.py"],
"javascript": ["src/codegraphcontext/tools/languages/javascript.py"],
"python": ["src/codegraphcontext/tools/languages/python.py"],
"ruby": ["src/codegraphcontext/tools/languages/ruby.py"],
"rust": ["src/codegraphcontext/tools/languages/rust.py"],
"typescript": ["src/codegraphcontext/tools/languages/typescript.py"],
}
def get_contributor_stats(files):
"""
Returns a dictionary of contributors with commit count, lines added, and lines deleted.
This is done by parsing the output of 'git log'.
"""
data = defaultdict(lambda: {"commits": 0, "added": 0, "deleted": 0, "email": ""})
try:
# Use 'git log' with '--numstat' to get file changes, author name, and email in one go.
log_output = subprocess.check_output(
["git", "log", "--no-merges", "--numstat", "--pretty=format:---%n%an%n%ae", "--"] + files,
text=True,
cwd=PROJECT_ROOT
).strip()
except subprocess.CalledProcessError as e:
print(f"Error fetching git log for files {files}: {e}")
return data
if not log_output:
return data
commits = log_output.split('---')[1:]
for commit in commits:
lines = commit.strip().split('\n')
author = lines[0].strip()
email = lines[1].strip()
if not author:
continue
data[author]["commits"] += 1
data[author]["email"] = email
for line in lines[2:]:
if not line.strip():
continue
parts = line.split("\t")
if len(parts) >= 3:
added, deleted, _ = parts
added = int(added) if added != "-" else 0
deleted = int(deleted) if deleted != "-" else 0
data[author]["added"] += added
data[author]["deleted"] += deleted
return data
def get_username_from_email(email):
if email.endswith('@users.noreply.github.com'):
return email.split('+')[1].split('@')[0]
return None
def get_repo_url():
try:
url = subprocess.check_output(
["git", "remote", "get-url", "origin"],
text=True,
cwd=PROJECT_ROOT
).strip()
if url.endswith(".git"):
url = url[:-4]
if url.startswith("[email protected]:"):
url = url.replace("[email protected]:", "https://github.com/")
return url
except Exception:
return None
def generate_markdown_table(lang, stats, repo_url, files):
"""
Generates a Markdown table for contributors
"""
table = f"## {lang.capitalize()} Contributors\n\n"
table += "| Rank | Contributor | Commits | Lines Added | Lines Deleted | Link to Contributions |\n"
table += "|---|---|---|---|---|---|\n"
for rank, (author, vals) in enumerate(sorted(stats.items(), key=lambda x: (x[1]["commits"], x[1]["added"]), reverse=True), 1):
email = vals["email"]
username = get_username_from_email(email)
if username:
profile_str = f"[{author}](https://github.com/{username})"
author_for_link = username
else:
profile_str = author
author_for_link = email
contribution_links = []
for file_path in files:
file_name = os.path.basename(file_path)
link = f"[{file_name}]({repo_url}/commits/main/{file_path}?author={author_for_link})"
contribution_links.append(link)
links_str = ", ".join(contribution_links)
table += f"| {rank} | {profile_str} | {vals['commits']} | {vals['added']} | {vals['deleted']} | {links_str} |\n"
return table
def main():
repo_url = get_repo_url()
if not repo_url:
print("Could not determine repository URL. Contribution links will not be generated.")
output_file = os.path.join(PROJECT_ROOT, "contributors.md")
with open(output_file, "w") as f:
f.write("# Language Contributors\n\n")
f.write("This file is auto-generated. Do not edit manually.\n\n")
for lang, files in files_by_lang.items():
stats = get_contributor_stats(files)
if stats:
table = generate_markdown_table(lang, stats, repo_url, files)
f.write(table + "\n\n")
print(f"Contributor stats generated in {output_file}")
if __name__ == "__main__":
main()
```
--------------------------------------------------------------------------------
/website/src/components/ui/navigation-menu.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu";
import { cva } from "class-variance-authority";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Root
ref={ref}
className={cn("relative z-10 flex max-w-max flex-1 items-center justify-center", className)}
{...props}
>
{children}
<NavigationMenuViewport />
</NavigationMenuPrimitive.Root>
));
NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName;
const NavigationMenuList = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.List>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.List
ref={ref}
className={cn("group flex flex-1 list-none items-center justify-center space-x-1", className)}
{...props}
/>
));
NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName;
const NavigationMenuItem = NavigationMenuPrimitive.Item;
const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50",
);
const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Trigger
ref={ref}
className={cn(navigationMenuTriggerStyle(), "group", className)}
{...props}
>
{children}{" "}
<ChevronDown
className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
));
NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName;
const NavigationMenuContent = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Content
ref={ref}
className={cn(
"left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto",
className,
)}
{...props}
/>
));
NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName;
const NavigationMenuLink = NavigationMenuPrimitive.Link;
const NavigationMenuViewport = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
>(({ className, ...props }, ref) => (
<div className={cn("absolute left-0 top-full flex justify-center")}>
<NavigationMenuPrimitive.Viewport
className={cn(
"origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",
className,
)}
ref={ref}
{...props}
/>
</div>
));
NavigationMenuViewport.displayName = NavigationMenuPrimitive.Viewport.displayName;
const NavigationMenuIndicator = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Indicator
ref={ref}
className={cn(
"top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",
className,
)}
{...props}
>
<div className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
</NavigationMenuPrimitive.Indicator>
));
NavigationMenuIndicator.displayName = NavigationMenuPrimitive.Indicator.displayName;
export {
navigationMenuTriggerStyle,
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
};
```
--------------------------------------------------------------------------------
/tests/sample_project_typescript/src/types-interfaces.ts:
--------------------------------------------------------------------------------
```typescript
/**
* Basic Types and Interfaces
* Demonstrates TypeScript's core type system including primitives,
* interfaces, type aliases, unions, intersections, and advanced type patterns
*/
// ========== Primitive Types ==========
export const stringValue: string = "Hello TypeScript";
export const numberValue: number = 42;
export const booleanValue: boolean = true;
export const nullValue: null = null;
export const undefinedValue: undefined = undefined;
export const symbolValue: symbol = Symbol("unique");
export const bigintValue: bigint = 100n;
// ========== Array and Tuple Types ==========
export const numberArray: number[] = [1, 2, 3, 4];
export const stringArray: Array<string> = ["a", "b", "c"];
export const mixedTuple: [string, number, boolean] = ["hello", 42, true];
export const namedTuple: [name: string, age: number] = ["Alice", 30];
// ========== Object Types ==========
export const basicObject: { name: string; age: number } = {
name: "John",
age: 25
};
// ========== Interface Definitions ==========
export interface User {
readonly id: number;
name: string;
email?: string; // Optional property
readonly createdAt: Date;
preferences: UserPreferences;
}
export interface UserPreferences {
theme: "light" | "dark";
notifications: boolean;
language: string;
}
// Interface inheritance
export interface AdminUser extends User {
permissions: string[];
lastLogin?: Date;
}
// Interface with index signature
export interface Dictionary<T = any> {
[key: string]: T;
}
// Interface with call signature
export interface StringProcessor {
(input: string): string;
description: string;
}
// Interface with construct signature
export interface Constructable {
new (name: string): { name: string };
}
// ========== Type Aliases ==========
export type Status = "pending" | "approved" | "rejected";
export type ID = string | number;
export type EventHandler<T> = (event: T) => void;
// Generic type alias
export type Response<T> = {
data: T;
error: string | null;
timestamp: Date;
};
// Mapped type alias
export type Optional<T> = {
[K in keyof T]?: T[K];
};
// ========== Union Types ==========
export type StringOrNumber = string | number;
export type Theme = "light" | "dark" | "auto";
export function formatValue(value: StringOrNumber): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toString();
}
// Discriminated union
export type Shape =
| { kind: "circle"; radius: number }
| { kind: "rectangle"; width: number; height: number }
| { kind: "triangle"; base: number; height: number };
export function calculateArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rectangle":
return shape.width * shape.height;
case "triangle":
return (shape.base * shape.height) / 2;
default:
const _exhaustive: never = shape;
throw new Error(`Unhandled shape: ${_exhaustive}`);
}
}
// ========== Intersection Types ==========
export type PersonalInfo = {
name: string;
age: number;
};
export type ContactInfo = {
email: string;
phone: string;
};
export type Employee = PersonalInfo & ContactInfo & {
employeeId: string;
department: string;
};
// ========== Conditional Types ==========
export type NonNullable<T> = T extends null | undefined ? never : T;
export type ArrayElement<T> = T extends (infer U)[] ? U : never;
// ========== Template Literal Types ==========
export type EventName<T extends string> = `on${Capitalize<T>}`;
export type CSSProperty = `--${string}`;
// ========== Utility Types Usage ==========
export type PartialUser = Partial<User>;
export type RequiredUser = Required<User>;
export type UserEmail = Pick<User, "email">;
export type UserWithoutId = Omit<User, "id">;
export type UserKeys = keyof User;
export type UserValues = User[keyof User];
// ========== Complex Type Examples ==========
export interface GenericRepository<T, K extends keyof T> {
findById(id: T[K]): Promise<T | null>;
findAll(): Promise<T[]>;
create(entity: Omit<T, K>): Promise<T>;
update(id: T[K], updates: Partial<T>): Promise<T>;
delete(id: T[K]): Promise<void>;
}
// Recursive type
export interface TreeNode<T> {
value: T;
children: TreeNode<T>[];
parent?: TreeNode<T>;
}
// Function type with overloads
export interface Logger {
(message: string): void;
(level: "info" | "warn" | "error", message: string): void;
(level: "info" | "warn" | "error", message: string, data: any): void;
}
// ========== Implementation Examples ==========
const user: User = {
id: 1,
name: "Alice Johnson",
email: "[email protected]",
createdAt: new Date(),
preferences: {
theme: "dark",
notifications: true,
language: "en"
}
};
const adminUser: AdminUser = {
...user,
permissions: ["read", "write", "delete"],
lastLogin: new Date()
};
const shapes: Shape[] = [
{ kind: "circle", radius: 5 },
{ kind: "rectangle", width: 10, height: 6 },
{ kind: "triangle", base: 8, height: 4 }
];
export const typeExamples = {
user,
adminUser,
shapes,
areas: shapes.map(calculateArea)
};
```
--------------------------------------------------------------------------------
/src/codegraphcontext/prompts.py:
--------------------------------------------------------------------------------
```python
# src/codegraphcontext/prompts.py
"""
This file contains the system prompt for the language model.
This prompt provides the core instructions, principles, and standard operating
procedures for the AI assistant, guiding it on how to effectively use the tools
provided by this MCP server.
"""
LLM_SYSTEM_PROMPT = """# AI Pair Programmer Instructions
## 1. Your Role and Goal
You are an expert AI pair programmer. Your primary goal is to help a developer understand, write, and refactor code within their **local project**. Your defining feature is your connection to a local Model Context Protocol (MCP) server, which gives you real-time, accurate information about the codebase.
**Always prioritize using this MCP tools when they can simplify or enhance your workflow compared to guessing.**
## 2. Your Core Principles
### Principle I: Ground Your Answers in Fact
**Your CORE DIRECTIVE is to use the provided tools to gather facts from the MCP server *before* answering questions or generating code.** Do not guess. Your value comes from providing contextually-aware, accurate assistance.
### Principle II: Be an Agent, Not Just a Planner
**Your goal is to complete the user's task in the fewest steps possible.**
* If the user's request maps directly to a single tool, **execute that tool immediately.**
* Do not create a multi-step plan for a one-step task. The Standard Operating Procedures (SOPs) below are for complex queries that require reasoning and combining information from multiple tools.
**Example of what NOT to do:**
> **User:** "Start watching the `my-project` folder."
> **Incorrect Plan:**
> 1. Check if `watchdog` is installed.
> 2. Use the `watch_directory` tool on `my-project`.
> 3. Update a todo list.
**Example of the CORRECT, direct action:**
> **User:** "Start watching the `my-project` folder."
> **Correct Action:** Immediately call the `watch_directory` tool.
> ```json
> {
> "tool_name": "watch_directory",
> "arguments": { "path": "my-project" }
> }
> ```
## 3. Tool Manifest & Usage
| Tool Name | Purpose & When to Use |
| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ |
| **`find_code`** | **Your primary search tool.** Use this first for almost any query about locating code. t |
| **`analyze_code_relationships`** | **Your deep analysis tool.** Use this after locating a specific item. Use query types like `find_callers` or `find_callees`. |
| **`add_code_to_graph`** | **Your indexing tool.** Use this when the user wants to add a new project folder or file to the context. |
| **`add_package_to_graph`** | **Your dependency indexing tool.** Use this to add a `pip` package to the context. |
| **`list_jobs`** & **`check_job_status`** | **Your job monitoring tools.** |
| **`watch_directory`** | **Your live-update tool.** Use this if the user wants to automatically keep the context updated as they work. |
| **`execute_cypher_query`** | **Expert Fallback Tool.** Use this *only* when other tools cannot answer a very specific or complex question about the code graph. Requires knowledge of Cypher. |
## 4. Standard Operating Procedures (SOPs) for Complex Tasks
**Note:** Follow these methodical workflows for **complex requests** that require multiple steps of reasoning or combining information from several tools. For direct commands, refer to Principle II and act immediately.
### SOP-1: Answering "Where is...?" or "How does...?" Questions
1. **Locate:** Use `find_code` to find the relevant code.
2. **Analyze:** Use `analyze_code_relationships` to understand its usage.
3. **Synthesize:** Combine the information into a clear explanation.
### SOP-2: Generating New Code
1. **Find Context:** Use `find_code` to find similar, existing code to match the style.
2. **Find Reusable Code:** Use `find_code` to locate specific helper functions the user wants you to use.
3. **Generate:** Write the code using the correct imports and signatures.
### SOP-3: Refactoring or Analyzing Impact
1. **Identify & Locate:** Use `find_code` to get the canonical path of the item to be changed.
2. **Assess Impact:** Use `analyze_code_relationships` with the `find_callers` query type to find all affected locations.
3. **Report Findings:** Present a clear list of all affected files.
### SOP-4: Using the Cypher Fallback
1. **Attempt Standard Tools:** First, always try to use `find_code` and `analyze_code_relationships`.
2. **Identify Failure:** If the standard tools cannot answer a complex, multi-step relationship query (e.g., "Find all functions that are called by a method in a class that inherits from 'BaseHandler'"), then and only then, resort to the fallback.
3. **Formulate & Execute:** Construct a Cypher query to find the answer and execute it using `execute_cypher_query`.
4. **Present Results:** Explain the results to the user based on the query output.
"""
```
--------------------------------------------------------------------------------
/tests/test_cpp_parser.py:
--------------------------------------------------------------------------------
```python
"""
Test script for the enhanced C++ parser.
"""
import json
import sys
from pathlib import Path
def test_parser():
"""Test the C++ parser with a sample file."""
test_cpp_code = '''
class TestClass : public BaseClass {
private:
int privateVar;
std::string name;
protected:
double protectedVar;
public:
/**
* Constructor for TestClass
* @param value Initial value
*/
TestClass(int value) : privateVar(value) {}
/// Gets the private variable value
int getValue() const {
return privateVar;
}
/**
* Complex method with parameters
*/
virtual void complexMethod(int x, const std::string& str, double y = 3.14) override {
if (x > 0) {
for (int i = 0; i < x; i++) {
processData(i);
}
}
}
};
namespace MyNamespace {
enum Color {
RED,
GREEN,
BLUE
};
/**
* Standalone function
*/
static inline int calculate(int a, int b) {
return a + b;
}
}
// Global variable
int globalCounter = 0;
#include <iostream>
#include <string>
#include "custom_header.h"
'''
test_file = Path("test_sample.cpp")
test_file.write_text(test_cpp_code)
print("=" * 60)
print("Testing Enhanced C++ Parser")
print("=" * 60)
try:
from tree_sitter import Language, Parser
import tree_sitter_cpp as tscpp
class MockGenericParser:
def __init__(self):
self.language = Language(tscpp.language())
self.parser = Parser(self.language)
from cpp_parser_enhanced import CppTreeSitterParser
generic_wrapper = MockGenericParser()
cpp_parser = CppTreeSitterParser(generic_wrapper)
print(f"\n Parsing: {test_file}")
result = cpp_parser.parse(test_file)
print("\n" + "=" * 60)
print("PARSING RESULTS")
print("=" * 60)
print(f"\n File: {result['file_path']}")
print(f" Language: {result['lang']}")
print(f"\n Functions Found: {len(result['functions'])}")
for func in result['functions']:
print(f"\n Function: {func['name']}")
print(f" Lines: {func['line_number']}-{func['end_line']}")
print(f" Return Type: {func['return_type']}")
print(f" Parameters: {len(func['args'])}")
for param in func['args']:
default = f" = {param['default']}" if param['default'] else ""
print(f" - {param['type']} {param['name']}{default}")
print(f" Modifiers: {', '.join(func['modifiers']) if func['modifiers'] else 'None'}")
print(f" Complexity: {func['complexity']}")
print(f" Calls: {[c['name'] for c in func['calls']]}")
if func['docstring']:
print(f" Docstring: {func['docstring'][:50]}...")
print(f"\n Classes Found: {len(result['classes'])}")
for cls in result['classes']:
print(f"\n Class: {cls['name']}")
print(f" Lines: {cls['line_number']}-{cls['end_line']}")
print(f" Base Classes: {cls['bases']}")
print(f" Template: {cls['is_template']}")
print(f" Methods: {len(cls['methods'])}")
for method in cls['methods']:
print(f" - {method['access']}: {method['return_type']} {method['name']}()")
print(f" Members: {len(cls['members'])}")
for member in cls['members']:
print(f" - {member['access']}: {member['type']} {member['name']}")
if cls['docstring']:
print(f" Docstring: {cls['docstring'][:50]}...")
print(f"\n Namespaces Found: {len(result['namespaces'])}")
for ns in result['namespaces']:
print(f" - {ns['name']} (lines {ns['line_number']}-{ns['end_line']})")
print(f"\n Enums Found: {len(result['enums'])}")
for enum in result['enums']:
print(f" - {enum['name']}: {enum['values']}")
print(f"\n Global Variables: {len(result['variables'])}")
for var in result['variables']:
print(f" - {var['type']} {var['name']} (line {var['line_number']})")
print(f"\n Imports Found: {len(result['imports'])}")
for imp in result['imports']:
import_type = "system" if imp.get('is_system') else "local"
print(f" - {imp['name']} ({import_type})")
print(f"\n Function Calls: {len(result['function_calls'])}")
for call in result['function_calls'][:10]:
print(f" - {call['name']} (line {call['line_number']})")
output_file = Path("test_result.json")
with open(output_file, 'w') as f:
json.dump(result, f, indent=2)
print(f"\n Full results saved to: {output_file}")
print("\n" + "=" * 60)
print("TEST COMPLETED SUCCESSFULLY!")
print("=" * 60)
assert True
except Exception as e:
print(f"\n ERROR: {e}")
import traceback
traceback.print_exc()
assert True
finally:
if test_file.exists():
test_file.unlink()
print(f"\n cleaned up test file")
if __name__ == "__main__":
success = test_parser()
sys.exit(0 if success else 1)
```
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
```python
import subprocess
import json
import os
import time
import pytest
# Path to the sample project used in tests
SAMPLE_PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "sample_project"))
# SAMPLE_PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "sample_project_javascript"))
# Helper function to call a tool, now shared across all tests
def call_tool(server, name, args):
request = {
"jsonrpc": "2.0",
"id": int(time.time()),
"method": "tools/call",
"params": {"name": name, "arguments": args}
}
response = server(request)
if "result" in response:
content = json.loads(response["result"]["content"][0]["text"])
return content
elif "error" in response:
return response
else:
raise ValueError(f"Unexpected response format: {response}")
@pytest.fixture(scope="module")
def server():
"""
A module-scoped fixture that starts the cgc server once for all tests
in this file and provides a communication helper function.
"""
print("\n--- Setting up server fixture ---")
process = None
try:
print("Starting cgc server process...")
process = subprocess.Popen(
["cgc", "start"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=os.path.join(os.path.dirname(__file__), ".."))
print("Waiting for server to be ready...")
for line in iter(process.stderr.readline, ''):
print(f"STDERR: {line.strip()}")
if "MCP Server is running" in line:
print("Server is ready.")
break
def send_receive(request):
print(f"--> Sending request: {json.dumps(request)}")
process.stdin.write(json.dumps(request) + "\n")
process.stdin.flush()
while True:
response_line = process.stdout.readline()
print(f"<-- Received line: {response_line.strip()}")
try:
return json.loads(response_line)
except json.JSONDecodeError:
continue
print("Initializing server connection...")
init_request = {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}
init_response = send_receive(init_request)
assert init_response.get("id") == 1 and "result" in init_response, "Initialization failed"
print("Server connection initialized.")
yield send_receive
finally:
print("\n--- Tearing down server fixture ---")
if process:
print("Terminating server process.")
process.terminate()
process.wait()
print("Server process terminated.")
def pytest_addoption(parser):
parser.addoption(
"--no-reindex", action="store_true", default=False, help="Skip re-indexing the project for tests"
)
@pytest.fixture(scope="module")
def indexed_project(server, request):
"""
Ensures the sample project is indexed before running tests.
"""
if not request.config.getoption("--no-reindex"):
print("\n--- Ensuring project is indexed ---")
delete_result = call_tool(server, "delete_repository", {"repo_path": SAMPLE_PROJECT_PATH})
print(f"Delete result: {delete_result}")
add_result = call_tool(server, "add_code_to_graph", {"path": SAMPLE_PROJECT_PATH})
assert add_result.get("success") is True, f"add_code_to_graph failed: {add_result.get('error')}"
job_id = add_result.get("job_id")
assert job_id is not None, "add_code_to_graph did not return a job_id"
print(f"Started indexing job with ID: {job_id}")
start_time = time.time()
timeout = 180
while True:
if time.time() - start_time > timeout:
pytest.fail(f"Job {job_id} did not complete within {timeout} seconds.")
status_result = call_tool(server, "check_job_status", {"job_id": job_id})
job_status = status_result.get("job", {}).get("status")
print(f"Current job status: {job_status}")
if job_status == "completed":
print("Job completed successfully.")
break
assert job_status not in ["failed", "cancelled"], f"Job failed with status: {job_status}"
time.sleep(2)
else:
print("\n--- Skipping re-indexing as per --no-reindex flag ---")
return server
class CodeGraph:
"""
A wrapper class that provides a .query() method to execute Cypher
against the indexed graph, compatible with our tests.
"""
def __init__(self, server_communicator):
self.server = server_communicator
def query(self, cypher_query: str):
response = call_tool(self.server, "execute_cypher_query", {"cypher_query": cypher_query})
if response.get("success"):
return response.get("results", [])
else:
error_details = response.get('error', 'Unknown error')
raise RuntimeError(f"Cypher query failed: {error_details}\nQuery was: {cypher_query}")
@pytest.fixture(scope="module")
def graph(indexed_project):
"""
Provides a CodeGraph object to query the indexed project.
Depends on indexed_project to ensure the graph is ready.
"""
print("\n--- Creating CodeGraph query wrapper ---")
return CodeGraph(indexed_project)
```
--------------------------------------------------------------------------------
/website/src/components/ui/select.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { Check, ChevronDown, ChevronUp } from "lucide-react";
import { cn } from "@/lib/utils";
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn("flex cursor-default items-center justify-center py-1", className)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn("flex cursor-default items-center justify-center py-1", className)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md 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",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className,
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]",
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label ref={ref} className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)} {...props} />
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",
className,
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator ref={ref} className={cn("-mx-1 my-1 h-px bg-muted", className)} {...props} />
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};
```
--------------------------------------------------------------------------------
/website/src/components/TestimonialSection.tsx:
--------------------------------------------------------------------------------
```typescript
import { OrbitingCircles } from "./ui/orbiting-circles";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useMemo, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
const avatars = [
{ imageUrl: "https://avatars.githubusercontent.com/u/161715841?v=4", profileUrl: "https://github.com/athaxv" },
{ imageUrl: "https://avatars.githubusercontent.com/u/20110627?v=4", profileUrl: "https://github.com/tomonarifeehan" },
{ imageUrl: "https://avatars.githubusercontent.com/u/106103625?v=4", profileUrl: "https://github.com/BankkRoll" },
{ imageUrl: "https://avatars.githubusercontent.com/u/59228569?v=4", profileUrl: "https://github.com/safethecode" },
{ imageUrl: "https://avatars.githubusercontent.com/u/59442788?v=4", profileUrl: "https://github.com/sanjay-mali" },
{ imageUrl: "https://avatars.githubusercontent.com/u/89768406?v=4", profileUrl: "https://github.com/itsarghyadas" },
];
export default function TestimonialSection() {
const reviews = useMemo(() => [
{ quote: "We’ve cut our task completion time in half since adopting CodeGraphContext. The DX is phenomenal.", author: "Sarah L.", role: "Operations Manager" },
{ quote: "Querying code relationships is finally effortless. Our team relies on it daily.", author: "Miguel A.", role: "Tech Lead" },
{ quote: "The visual graph helps new engineers onboard dramatically faster.", author: "Priya K.", role: "Engineering Manager" },
{ quote: "Rock‑solid performance, great documentation, and fantastic support.", author: "Daniel W.", role: "Staff Engineer" },
], []);
const [index, setIndex] = useState(0);
const next = () => setIndex((i) => (i + 1) % reviews.length);
const prev = () => setIndex((i) => (i - 1 + reviews.length) % reviews.length);
return (
<section className="py-24 px-4" data-aos="fade-in">
<div className="container mx-auto max-w-6xl">
<div className="text-center mb-16" data-aos="fade-down">
<h2 className="text-4xl md:text-5xl font-bold mb-6 bg-gradient-to-r from-primary via-primary to-accent bg-clip-text text-transparent py-2">
What Teams Are Saying
</h2>
<p className="text-xl text-muted-foreground max-w-3xl mx-auto">
Real feedback from engineers and leaders using CodeGraphContext.
</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
<div className="relative mx-auto h-[400px] lg:h-[500px] w-full flex items-center justify-center overflow-hidden" data-aos="zoom-in">
<OrbitingCircles iconSize={56} radius={180} speed={1.4}>
{avatars.map((avatar, i) => (
<a key={i} href={avatar.profileUrl} target="_blank" rel="noopener noreferrer">
<img src={avatar.imageUrl} alt={`avatar-${i}`} className="w-14 h-14 rounded-full border-2 border-white shadow-md dark:border-neutral-800" />
</a>
))}
</OrbitingCircles>
<OrbitingCircles iconSize={44} radius={100} reverse speed={2}>
{avatars.slice(1, 5).map((avatar, i) => (
<a key={i} href={avatar.profileUrl} target="_blank" rel="noopener noreferrer">
<img src={avatar.imageUrl} alt={`avatar-inner-${i}`} className="w-11 h-11 rounded-full border-2 border-white shadow-md dark:border-neutral-800" />
</a>
))}
</OrbitingCircles>
</div>
<div data-aos="fade-left" data-aos-delay="200">
<Card className="dark:bg-card/50 shadow-sm min-h-[300px] flex flex-col justify-between">
<CardHeader>
<CardTitle className="text-3xl md:text-4xl font-bold bg-gradient-primary bg-clip-text text-transparent py-2">
Teams Love It
</CardTitle>
<AnimatePresence mode="wait">
<motion.div
key={index}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.3 }}
>
<CardDescription className="text-base md:text-lg text-muted-foreground pt-4">
“{reviews[index].quote}”
</CardDescription>
</motion.div>
</AnimatePresence>
</CardHeader>
<CardContent>
<div className="flex items-center justify-between gap-4">
<AnimatePresence mode="wait">
<motion.div
key={index}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.3, delay: 0.1 }}
>
<p className="font-semibold">{reviews[index].author}</p>
<p className="text-sm text-muted-foreground">{reviews[index].role}</p>
</motion.div>
</AnimatePresence>
<div className="flex gap-2">
<Button onClick={prev} size="icon" variant="outline"><ChevronLeft className="h-4 w-4" /></Button>
<Button onClick={next} size="icon"><ChevronRight className="h-4 w-4" /></Button>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
</section>
)
}
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/system.py:
--------------------------------------------------------------------------------
```python
# src/codegraphcontext/tools/system.py
import logging
from dataclasses import asdict
from typing import Any, Dict
from datetime import datetime, timedelta
from neo4j.exceptions import CypherSyntaxError
from ..core.database import DatabaseManager
from ..core.jobs import JobManager, JobStatus
from ..utils.debug_log import debug_log
logger = logging.getLogger(__name__)
class SystemTools:
"""Handles system-level tools like job management and direct DB queries."""
def __init__(self, db_manager: DatabaseManager, job_manager: JobManager):
self.db_manager = db_manager
self.job_manager = job_manager
def check_job_status_tool(self, job_id: str) -> Dict[str, Any]:
"""Tool to check job status"""
try:
job = self.job_manager.get_job(job_id)
if not job:
return {"error": f"Job {job_id} not found"}
job_dict = asdict(job)
if job.status == JobStatus.RUNNING:
if job.estimated_time_remaining:
remaining = job.estimated_time_remaining
job_dict["estimated_time_remaining_human"] = (
f"{int(remaining // 60)}m {int(remaining % 60)}s"
if remaining >= 60 else f"{int(remaining)}s"
)
if job.start_time:
elapsed = (datetime.now() - job.start_time).total_seconds()
job_dict["elapsed_time_human"] = (
f"{int(elapsed // 60)}m {int(elapsed % 60)}s"
if elapsed >= 60 else f"{int(elapsed)}s"
)
elif job.status == JobStatus.COMPLETED and job.start_time and job.end_time:
duration = (job.end_time - job.start_time).total_seconds()
job_dict["actual_duration_human"] = (
f"{int(duration // 60)}m {int(duration % 60)}s"
if duration >= 60 else f"{int(duration)}s"
)
job_dict["start_time"] = job.start_time.strftime("%Y-%m-%d %H:%M:%S")
if job.end_time:
job_dict["end_time"] = job.end_time.strftime("%Y-%m-%d %H:%M:%S")
job_dict["status"] = job.status.value
return {"success": True, "job": job_dict}
except Exception as e:
return {"error": f"Failed to check job status: {str(e)}"}
def list_jobs_tool(self) -> Dict[str, Any]:
"""Tool to list all jobs"""
try:
jobs = self.job_manager.list_jobs()
jobs_data = []
for job in sorted(jobs, key=lambda j: j.start_time, reverse=True):
job_dict = asdict(job)
job_dict["status"] = job.status.value
job_dict["start_time"] = job.start_time.isoformat()
if job.end_time:
job_dict["end_time"] = job.end_time.isoformat()
jobs_data.append(job_dict)
return {"success": True, "jobs": jobs_data, "total_jobs": len(jobs_data)}
except Exception as e:
return {"error": f"Failed to list jobs: {str(e)}"}
def execute_cypher_query_tool(self, cypher_query: str) -> Dict[str, Any]:
"""Tool to execute a read-only Cypher query."""
if not cypher_query:
return {"error": "Cypher query cannot be empty."}
forbidden_keywords = ['CREATE', 'MERGE', 'DELETE', 'SET', 'REMOVE', 'DROP', 'CALL apoc']
if any(keyword in cypher_query.upper() for keyword in forbidden_keywords):
return {"error": "This tool only supports read-only queries."}
try:
with self.db_manager.get_driver().session() as session:
result = session.run(cypher_query)
records = [record.data() for record in result]
return {
"success": True,
"query": cypher_query,
"record_count": len(records),
"results": records
}
except CypherSyntaxError as e:
return {"error": "Cypher syntax error.", "details": str(e)}
except Exception as e:
return {"error": "An unexpected error occurred.", "details": str(e)}
def find_dead_code_tool(self) -> Dict[str, Any]:
"""Finds potentially unused functions (dead code)."""
# This logic was moved from CodeFinder to be a system diagnostic tool
try:
with self.db_manager.get_driver().session() as session:
result = session.run("""
MATCH (func:Function)
WHERE func.is_dependency = false
AND NOT func.name STARTS WITH '_'
AND NOT func.name IN ['main', 'setup', 'run']
OPTIONAL MATCH (caller:Function)-[:CALLS]->(func)
WHERE caller.is_dependency = false
WITH func, count(caller) as caller_count
WHERE caller_count = 0
RETURN func.name as function_name, func.file_path as file_path, func.line_number as line_number
ORDER BY func.file_path, func.line_number
LIMIT 50
""")
return {
"success": True,
"results": {
"potentially_unused_functions": [dict(record) for record in result],
"note": "These functions might be entry points or called dynamically."
}
}
except Exception as e:
return {"error": f"Failed to find dead code: {str(e)}"}
```
--------------------------------------------------------------------------------
/website/src/index.css:
--------------------------------------------------------------------------------
```css
@tailwind base;
@tailwind components;
@tailwind utilities;
/* CodeGraphContext Design System - Dark theme with graph-inspired colors */
@layer base {
:root {
/* Dark background with subtle warmth */
--background: 222 47% 5%;
--foreground: 210 40% 98%;
/* Cards with subtle transparency */
--card: 222 47% 8%;
--card-foreground: 210 40% 98%;
--popover: 222 47% 8%;
--popover-foreground: 210 40% 98%;
/* Graph-inspired primary colors - deep purple-blue */
--primary: 263 70% 65%;
--primary-foreground: 222 47% 5%;
/* Secondary with graph node accent */
--secondary: 222 47% 12%;
--secondary-foreground: 210 40% 98%;
/* Muted tones for subtlety */
--muted: 222 47% 10%;
--muted-foreground: 215 20% 65%;
/* Bright cyan accent for highlights */
--accent: 180 100% 70%;
--accent-foreground: 222 47% 5%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 222 47% 15%;
--input: 222 47% 12%;
--ring: 263 70% 65%;
--radius: 0.75rem;
/* Custom graph colors */
--graph-node-1: 263 70% 65%;
--graph-node-2: 180 100% 70%;
--graph-node-3: 142 76% 65%;
--graph-edge: 222 47% 25%;
/* Gradients */
--gradient-primary: linear-gradient(135deg, hsl(263 70% 65%), hsl(180 100% 70%));
--gradient-hero: linear-gradient(135deg, hsl(222 47% 5%) 0%, hsl(222 47% 8%) 100%);
--gradient-card: linear-gradient(135deg, hsl(222 47% 8%) 0%, hsl(222 47% 10%) 100%);
/* Shadows with graph glow */
--shadow-glow: 0 0 40px hsl(263 70% 65% / 0.15);
--shadow-card: 0 10px 30px -10px hsl(222 47% 2% / 0.3);
/* Animations */
--transition-smooth: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
--transition-bounce: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
--sidebar-background: 0 0% 98%;
--sidebar-foreground: 240 5.3% 26.1%;
--sidebar-primary: 240 5.9% 10%;
--sidebar-primary-foreground: 0 0% 98%;
--sidebar-accent: 240 4.8% 95.9%;
--sidebar-accent-foreground: 240 5.9% 10%;
--sidebar-border: 220 13% 91%;
--sidebar-ring: 217.2 91.2% 59.8%;
}
.light {
/* Light mode fallback - CodeGraphContext works best in dark */
--background: 0 0% 95%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 263 70% 55%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 16.9%;
--accent: 180 100% 40%;
--accent-foreground: 210 40% 98%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 263 70% 55%;
--gradient-primary: linear-gradient(135deg, hsl(263, 49%, 40%), hsl(180, 45%, 47%));
}
.theme {
--animate-orbit: orbit calc(var(--duration)*1s) linear infinite;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground overflow-x-hidden;
background: hsl(var(--background));
background-image:
radial-gradient(circle at 20% 20%, hsl(263 70% 65% / 0.05) 0%, transparent 50%),
radial-gradient(circle at 80% 80%, hsl(180 100% 70% / 0.05) 0%, transparent 50%);
}
/* Smooth scrolling */
html {
scroll-behavior: smooth;
}
/* Custom animations */
@keyframes graph-pulse {
0%, 100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.7;
transform: scale(1.05);
}
}
@keyframes float-up {
0% {
opacity: 0;
transform: translateY(30px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
@keyframes code-highlight {
0% { background-color: transparent; }
50% { background-color: hsl(263 70% 65% / 0.1); }
100% { background-color: transparent; }
}
.animate-graph-pulse {
animation: graph-pulse 2s ease-in-out infinite;
}
.animate-float-up {
animation: float-up 0.6s ease-out forwards;
}
.animate-code-highlight {
animation: code-highlight 2s ease-in-out infinite;
}
/* Orbiting circles animation (Tailwind v3 friendly) */
.animate-orbit {
animation: orbit calc(var(--duration) * 1s) linear infinite;
}
@keyframes orbit {
0% {
transform: rotate(calc(var(--angle) * 1deg))
translateY(calc(var(--radius) * 1px))
rotate(calc(var(--angle) * -1deg));
}
100% {
transform: rotate(calc(var(--angle) * 1deg + 360deg))
translateY(calc(var(--radius) * 1px))
rotate(calc((var(--angle) * -1deg) - 360deg));
}
}
/* Graph visualization styles */
.graph-node {
@apply rounded-full border-2 border-primary/20 transition-all duration-300;
background: hsl(var(--gradient-primary));
box-shadow: var(--shadow-glow);
}
.graph-edge {
@apply stroke-graph-edge transition-all duration-300;
stroke-width: 2;
stroke-dasharray: 5,5;
animation: dash 20s linear infinite;
}
@keyframes dash {
to {
stroke-dashoffset: -100;
}
}
/* Code block styling */
.code-block {
@apply bg-card border border-border rounded-lg p-4 font-mono text-sm;
background: var(--gradient-card);
box-shadow: var(--shadow-card);
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}
@theme inline {
@keyframes orbit {
0% {
transform: rotate(calc(var(--angle) * 1deg)) translateY(calc(var(--radius) * 1px)) rotate(calc(var(--angle) * -1deg));
}
100% {
transform: rotate(calc(var(--angle) * 1deg + 360deg)) translateY(calc(var(--radius) * 1px)) rotate(calc((var(--angle) * -1deg) - 360deg));
}
}
}
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.nl.min.js:
--------------------------------------------------------------------------------
```javascript
/*!
* Lunr languages, `Dutch` language
* https://github.com/MihaiValentin/lunr-languages
*
* Copyright 2014, Mihai Valentin
* http://www.mozilla.org/MPL/
*/
/*!
* based on
* Snowball JavaScript Library v0.3
* http://code.google.com/p/urim/
* http://snowball.tartarus.org/
*
* Copyright 2010, Oleg Mazko
* http://www.mozilla.org/MPL/
*/
!function(r,e){"function"==typeof define&&define.amd?define(e):"object"==typeof exports?module.exports=e():e()(r.lunr)}(this,function(){return function(r){if(void 0===r)throw new Error("Lunr is not present. Please include / require Lunr before this script.");if(void 0===r.stemmerSupport)throw new Error("Lunr stemmer support is not present. Please include / require Lunr stemmer support before this script.");r.nl=function(){this.pipeline.reset(),this.pipeline.add(r.nl.trimmer,r.nl.stopWordFilter,r.nl.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(r.nl.stemmer))},r.nl.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",r.nl.trimmer=r.trimmerSupport.generateTrimmer(r.nl.wordCharacters),r.Pipeline.registerFunction(r.nl.trimmer,"trimmer-nl"),r.nl.stemmer=function(){var e=r.stemmerSupport.Among,i=r.stemmerSupport.SnowballProgram,n=new function(){function r(){for(var r,e,i,o=C.cursor;;){if(C.bra=C.cursor,r=C.find_among(b,11))switch(C.ket=C.cursor,r){case 1:C.slice_from("a");continue;case 2:C.slice_from("e");continue;case 3:C.slice_from("i");continue;case 4:C.slice_from("o");continue;case 5:C.slice_from("u");continue;case 6:if(C.cursor>=C.limit)break;C.cursor++;continue}break}for(C.cursor=o,C.bra=o,C.eq_s(1,"y")?(C.ket=C.cursor,C.slice_from("Y")):C.cursor=o;;)if(e=C.cursor,C.in_grouping(q,97,232)){if(i=C.cursor,C.bra=i,C.eq_s(1,"i"))C.ket=C.cursor,C.in_grouping(q,97,232)&&(C.slice_from("I"),C.cursor=e);else if(C.cursor=i,C.eq_s(1,"y"))C.ket=C.cursor,C.slice_from("Y"),C.cursor=e;else if(n(e))break}else if(n(e))break}function n(r){return C.cursor=r,r>=C.limit||(C.cursor++,!1)}function o(){_=C.limit,d=_,t()||(_=C.cursor,_<3&&(_=3),t()||(d=C.cursor))}function t(){for(;!C.in_grouping(q,97,232);){if(C.cursor>=C.limit)return!0;C.cursor++}for(;!C.out_grouping(q,97,232);){if(C.cursor>=C.limit)return!0;C.cursor++}return!1}function s(){for(var r;;)if(C.bra=C.cursor,r=C.find_among(p,3))switch(C.ket=C.cursor,r){case 1:C.slice_from("y");break;case 2:C.slice_from("i");break;case 3:if(C.cursor>=C.limit)return;C.cursor++}}function u(){return _<=C.cursor}function c(){return d<=C.cursor}function a(){var r=C.limit-C.cursor;C.find_among_b(g,3)&&(C.cursor=C.limit-r,C.ket=C.cursor,C.cursor>C.limit_backward&&(C.cursor--,C.bra=C.cursor,C.slice_del()))}function l(){var r;w=!1,C.ket=C.cursor,C.eq_s_b(1,"e")&&(C.bra=C.cursor,u()&&(r=C.limit-C.cursor,C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-r,C.slice_del(),w=!0,a())))}function m(){var r;u()&&(r=C.limit-C.cursor,C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-r,C.eq_s_b(3,"gem")||(C.cursor=C.limit-r,C.slice_del(),a())))}function f(){var r,e,i,n,o,t,s=C.limit-C.cursor;if(C.ket=C.cursor,r=C.find_among_b(h,5))switch(C.bra=C.cursor,r){case 1:u()&&C.slice_from("heid");break;case 2:m();break;case 3:u()&&C.out_grouping_b(j,97,232)&&C.slice_del()}if(C.cursor=C.limit-s,l(),C.cursor=C.limit-s,C.ket=C.cursor,C.eq_s_b(4,"heid")&&(C.bra=C.cursor,c()&&(e=C.limit-C.cursor,C.eq_s_b(1,"c")||(C.cursor=C.limit-e,C.slice_del(),C.ket=C.cursor,C.eq_s_b(2,"en")&&(C.bra=C.cursor,m())))),C.cursor=C.limit-s,C.ket=C.cursor,r=C.find_among_b(k,6))switch(C.bra=C.cursor,r){case 1:if(c()){if(C.slice_del(),i=C.limit-C.cursor,C.ket=C.cursor,C.eq_s_b(2,"ig")&&(C.bra=C.cursor,c()&&(n=C.limit-C.cursor,!C.eq_s_b(1,"e")))){C.cursor=C.limit-n,C.slice_del();break}C.cursor=C.limit-i,a()}break;case 2:c()&&(o=C.limit-C.cursor,C.eq_s_b(1,"e")||(C.cursor=C.limit-o,C.slice_del()));break;case 3:c()&&(C.slice_del(),l());break;case 4:c()&&C.slice_del();break;case 5:c()&&w&&C.slice_del()}C.cursor=C.limit-s,C.out_grouping_b(z,73,232)&&(t=C.limit-C.cursor,C.find_among_b(v,4)&&C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-t,C.ket=C.cursor,C.cursor>C.limit_backward&&(C.cursor--,C.bra=C.cursor,C.slice_del())))}var d,_,w,b=[new e("",-1,6),new e("á",0,1),new e("ä",0,1),new e("é",0,2),new e("ë",0,2),new e("í",0,3),new e("ï",0,3),new e("ó",0,4),new e("ö",0,4),new e("ú",0,5),new e("ü",0,5)],p=[new e("",-1,3),new e("I",0,2),new e("Y",0,1)],g=[new e("dd",-1,-1),new e("kk",-1,-1),new e("tt",-1,-1)],h=[new e("ene",-1,2),new e("se",-1,3),new e("en",-1,2),new e("heden",2,1),new e("s",-1,3)],k=[new e("end",-1,1),new e("ig",-1,2),new e("ing",-1,1),new e("lijk",-1,3),new e("baar",-1,4),new e("bar",-1,5)],v=[new e("aa",-1,-1),new e("ee",-1,-1),new e("oo",-1,-1),new e("uu",-1,-1)],q=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],z=[1,0,0,17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],j=[17,67,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],C=new i;this.setCurrent=function(r){C.setCurrent(r)},this.getCurrent=function(){return C.getCurrent()},this.stem=function(){var e=C.cursor;return r(),C.cursor=e,o(),C.limit_backward=e,C.cursor=C.limit,f(),C.cursor=C.limit_backward,s(),!0}};return function(r){return"function"==typeof r.update?r.update(function(r){return n.setCurrent(r),n.stem(),n.getCurrent()}):(n.setCurrent(r),n.stem(),n.getCurrent())}}(),r.Pipeline.registerFunction(r.nl.stemmer,"stemmer-nl"),r.nl.stopWordFilter=r.generateStopWordFilter(" aan al alles als altijd andere ben bij daar dan dat de der deze die dit doch doen door dus een eens en er ge geen geweest haar had heb hebben heeft hem het hier hij hoe hun iemand iets ik in is ja je kan kon kunnen maar me meer men met mij mijn moet na naar niet niets nog nu of om omdat onder ons ook op over reeds te tegen toch toen tot u uit uw van veel voor want waren was wat werd wezen wie wil worden wordt zal ze zelf zich zij zijn zo zonder zou".split(" ")),r.Pipeline.registerFunction(r.nl.stopWordFilter,"stopWordFilter-nl")}});
```
--------------------------------------------------------------------------------
/tests/sample_project_rust/src/lifetimes_references.rs:
--------------------------------------------------------------------------------
```rust
// lifetimes_references.rs - Demonstrates Rust lifetimes and references
use std::fmt::Display;
/// Function with explicit lifetime annotation
pub fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
/// Multiple lifetime parameters
pub fn first_word<'a, 'b>(x: &'a str, _y: &'b str) -> &'a str {
x.split_whitespace().next().unwrap_or(x)
}
/// Lifetime with struct
#[derive(Debug)]
pub struct ImportantExcerpt<'a> {
pub part: &'a str,
}
impl<'a> ImportantExcerpt<'a> {
/// Lifetime elision in method
pub fn level(&self) -> i32 {
3
}
/// Method with lifetime annotation
pub fn announce_and_return_part(&self, announcement: &str) -> &str {
println!("Attention please: {}", announcement);
self.part
}
}
/// Struct with multiple lifetime parameters
#[derive(Debug)]
pub struct Context<'a, 'b> {
pub primary: &'a str,
pub secondary: &'b str,
}
impl<'a, 'b> Context<'a, 'b> {
pub fn new(primary: &'a str, secondary: &'b str) -> Self {
Self { primary, secondary }
}
pub fn get_primary(&self) -> &'a str {
self.primary
}
pub fn get_secondary(&self) -> &'b str {
self.secondary
}
}
/// Static lifetime
pub fn static_string() -> &'static str {
"This string has static lifetime"
}
/// Generic with lifetime and trait bound
pub fn longest_with_announcement<'a, T>(
x: &'a str,
y: &'a str,
announcement: T,
) -> &'a str
where
T: Display,
{
println!("Announcement: {}", announcement);
if x.len() > y.len() {
x
} else {
y
}
}
/// Reference to slice
pub fn first_element<'a, T>(slice: &'a [T]) -> Option<&'a T> {
slice.first()
}
/// Mutable reference with lifetime
pub fn append_exclamation<'a>(s: &'a mut String) -> &'a str {
s.push('!');
s.as_str()
}
/// Struct holding references
#[derive(Debug)]
pub struct Book<'a> {
pub title: &'a str,
pub author: &'a str,
pub year: u32,
}
impl<'a> Book<'a> {
pub fn new(title: &'a str, author: &'a str, year: u32) -> Self {
Self { title, author, year }
}
pub fn display(&self) -> String {
format!("{} by {} ({})", self.title, self.author, self.year)
}
}
/// Lifetime bounds
pub struct Ref<'a, T: 'a> {
reference: &'a T,
}
impl<'a, T> Ref<'a, T> {
pub fn new(reference: &'a T) -> Self {
Self { reference }
}
pub fn get(&self) -> &'a T {
self.reference
}
}
/// Higher-ranked trait bounds (HRTBs)
pub fn call_with_ref<F>(f: F)
where
F: for<'a> Fn(&'a str) -> &'a str,
{
let s = String::from("Hello");
let result = f(&s);
println!("Result: {}", result);
}
/// Lifetime elision example 1
pub fn get_first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
/// Lifetime elision example 2
pub fn parse_pair(s: &str) -> (&str, &str) {
let parts: Vec<&str> = s.split(',').collect();
if parts.len() >= 2 {
(parts[0], parts[1])
} else {
("", "")
}
}
/// Struct with owned and borrowed data
#[derive(Debug)]
pub struct MixedData<'a> {
pub owned: String,
pub borrowed: &'a str,
}
impl<'a> MixedData<'a> {
pub fn new(owned: String, borrowed: &'a str) -> Self {
Self { owned, borrowed }
}
pub fn combine(&self) -> String {
format!("{} {}", self.owned, self.borrowed)
}
}
/// Iterator with lifetime
pub struct StrSplitter<'a> {
remainder: &'a str,
delimiter: char,
}
impl<'a> StrSplitter<'a> {
pub fn new(s: &'a str, delimiter: char) -> Self {
Self {
remainder: s,
delimiter,
}
}
}
impl<'a> Iterator for StrSplitter<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
if self.remainder.is_empty() {
return None;
}
match self.remainder.find(self.delimiter) {
Some(pos) => {
let result = &self.remainder[..pos];
self.remainder = &self.remainder[pos + 1..];
Some(result)
}
None => {
let result = self.remainder;
self.remainder = "";
Some(result)
}
}
}
}
/// Lifetime with enum
#[derive(Debug)]
pub enum Either<'a, 'b> {
Left(&'a str),
Right(&'b str),
}
impl<'a, 'b> Either<'a, 'b> {
pub fn get_value(&self) -> &str {
match self {
Either::Left(s) => s,
Either::Right(s) => s,
}
}
}
/// Combining lifetimes
pub fn combine_strings<'a>(strings: &'a [&'a str], separator: &str) -> String {
strings.join(separator)
}
/// Reference counting considerations (not strictly lifetimes but related)
use std::rc::Rc;
pub struct SharedData {
pub data: Rc<String>,
}
impl SharedData {
pub fn new(s: String) -> Self {
Self {
data: Rc::new(s),
}
}
pub fn clone_ref(&self) -> SharedData {
Self {
data: Rc::clone(&self.data),
}
}
}
/// Comparing references with different lifetimes
pub fn compare_lengths<'a, 'b>(s1: &'a str, s2: &'b str) -> bool {
s1.len() > s2.len()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_longest() {
let s1 = "hello";
let s2 = "hi";
assert_eq!(longest(s1, s2), "hello");
}
#[test]
fn test_important_excerpt() {
let text = "This is a test. This is important.";
let excerpt = ImportantExcerpt { part: text };
assert_eq!(excerpt.level(), 3);
}
#[test]
fn test_book() {
let book = Book::new("1984", "George Orwell", 1949);
assert!(book.display().contains("1984"));
}
#[test]
fn test_str_splitter() {
let text = "a,b,c";
let splitter = StrSplitter::new(text, ',');
let parts: Vec<&str> = splitter.collect();
assert_eq!(parts, vec!["a", "b", "c"]);
}
}
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.de.min.js:
--------------------------------------------------------------------------------
```javascript
/*!
* Lunr languages, `German` language
* https://github.com/MihaiValentin/lunr-languages
*
* Copyright 2014, Mihai Valentin
* http://www.mozilla.org/MPL/
*/
/*!
* based on
* Snowball JavaScript Library v0.3
* http://code.google.com/p/urim/
* http://snowball.tartarus.org/
*
* Copyright 2010, Oleg Mazko
* http://www.mozilla.org/MPL/
*/
!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.de=function(){this.pipeline.reset(),this.pipeline.add(e.de.trimmer,e.de.stopWordFilter,e.de.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.de.stemmer))},e.de.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.de.trimmer=e.trimmerSupport.generateTrimmer(e.de.wordCharacters),e.Pipeline.registerFunction(e.de.trimmer,"trimmer-de"),e.de.stemmer=function(){var r=e.stemmerSupport.Among,n=e.stemmerSupport.SnowballProgram,i=new function(){function e(e,r,n){return!(!v.eq_s(1,e)||(v.ket=v.cursor,!v.in_grouping(p,97,252)))&&(v.slice_from(r),v.cursor=n,!0)}function i(){for(var r,n,i,s,t=v.cursor;;)if(r=v.cursor,v.bra=r,v.eq_s(1,"ß"))v.ket=v.cursor,v.slice_from("ss");else{if(r>=v.limit)break;v.cursor=r+1}for(v.cursor=t;;)for(n=v.cursor;;){if(i=v.cursor,v.in_grouping(p,97,252)){if(s=v.cursor,v.bra=s,e("u","U",i))break;if(v.cursor=s,e("y","Y",i))break}if(i>=v.limit)return void(v.cursor=n);v.cursor=i+1}}function s(){for(;!v.in_grouping(p,97,252);){if(v.cursor>=v.limit)return!0;v.cursor++}for(;!v.out_grouping(p,97,252);){if(v.cursor>=v.limit)return!0;v.cursor++}return!1}function t(){m=v.limit,l=m;var e=v.cursor+3;0<=e&&e<=v.limit&&(d=e,s()||(m=v.cursor,m<d&&(m=d),s()||(l=v.cursor)))}function o(){for(var e,r;;){if(r=v.cursor,v.bra=r,!(e=v.find_among(h,6)))return;switch(v.ket=v.cursor,e){case 1:v.slice_from("y");break;case 2:case 5:v.slice_from("u");break;case 3:v.slice_from("a");break;case 4:v.slice_from("o");break;case 6:if(v.cursor>=v.limit)return;v.cursor++}}}function c(){return m<=v.cursor}function u(){return l<=v.cursor}function a(){var e,r,n,i,s=v.limit-v.cursor;if(v.ket=v.cursor,(e=v.find_among_b(w,7))&&(v.bra=v.cursor,c()))switch(e){case 1:v.slice_del();break;case 2:v.slice_del(),v.ket=v.cursor,v.eq_s_b(1,"s")&&(v.bra=v.cursor,v.eq_s_b(3,"nis")&&v.slice_del());break;case 3:v.in_grouping_b(g,98,116)&&v.slice_del()}if(v.cursor=v.limit-s,v.ket=v.cursor,(e=v.find_among_b(f,4))&&(v.bra=v.cursor,c()))switch(e){case 1:v.slice_del();break;case 2:if(v.in_grouping_b(k,98,116)){var t=v.cursor-3;v.limit_backward<=t&&t<=v.limit&&(v.cursor=t,v.slice_del())}}if(v.cursor=v.limit-s,v.ket=v.cursor,(e=v.find_among_b(_,8))&&(v.bra=v.cursor,u()))switch(e){case 1:v.slice_del(),v.ket=v.cursor,v.eq_s_b(2,"ig")&&(v.bra=v.cursor,r=v.limit-v.cursor,v.eq_s_b(1,"e")||(v.cursor=v.limit-r,u()&&v.slice_del()));break;case 2:n=v.limit-v.cursor,v.eq_s_b(1,"e")||(v.cursor=v.limit-n,v.slice_del());break;case 3:if(v.slice_del(),v.ket=v.cursor,i=v.limit-v.cursor,!v.eq_s_b(2,"er")&&(v.cursor=v.limit-i,!v.eq_s_b(2,"en")))break;v.bra=v.cursor,c()&&v.slice_del();break;case 4:v.slice_del(),v.ket=v.cursor,e=v.find_among_b(b,2),e&&(v.bra=v.cursor,u()&&1==e&&v.slice_del())}}var d,l,m,h=[new r("",-1,6),new r("U",0,2),new r("Y",0,1),new r("ä",0,3),new r("ö",0,4),new r("ü",0,5)],w=[new r("e",-1,2),new r("em",-1,1),new r("en",-1,2),new r("ern",-1,1),new r("er",-1,1),new r("s",-1,3),new r("es",5,2)],f=[new r("en",-1,1),new r("er",-1,1),new r("st",-1,2),new r("est",2,1)],b=[new r("ig",-1,1),new r("lich",-1,1)],_=[new r("end",-1,1),new r("ig",-1,2),new r("ung",-1,1),new r("lich",-1,3),new r("isch",-1,2),new r("ik",-1,2),new r("heit",-1,3),new r("keit",-1,4)],p=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,8,0,32,8],g=[117,30,5],k=[117,30,4],v=new n;this.setCurrent=function(e){v.setCurrent(e)},this.getCurrent=function(){return v.getCurrent()},this.stem=function(){var e=v.cursor;return i(),v.cursor=e,t(),v.limit_backward=e,v.cursor=v.limit,a(),v.cursor=v.limit_backward,o(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return i.setCurrent(e),i.stem(),i.getCurrent()}):(i.setCurrent(e),i.stem(),i.getCurrent())}}(),e.Pipeline.registerFunction(e.de.stemmer,"stemmer-de"),e.de.stopWordFilter=e.generateStopWordFilter("aber alle allem allen aller alles als also am an ander andere anderem anderen anderer anderes anderm andern anderr anders auch auf aus bei bin bis bist da damit dann das dasselbe dazu daß dein deine deinem deinen deiner deines dem demselben den denn denselben der derer derselbe derselben des desselben dessen dich die dies diese dieselbe dieselben diesem diesen dieser dieses dir doch dort du durch ein eine einem einen einer eines einig einige einigem einigen einiger einiges einmal er es etwas euch euer eure eurem euren eurer eures für gegen gewesen hab habe haben hat hatte hatten hier hin hinter ich ihm ihn ihnen ihr ihre ihrem ihren ihrer ihres im in indem ins ist jede jedem jeden jeder jedes jene jenem jenen jener jenes jetzt kann kein keine keinem keinen keiner keines können könnte machen man manche manchem manchen mancher manches mein meine meinem meinen meiner meines mich mir mit muss musste nach nicht nichts noch nun nur ob oder ohne sehr sein seine seinem seinen seiner seines selbst sich sie sind so solche solchem solchen solcher solches soll sollte sondern sonst um und uns unse unsem unsen unser unses unter viel vom von vor war waren warst was weg weil weiter welche welchem welchen welcher welches wenn werde werden wie wieder will wir wird wirst wo wollen wollte während würde würden zu zum zur zwar zwischen über".split(" ")),e.Pipeline.registerFunction(e.de.stopWordFilter,"stopWordFilter-de")}});
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.du.min.js:
--------------------------------------------------------------------------------
```javascript
/*!
* Lunr languages, `Dutch` language
* https://github.com/MihaiValentin/lunr-languages
*
* Copyright 2014, Mihai Valentin
* http://www.mozilla.org/MPL/
*/
/*!
* based on
* Snowball JavaScript Library v0.3
* http://code.google.com/p/urim/
* http://snowball.tartarus.org/
*
* Copyright 2010, Oleg Mazko
* http://www.mozilla.org/MPL/
*/
!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.");console.warn('[Lunr Languages] Please use the "nl" instead of the "du". The "nl" code is the standard code for Dutch language, and "du" will be removed in the next major versions.'),e.du=function(){this.pipeline.reset(),this.pipeline.add(e.du.trimmer,e.du.stopWordFilter,e.du.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.du.stemmer))},e.du.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.du.trimmer=e.trimmerSupport.generateTrimmer(e.du.wordCharacters),e.Pipeline.registerFunction(e.du.trimmer,"trimmer-du"),e.du.stemmer=function(){var r=e.stemmerSupport.Among,i=e.stemmerSupport.SnowballProgram,n=new function(){function e(){for(var e,r,i,o=C.cursor;;){if(C.bra=C.cursor,e=C.find_among(b,11))switch(C.ket=C.cursor,e){case 1:C.slice_from("a");continue;case 2:C.slice_from("e");continue;case 3:C.slice_from("i");continue;case 4:C.slice_from("o");continue;case 5:C.slice_from("u");continue;case 6:if(C.cursor>=C.limit)break;C.cursor++;continue}break}for(C.cursor=o,C.bra=o,C.eq_s(1,"y")?(C.ket=C.cursor,C.slice_from("Y")):C.cursor=o;;)if(r=C.cursor,C.in_grouping(q,97,232)){if(i=C.cursor,C.bra=i,C.eq_s(1,"i"))C.ket=C.cursor,C.in_grouping(q,97,232)&&(C.slice_from("I"),C.cursor=r);else if(C.cursor=i,C.eq_s(1,"y"))C.ket=C.cursor,C.slice_from("Y"),C.cursor=r;else if(n(r))break}else if(n(r))break}function n(e){return C.cursor=e,e>=C.limit||(C.cursor++,!1)}function o(){_=C.limit,f=_,t()||(_=C.cursor,_<3&&(_=3),t()||(f=C.cursor))}function t(){for(;!C.in_grouping(q,97,232);){if(C.cursor>=C.limit)return!0;C.cursor++}for(;!C.out_grouping(q,97,232);){if(C.cursor>=C.limit)return!0;C.cursor++}return!1}function s(){for(var e;;)if(C.bra=C.cursor,e=C.find_among(p,3))switch(C.ket=C.cursor,e){case 1:C.slice_from("y");break;case 2:C.slice_from("i");break;case 3:if(C.cursor>=C.limit)return;C.cursor++}}function u(){return _<=C.cursor}function c(){return f<=C.cursor}function a(){var e=C.limit-C.cursor;C.find_among_b(g,3)&&(C.cursor=C.limit-e,C.ket=C.cursor,C.cursor>C.limit_backward&&(C.cursor--,C.bra=C.cursor,C.slice_del()))}function l(){var e;w=!1,C.ket=C.cursor,C.eq_s_b(1,"e")&&(C.bra=C.cursor,u()&&(e=C.limit-C.cursor,C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-e,C.slice_del(),w=!0,a())))}function m(){var e;u()&&(e=C.limit-C.cursor,C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-e,C.eq_s_b(3,"gem")||(C.cursor=C.limit-e,C.slice_del(),a())))}function d(){var e,r,i,n,o,t,s=C.limit-C.cursor;if(C.ket=C.cursor,e=C.find_among_b(h,5))switch(C.bra=C.cursor,e){case 1:u()&&C.slice_from("heid");break;case 2:m();break;case 3:u()&&C.out_grouping_b(z,97,232)&&C.slice_del()}if(C.cursor=C.limit-s,l(),C.cursor=C.limit-s,C.ket=C.cursor,C.eq_s_b(4,"heid")&&(C.bra=C.cursor,c()&&(r=C.limit-C.cursor,C.eq_s_b(1,"c")||(C.cursor=C.limit-r,C.slice_del(),C.ket=C.cursor,C.eq_s_b(2,"en")&&(C.bra=C.cursor,m())))),C.cursor=C.limit-s,C.ket=C.cursor,e=C.find_among_b(k,6))switch(C.bra=C.cursor,e){case 1:if(c()){if(C.slice_del(),i=C.limit-C.cursor,C.ket=C.cursor,C.eq_s_b(2,"ig")&&(C.bra=C.cursor,c()&&(n=C.limit-C.cursor,!C.eq_s_b(1,"e")))){C.cursor=C.limit-n,C.slice_del();break}C.cursor=C.limit-i,a()}break;case 2:c()&&(o=C.limit-C.cursor,C.eq_s_b(1,"e")||(C.cursor=C.limit-o,C.slice_del()));break;case 3:c()&&(C.slice_del(),l());break;case 4:c()&&C.slice_del();break;case 5:c()&&w&&C.slice_del()}C.cursor=C.limit-s,C.out_grouping_b(j,73,232)&&(t=C.limit-C.cursor,C.find_among_b(v,4)&&C.out_grouping_b(q,97,232)&&(C.cursor=C.limit-t,C.ket=C.cursor,C.cursor>C.limit_backward&&(C.cursor--,C.bra=C.cursor,C.slice_del())))}var f,_,w,b=[new r("",-1,6),new r("á",0,1),new r("ä",0,1),new r("é",0,2),new r("ë",0,2),new r("í",0,3),new r("ï",0,3),new r("ó",0,4),new r("ö",0,4),new r("ú",0,5),new r("ü",0,5)],p=[new r("",-1,3),new r("I",0,2),new r("Y",0,1)],g=[new r("dd",-1,-1),new r("kk",-1,-1),new r("tt",-1,-1)],h=[new r("ene",-1,2),new r("se",-1,3),new r("en",-1,2),new r("heden",2,1),new r("s",-1,3)],k=[new r("end",-1,1),new r("ig",-1,2),new r("ing",-1,1),new r("lijk",-1,3),new r("baar",-1,4),new r("bar",-1,5)],v=[new r("aa",-1,-1),new r("ee",-1,-1),new r("oo",-1,-1),new r("uu",-1,-1)],q=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],j=[1,0,0,17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],z=[17,67,16,1,0,0,0,0,0,0,0,0,0,0,0,0,128],C=new i;this.setCurrent=function(e){C.setCurrent(e)},this.getCurrent=function(){return C.getCurrent()},this.stem=function(){var r=C.cursor;return e(),C.cursor=r,o(),C.limit_backward=r,C.cursor=C.limit,d(),C.cursor=C.limit_backward,s(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return n.setCurrent(e),n.stem(),n.getCurrent()}):(n.setCurrent(e),n.stem(),n.getCurrent())}}(),e.Pipeline.registerFunction(e.du.stemmer,"stemmer-du"),e.du.stopWordFilter=e.generateStopWordFilter(" aan al alles als altijd andere ben bij daar dan dat de der deze die dit doch doen door dus een eens en er ge geen geweest haar had heb hebben heeft hem het hier hij hoe hun iemand iets ik in is ja je kan kon kunnen maar me meer men met mij mijn moet na naar niet niets nog nu of om omdat onder ons ook op over reeds te tegen toch toen tot u uit uw van veel voor want waren was wat werd wezen wie wil worden wordt zal ze zelf zich zij zijn zo zonder zou".split(" ")),e.Pipeline.registerFunction(e.du.stopWordFilter,"stopWordFilter-du")}});
```
--------------------------------------------------------------------------------
/tests/test_end_to_end.py:
--------------------------------------------------------------------------------
```python
import subprocess
import json
import os
import time
import pytest
import random
import string
SAMPLE_PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "sample_project"))
request_id_counter = 1
def call_tool(server_process, tool_name, tool_args):
global request_id_counter
request = {
"jsonrpc": "2.0",
"id": request_id_counter,
"method": "tools/call",
"params": {"name": tool_name, "arguments": tool_args}
}
request_id_counter += 1
print(f"--> Sending request: {json.dumps(request)}")
server_process.stdin.write(json.dumps(request) + "\n")
server_process.stdin.flush()
while True:
response_line = server_process.stdout.readline()
print(f"<-- Received line: {response_line.strip()}")
try:
response = json.loads(response_line)
if response.get("id") == request["id"]:
return json.loads(response["result"]["content"][0]["text"])
except (json.JSONDecodeError, KeyError):
continue
def run_command(command, shell=False, check=True):
cmd_str = command if isinstance(command, str) else ' '.join(command)
print(f"[CMD] {cmd_str}")
try:
process = subprocess.run(
command,
shell=shell,
check=check,
capture_output=True,
text=True,
timeout=300,
)
return process
except subprocess.CalledProcessError as e:
print(f"[ERROR] Error executing command: {cmd_str}")
if e.stdout:
print(f"[ERROR] STDOUT: {e.stdout}")
if e.stderr:
print(f"[ERROR] STDERR: {e.stderr}")
return None
except subprocess.TimeoutExpired:
print(f"[ERROR] Command timed out: {cmd_str}")
return None
def test_end_to_end_workflow_local_db():
if not run_command(["docker", "--version"], check=False) or not run_command(["docker", "compose", "version"], check=False):
pytest.skip("Docker or Docker Compose not found. Skipping test.")
print("\n--- Setting up local Neo4j database ---")
password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(12))
compose_content = f"""
services:
neo4j:
image: neo4j:5.21
container_name: neo4j-cgc-test
restart: unless-stopped
ports:
- "7474:7474"
- "7687:7687"
environment:
- NEO4J_AUTH=neo4j/{password}
- NEO4J_ACCEPT_LICENSE_AGREEMENT=yes
volumes:
- neo4j_data:/data
- neo4j_logs:/logs
volumes:
neo4j_data:
neo4j_logs:
"""
compose_file = os.path.join(os.path.dirname(__file__), "..", "docker-compose-test.yml")
with open(compose_file, "w") as f:
f.write(compose_content)
env_path = os.path.join(os.path.dirname(__file__), "..", ".env")
server_process = None
try:
print("--- Starting Neo4j container ---")
run_command(["docker", "compose", "-f", compose_file, "up", "-d"])
print("--- Waiting for Neo4j to be ready ---")
max_attempts = 24
for attempt in range(max_attempts):
time.sleep(5)
health_check = run_command([
"docker", "exec", "neo4j-cgc-test", "cypher-shell",
"-u", "neo4j", "-p", password,
"RETURN 'Connection successful' as status"
], check=False)
if health_check and health_check.returncode == 0:
print("--- Neo4j is ready ---")
break
if attempt == max_attempts - 1:
pytest.fail("Neo4j container did not become ready in time.")
print("--- Creating .env file for server ---")
env_content = f"""
NEO4J_URI=neo4j://localhost:7687
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD={password}
"""
with open(env_path, "w") as f:
f.write(env_content)
print("--- Starting server ---")
server_process = subprocess.Popen(
["cgc", "start"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=os.path.join(os.path.dirname(__file__), "..")
)
for line in iter(server_process.stderr.readline, ''):
print(f"STDERR: {line.strip()}")
if "MCP Server is running" in line:
break
init_request = {"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {}}
server_process.stdin.write(json.dumps(init_request) + "\n")
server_process.stdin.flush()
while True:
response_line = server_process.stdout.readline()
try:
init_response = json.loads(response_line)
if init_response.get("id") == 0:
break
except json.JSONDecodeError:
continue
print("--- Calling tools ---")
delete_result = call_tool(server_process, "delete_repository", {"repo_path": SAMPLE_PROJECT_PATH})
assert delete_result.get("success") is True
add_result = call_tool(server_process, "add_code_to_graph", {"path": SAMPLE_PROJECT_PATH})
assert add_result.get("success") is True
job_id = add_result.get("job_id")
assert job_id is not None
while True:
status_result = call_tool(server_process, "check_job_status", {"job_id": job_id})
if status_result.get("job", {}).get("status") == "completed":
break
time.sleep(2)
list_result = call_tool(server_process, "list_indexed_repositories", {})
assert list_result.get("success") is True
assert SAMPLE_PROJECT_PATH in [repo["path"] for repo in list_result.get("repositories", [])]
finally:
print("--- Shutting down server and Neo4j container ---")
if server_process:
server_process.terminate()
server_process.wait()
run_command(["docker", "compose", "-f", compose_file, "down"])
if os.path.exists(env_path):
os.remove(env_path)
if os.path.exists(compose_file):
os.remove(compose_file)
```
--------------------------------------------------------------------------------
/website/src/components/DemoSection.tsx:
--------------------------------------------------------------------------------
```typescript
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
import { motion } from "framer-motion";
import graphTotalImage from "../assets/graph-total.png";
import functionCallsImage from "../assets/function-calls.png";
import hierarchyImage from "../assets/hierarchy.png";
import type { Variants } from "framer-motion";
const DemoSection = () => {
const visualizations = [
{
title: "Complete Code Graph",
description: "All components and relationships between code elements.",
image: graphTotalImage,
badge: "Full Overview",
aos: "fade-up",
},
{
title: "Function Call Analysis",
description: "Direct and indirect function calls across directories.",
image: functionCallsImage,
badge: "Call Chains",
aos: "zoom-in",
},
{
title: "Project Hierarchy",
description: "Hierarchical structure of files and dependencies.",
image: hierarchyImage,
badge: "File Structure",
aos: "flip-up",
},
];
const containerVariants: Variants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: { staggerChildren: 0.2, delayChildren: 0.1 },
},
};
const itemVariants: Variants = {
hidden: { y: 20, opacity: 0 },
visible: {
y: 0,
opacity: 1,
transition: { duration: 0.6, ease: "easeOut" },
},
};
return (
<section
className="py-20 px-4 bg-gradient-to-b from-background to-secondary/10"
data-aos="fade-in"
data-aos-duration="800"
>
<div className="container mx-auto max-w-7xl">
{/* Heading Section */}
<motion.div
className="text-center mb-16"
initial={{ opacity: 0, y: -20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, amount: 0.5 }}
transition={{ duration: 0.7 }}
>
<h2
className="text-3xl sm:text-4xl md:text-5xl font-bold mb-6 bg-gradient-to-r from-primary via-primary to-accent bg-clip-text text-transparent py-2"
data-aos="fade-down"
data-aos-duration="1000"
>
See CodeGraphContext in Action
</h2>
<p
className="text-xl text-muted-foreground max-w-3xl mx-auto mb-12"
data-aos="fade-up"
data-aos-delay="200"
>
Watch how CodeGraphContext transforms complex codebases into
interactive knowledge graphs.
</p>
</motion.div>
{/* Embedded Demo Video */}
<motion.div
className="max-w-4xl mx-auto mb-16"
initial={{ opacity: 0, scale: 0.9 }}
whileInView={{ opacity: 1, scale: 1 }}
viewport={{ once: true, amount: 0.3 }}
transition={{ duration: 0.8, ease: "easeInOut" }}
data-aos="zoom-in"
>
<div className="relative aspect-video rounded-lg overflow-hidden shadow-2xl border border-border/50">
<iframe
src="https://www.youtube.com/embed/KYYSdxhg1xU?autoplay=1&mute=1&loop=1&playlist=KYYSdxhg1xU"
title="CodeGraphContext Demo"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
className="w-full h-full"
/>
</div>
</motion.div>
{/* Interactive Visualizations Section */}
<div className="mb-12">
<h3
className="text-3xl font-bold text-center mb-8"
data-aos="fade-up"
data-aos-delay="100"
>
Interactive Visualizations
</h3>
<motion.div
className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"
variants={containerVariants}
initial="hidden"
whileInView="visible"
viewport={{ once: true, amount: 0.2 }}
>
{visualizations.map((viz, index) => (
<motion.div
key={index}
variants={itemVariants}
data-aos={viz.aos}
data-aos-delay={index * 150}
>
<Card className="group hover:shadow-xl transition-all duration-300 border-border/50 overflow-hidden w-full h-full bg-background/70 backdrop-blur-sm">
<Dialog>
<DialogTrigger asChild>
<div className="relative cursor-pointer flex flex-col h-full">
<div className="relative">
<img
src={viz.image}
alt={viz.title}
className="w-full h-48 object-cover group-hover:scale-105 transition-transform duration-300"
loading="lazy"
/>
<Badge className="absolute top-2 left-2 text-xs">
{viz.badge}
</Badge>
</div>
<CardContent className="p-6 flex-grow flex flex-col">
<h4 className="text-xl font-semibold mb-3 group-hover:text-primary transition-colors">
{viz.title}
</h4>
<p className="text-base text-muted-foreground flex-grow">
{viz.description}
</p>
</CardContent>
</div>
</DialogTrigger>
{/* Dialog Content */}
<DialogContent className="max-w-5xl w-full">
<img
src={viz.image}
alt={`${viz.title} Visualization`}
className="w-full h-auto max-h-[80vh] object-contain rounded-lg"
/>
</DialogContent>
</Dialog>
</Card>
</motion.div>
))}
</motion.div>
</div>
</div>
</section>
);
};
export default DemoSection;
```
--------------------------------------------------------------------------------
/tests/sample_project_rust/src/structs_enums.rs:
--------------------------------------------------------------------------------
```rust
// structs_enums.rs - Demonstrates Rust structs and enums
use std::fmt;
/// Basic struct with public fields
#[derive(Debug, Clone, PartialEq)]
pub struct Person {
pub name: String,
pub age: u32,
}
/// Struct with private fields
#[derive(Debug)]
pub struct BankAccount {
balance: f64,
account_number: String,
}
/// Tuple struct
#[derive(Debug, Clone, Copy)]
pub struct Point(pub i32, pub i32);
/// Unit struct
#[derive(Debug)]
pub struct Unit;
/// Struct with lifetime parameter
#[derive(Debug)]
pub struct BookReference<'a> {
title: &'a str,
author: &'a str,
}
/// Generic struct
#[derive(Debug)]
pub struct Container<T> {
value: T,
}
impl Person {
/// Constructor function (associated function)
pub fn new(name: String, age: u32) -> Self {
Self { name, age }
}
/// Method with immutable self
pub fn greet(&self) -> String {
format!("Hello, my name is {} and I'm {} years old", self.name, self.age)
}
/// Method with mutable self
pub fn have_birthday(&mut self) {
self.age += 1;
}
/// Method consuming self
pub fn into_name(self) -> String {
self.name
}
/// Method returning reference
pub fn get_name(&self) -> &str {
&self.name
}
/// Associated function
pub fn default_person() -> Self {
Self {
name: String::from("Unknown"),
age: 0,
}
}
/// Method with additional parameters
pub fn is_older_than(&self, other: &Person) -> bool {
self.age > other.age
}
}
impl BankAccount {
pub fn new(account_number: String, initial_balance: f64) -> Self {
Self {
balance: initial_balance,
account_number,
}
}
pub fn deposit(&mut self, amount: f64) -> Result<(), String> {
if amount <= 0.0 {
return Err("Deposit amount must be positive".to_string());
}
self.balance += amount;
Ok(())
}
pub fn withdraw(&mut self, amount: f64) -> Result<(), String> {
if amount <= 0.0 {
return Err("Withdrawal amount must be positive".to_string());
}
if amount > self.balance {
return Err("Insufficient funds".to_string());
}
self.balance -= amount;
Ok(())
}
pub fn get_balance(&self) -> f64 {
self.balance
}
}
impl Point {
pub fn new(x: i32, y: i32) -> Self {
Point(x, y)
}
pub fn distance_from_origin(&self) -> f64 {
((self.0.pow(2) + self.1.pow(2)) as f64).sqrt()
}
pub fn translate(&mut self, dx: i32, dy: i32) {
self.0 += dx;
self.1 += dy;
}
}
impl<T> Container<T> {
pub fn new(value: T) -> Self {
Self { value }
}
pub fn get(&self) -> &T {
&self.value
}
pub fn set(&mut self, value: T) {
self.value = value;
}
pub fn into_inner(self) -> T {
self.value
}
}
// Enums
/// Simple enum
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Status {
Active,
Inactive,
Pending,
}
/// Enum with data
#[derive(Debug, Clone, PartialEq)]
pub enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(u8, u8, u8),
}
/// Result-like enum
#[derive(Debug)]
pub enum MyResult<T, E> {
Ok(T),
Err(E),
}
/// Option-like enum
#[derive(Debug)]
pub enum MyOption<T> {
Some(T),
None,
}
/// Enum with methods
#[derive(Debug, Clone)]
pub enum TrafficLight {
Red,
Yellow,
Green,
}
impl TrafficLight {
pub fn duration(&self) -> u32 {
match self {
TrafficLight::Red => 60,
TrafficLight::Yellow => 10,
TrafficLight::Green => 50,
}
}
pub fn next(&self) -> TrafficLight {
match self {
TrafficLight::Red => TrafficLight::Green,
TrafficLight::Yellow => TrafficLight::Red,
TrafficLight::Green => TrafficLight::Yellow,
}
}
}
impl Message {
pub fn call(&self) {
match self {
Message::Quit => println!("Quitting"),
Message::Move { x, y } => println!("Moving to ({}, {})", x, y),
Message::Write(text) => println!("Writing: {}", text),
Message::ChangeColor(r, g, b) => println!("Changing color to RGB({}, {}, {})", r, g, b),
}
}
}
/// Pattern matching with enums
pub fn process_message(msg: Message) -> String {
match msg {
Message::Quit => "Quit command".to_string(),
Message::Move { x, y } if x > 0 && y > 0 => format!("Moving to positive quadrant: ({}, {})", x, y),
Message::Move { x, y } => format!("Moving to: ({}, {})", x, y),
Message::Write(text) => format!("Text: {}", text),
Message::ChangeColor(r, g, b) => format!("Color: RGB({}, {}, {})", r, g, b),
}
}
/// Enum with tuple variants
#[derive(Debug)]
pub enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
impl IpAddr {
pub fn is_loopback(&self) -> bool {
match self {
IpAddr::V4(127, 0, 0, 1) => true,
IpAddr::V6(s) if s == "::1" => true,
_ => false,
}
}
}
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Person {{ name: {}, age: {} }}", self.name, self.age)
}
}
impl fmt::Display for Status {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Status::Active => write!(f, "Active"),
Status::Inactive => write!(f, "Inactive"),
Status::Pending => write!(f, "Pending"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_person_creation() {
let person = Person::new("Alice".to_string(), 30);
assert_eq!(person.name, "Alice");
assert_eq!(person.age, 30);
}
#[test]
fn test_person_birthday() {
let mut person = Person::new("Bob".to_string(), 25);
person.have_birthday();
assert_eq!(person.age, 26);
}
#[test]
fn test_message_matching() {
let msg = Message::Move { x: 10, y: 20 };
let result = process_message(msg);
assert!(result.contains("Moving"));
}
}
```
--------------------------------------------------------------------------------
/website/src/components/ui/carousel.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import useEmblaCarousel, { type UseEmblaCarouselType } from "embla-carousel-react";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
type CarouselApi = UseEmblaCarouselType[1];
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>;
type CarouselOptions = UseCarouselParameters[0];
type CarouselPlugin = UseCarouselParameters[1];
type CarouselProps = {
opts?: CarouselOptions;
plugins?: CarouselPlugin;
orientation?: "horizontal" | "vertical";
setApi?: (api: CarouselApi) => void;
};
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0];
api: ReturnType<typeof useEmblaCarousel>[1];
scrollPrev: () => void;
scrollNext: () => void;
canScrollPrev: boolean;
canScrollNext: boolean;
} & CarouselProps;
const CarouselContext = React.createContext<CarouselContextProps | null>(null);
function useCarousel() {
const context = React.useContext(CarouselContext);
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />");
}
return context;
}
const Carousel = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement> & CarouselProps>(
({ orientation = "horizontal", opts, setApi, plugins, className, children, ...props }, ref) => {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins,
);
const [canScrollPrev, setCanScrollPrev] = React.useState(false);
const [canScrollNext, setCanScrollNext] = React.useState(false);
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) {
return;
}
setCanScrollPrev(api.canScrollPrev());
setCanScrollNext(api.canScrollNext());
}, []);
const scrollPrev = React.useCallback(() => {
api?.scrollPrev();
}, [api]);
const scrollNext = React.useCallback(() => {
api?.scrollNext();
}, [api]);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
scrollPrev();
} else if (event.key === "ArrowRight") {
event.preventDefault();
scrollNext();
}
},
[scrollPrev, scrollNext],
);
React.useEffect(() => {
if (!api || !setApi) {
return;
}
setApi(api);
}, [api, setApi]);
React.useEffect(() => {
if (!api) {
return;
}
onSelect(api);
api.on("reInit", onSelect);
api.on("select", onSelect);
return () => {
api?.off("select", onSelect);
};
}, [api, onSelect]);
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation: orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
},
);
Carousel.displayName = "Carousel";
const CarouselContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel();
return (
<div ref={carouselRef} className="overflow-hidden">
<div
ref={ref}
className={cn("flex", orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col", className)}
{...props}
/>
</div>
);
},
);
CarouselContent.displayName = "CarouselContent";
const CarouselItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
const { orientation } = useCarousel();
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn("min-w-0 shrink-0 grow-0 basis-full", orientation === "horizontal" ? "pl-4" : "pt-4", className)}
{...props}
/>
);
},
);
CarouselItem.displayName = "CarouselItem";
const CarouselPrevious = React.forwardRef<HTMLButtonElement, React.ComponentProps<typeof Button>>(
({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
);
},
);
CarouselPrevious.displayName = "CarouselPrevious";
const CarouselNext = React.forwardRef<HTMLButtonElement, React.ComponentProps<typeof Button>>(
({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
);
},
);
CarouselNext.displayName = "CarouselNext";
export { type CarouselApi, Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext };
```
--------------------------------------------------------------------------------
/tests/sample_project_go/generics.go:
--------------------------------------------------------------------------------
```go
// generics.go - Demonstrates Go generics (Go 1.18+)
package main
import (
"fmt"
"golang.org/x/exp/constraints"
)
// GenericMax returns the maximum of two values
func GenericMax[T constraints.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
// GenericMin returns the minimum of two values
func GenericMin[T constraints.Ordered](a, b T) T {
if a < b {
return a
}
return b
}
// Stack is a generic stack data structure
type Stack[T any] struct {
items []T
}
// Push adds an item to the stack
func (s *Stack[T]) Push(item T) {
s.items = append(s.items, item)
}
// Pop removes and returns the top item
func (s *Stack[T]) Pop() (T, bool) {
if len(s.items) == 0 {
var zero T
return zero, false
}
item := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return item, true
}
// Peek returns the top item without removing it
func (s *Stack[T]) Peek() (T, bool) {
if len(s.items) == 0 {
var zero T
return zero, false
}
return s.items[len(s.items)-1], true
}
// IsEmpty returns true if stack is empty
func (s *Stack[T]) IsEmpty() bool {
return len(s.items) == 0
}
// Size returns the number of items in the stack
func (s *Stack[T]) Size() int {
return len(s.items)
}
// Queue is a generic queue data structure
type Queue[T any] struct {
items []T
}
// Enqueue adds an item to the queue
func (q *Queue[T]) Enqueue(item T) {
q.items = append(q.items, item)
}
// Dequeue removes and returns the first item
func (q *Queue[T]) Dequeue() (T, bool) {
if len(q.items) == 0 {
var zero T
return zero, false
}
item := q.items[0]
q.items = q.items[1:]
return item, true
}
// Map applies a function to each element
func Map[T any, U any](items []T, fn func(T) U) []U {
result := make([]U, len(items))
for i, item := range items {
result[i] = fn(item)
}
return result
}
// Filter filters items based on a predicate
func Filter[T any](items []T, predicate func(T) bool) []T {
var result []T
for _, item := range items {
if predicate(item) {
result = append(result, item)
}
}
return result
}
// Reduce reduces a slice to a single value
func Reduce[T any, U any](items []T, initial U, fn func(U, T) U) U {
result := initial
for _, item := range items {
result = fn(result, item)
}
return result
}
// Contains checks if a slice contains an item
func Contains[T comparable](items []T, target T) bool {
for _, item := range items {
if item == target {
return true
}
}
return false
}
// Pair is a generic pair type
type Pair[T any, U any] struct {
First T
Second U
}
// NewPair creates a new pair
func NewPair[T any, U any](first T, second U) Pair[T, U] {
return Pair[T, U]{First: first, Second: second}
}
// Swap swaps the values in a pair
func (p Pair[T, U]) Swap() Pair[U, T] {
return Pair[U, T]{First: p.Second, Second: p.First}
}
// LinkedListNode is a generic linked list node
type LinkedListNode[T any] struct {
Value T
Next *LinkedListNode[T]
}
// LinkedList is a generic linked list
type LinkedList[T any] struct {
Head *LinkedListNode[T]
Tail *LinkedListNode[T]
size int
}
// Append adds a value to the end of the list
func (ll *LinkedList[T]) Append(value T) {
node := &LinkedListNode[T]{Value: value}
if ll.Head == nil {
ll.Head = node
ll.Tail = node
} else {
ll.Tail.Next = node
ll.Tail = node
}
ll.size++
}
// Prepend adds a value to the beginning of the list
func (ll *LinkedList[T]) Prepend(value T) {
node := &LinkedListNode[T]{Value: value, Next: ll.Head}
ll.Head = node
if ll.Tail == nil {
ll.Tail = node
}
ll.size++
}
// ToSlice converts the linked list to a slice
func (ll *LinkedList[T]) ToSlice() []T {
result := make([]T, 0, ll.size)
current := ll.Head
for current != nil {
result = append(result, current.Value)
current = current.Next
}
return result
}
// Number constraint for numeric types
type Number interface {
constraints.Integer | constraints.Float
}
// Sum calculates the sum of numbers
func Sum[T Number](numbers []T) T {
var sum T
for _, num := range numbers {
sum += num
}
return sum
}
// Average calculates the average of numbers
func Average[T Number](numbers []T) float64 {
if len(numbers) == 0 {
return 0
}
total := Sum(numbers)
return float64(total) / float64(len(numbers))
}
// Cache is a generic cache with type constraints
type Cache[K comparable, V any] struct {
data map[K]V
}
// NewCache creates a new cache
func NewCache[K comparable, V any]() *Cache[K, V] {
return &Cache[K, V]{
data: make(map[K]V),
}
}
// Set adds or updates a value in the cache
func (c *Cache[K, V]) Set(key K, value V) {
c.data[key] = value
}
// Get retrieves a value from the cache
func (c *Cache[K, V]) Get(key K) (V, bool) {
value, ok := c.data[key]
return value, ok
}
// Delete removes a value from the cache
func (c *Cache[K, V]) Delete(key K) {
delete(c.data, key)
}
// Keys returns all keys in the cache
func (c *Cache[K, V]) Keys() []K {
keys := make([]K, 0, len(c.data))
for k := range c.data {
keys = append(keys, k)
}
return keys
}
// FindFirst returns the first item matching the predicate
func FindFirst[T any](items []T, predicate func(T) bool) (T, bool) {
for _, item := range items {
if predicate(item) {
return item, true
}
}
var zero T
return zero, false
}
// GroupBy groups items by a key function
func GroupBy[T any, K comparable](items []T, keyFn func(T) K) map[K][]T {
result := make(map[K][]T)
for _, item := range items {
key := keyFn(item)
result[key] = append(result[key], item)
}
return result
}
func demonstrateGenerics() {
// Generic functions
fmt.Println("Max:", GenericMax(10, 20))
fmt.Println("Max:", GenericMax(3.14, 2.71))
// Generic stack
stack := Stack[int]{}
stack.Push(1)
stack.Push(2)
stack.Push(3)
val, _ := stack.Pop()
fmt.Println("Popped:", val)
// Generic map/filter/reduce
numbers := []int{1, 2, 3, 4, 5}
doubled := Map(numbers, func(n int) int { return n * 2 })
fmt.Println("Doubled:", doubled)
evens := Filter(numbers, func(n int) bool { return n%2 == 0 })
fmt.Println("Evens:", evens)
sum := Reduce(numbers, 0, func(acc, n int) int { return acc + n })
fmt.Println("Sum:", sum)
// Generic cache
cache := NewCache[string, int]()
cache.Set("age", 30)
age, _ := cache.Get("age")
fmt.Println("Age:", age)
}
```
--------------------------------------------------------------------------------
/tests/sample_project_go/embedded_composition.go:
--------------------------------------------------------------------------------
```go
// embedded_composition.go - Demonstrates Go embedding and composition
package main
import "fmt"
// Base is a base struct
type Base struct {
ID int
Name string
}
// GetID returns the ID
func (b Base) GetID() int {
return b.ID
}
// GetName returns the name
func (b Base) GetName() string {
return b.Name
}
// Describe provides a description
func (b Base) Describe() string {
return fmt.Sprintf("Base{ID: %d, Name: %s}", b.ID, b.Name)
}
// Extended embeds Base and adds functionality
type Extended struct {
Base
Extra string
}
// Describe overrides the Base method
func (e Extended) Describe() string {
return fmt.Sprintf("Extended{ID: %d, Name: %s, Extra: %s}", e.ID, e.Name, e.Extra)
}
// GetExtra returns the extra field
func (e Extended) GetExtra() string {
return e.Extra
}
// Address represents a physical address
type Address struct {
Street string
City string
ZipCode string
}
// FullAddress returns formatted address
func (a Address) FullAddress() string {
return fmt.Sprintf("%s, %s %s", a.Street, a.City, a.ZipCode)
}
// ContactInfo has contact details
type ContactInfo struct {
Email string
Phone string
}
// GetContact returns contact string
func (c ContactInfo) GetContact() string {
return fmt.Sprintf("Email: %s, Phone: %s", c.Email, c.Phone)
}
// Customer embeds multiple structs
type Customer struct {
Base
Address
ContactInfo
LoyaltyPoints int
}
// NewCustomer creates a new customer
func NewCustomer(id int, name, email string) *Customer {
return &Customer{
Base: Base{
ID: id,
Name: name,
},
ContactInfo: ContactInfo{
Email: email,
},
}
}
// GetFullInfo returns all customer info
func (c Customer) GetFullInfo() string {
return fmt.Sprintf("%s | %s | Points: %d",
c.Describe(), c.GetContact(), c.LoyaltyPoints)
}
// Logger provides logging functionality
type Logger interface {
Log(message string)
}
// ConsoleLogger logs to console
type ConsoleLogger struct {
Prefix string
}
// Log implements Logger interface
func (cl ConsoleLogger) Log(message string) {
fmt.Printf("[%s] %s\n", cl.Prefix, message)
}
// Service embeds a logger
type Service struct {
Logger
Name string
}
// Execute performs service action
func (s Service) Execute() {
s.Log(fmt.Sprintf("Executing service: %s", s.Name))
}
// Timestamper adds timestamp functionality
type Timestamper struct {
timestamp string
}
// SetTimestamp sets the timestamp
func (t *Timestamper) SetTimestamp(ts string) {
t.timestamp = ts
}
// GetTimestamp gets the timestamp
func (t Timestamper) GetTimestamp() string {
return t.timestamp
}
// Versioned adds version tracking
type Versioned struct {
Version int
}
// IncrementVersion increases version
func (v *Versioned) IncrementVersion() {
v.Version++
}
// GetVersion returns the version
func (v Versioned) GetVersion() int {
return v.Version
}
// Document combines multiple embedded types
type Document struct {
Timestamper
Versioned
Content string
Author string
}
// Update updates the document
func (d *Document) Update(content string) {
d.Content = content
d.IncrementVersion()
}
// GetInfo returns document info
func (d Document) GetInfo() string {
return fmt.Sprintf("Version %d by %s at %s",
d.GetVersion(), d.Author, d.GetTimestamp())
}
// Reader interface
type Reader interface {
Read() string
}
// Writer interface
type Writer interface {
Write(data string) error
}
// ReadWriter combines interfaces
type ReadWriter interface {
Reader
Writer
}
// FileHandler implements ReadWriter
type FileHandler struct {
Filename string
buffer string
}
// Read implements Reader
func (fh FileHandler) Read() string {
return fh.buffer
}
// Write implements Writer
func (fh *FileHandler) Write(data string) error {
fh.buffer = data
return nil
}
// BufferedHandler embeds FileHandler
type BufferedHandler struct {
FileHandler
BufferSize int
}
// Flush clears the buffer
func (bh *BufferedHandler) Flush() {
bh.buffer = ""
}
// Engine represents an engine
type Engine struct {
Horsepower int
Type string
}
// Start starts the engine
func (e Engine) Start() string {
return fmt.Sprintf("Starting %s engine with %d HP", e.Type, e.Horsepower)
}
// Wheels represents wheels
type Wheels struct {
Count int
Size int
}
// Roll makes wheels roll
func (w Wheels) Roll() string {
return fmt.Sprintf("Rolling on %d wheels of size %d", w.Count, w.Size)
}
// Car composes Engine and Wheels
type Car struct {
Engine
Wheels
Make string
Model string
}
// Drive drives the car
func (c Car) Drive() string {
return fmt.Sprintf("%s %s: %s, %s",
c.Make, c.Model, c.Start(), c.Roll())
}
// Metadata provides common metadata
type Metadata struct {
CreatedBy string
Tags []string
}
// AddTag adds a tag
func (m *Metadata) AddTag(tag string) {
m.Tags = append(m.Tags, tag)
}
// GetTags returns all tags
func (m Metadata) GetTags() []string {
return m.Tags
}
// Article combines content and metadata
type Article struct {
Metadata
Title string
Body string
}
// Summary returns article summary
func (a Article) Summary() string {
return fmt.Sprintf("'%s' by %s [%d tags]",
a.Title, a.CreatedBy, len(a.Tags))
}
// ConflictExample shows field name conflicts
type ConflictExample struct {
Base
Extended
}
// AccessConflict demonstrates accessing conflicting fields
func (c ConflictExample) AccessConflict() string {
// Need to specify which embedded type's field to access
return fmt.Sprintf("Base Name: %s, Extended Name: %s",
c.Base.Name, c.Extended.Name)
}
func demonstrateComposition() {
// Basic embedding
extended := Extended{
Base: Base{ID: 1, Name: "Test"},
Extra: "Additional",
}
fmt.Println(extended.Describe())
fmt.Println(extended.GetID()) // Promoted method from Base
// Multiple embedding
customer := NewCustomer(100, "John Doe", "[email protected]")
customer.Street = "123 Main St"
customer.City = "NYC"
customer.Phone = "555-1234"
fmt.Println(customer.GetFullInfo())
// Interface embedding
service := Service{
Logger: ConsoleLogger{Prefix: "SVC"},
Name: "DataProcessor",
}
service.Execute()
// Composition
car := Car{
Engine: Engine{Horsepower: 300, Type: "V8"},
Wheels: Wheels{Count: 4, Size: 18},
Make: "Tesla",
Model: "Model S",
}
fmt.Println(car.Drive())
}
```
--------------------------------------------------------------------------------
/tests/sample_project_go/error_handling.go:
--------------------------------------------------------------------------------
```go
// error_handling.go - Demonstrates Go error handling patterns
package main
import (
"errors"
"fmt"
"io"
"os"
"strconv"
)
// CustomError is a custom error type
type CustomError struct {
Code int
Message string
}
// Error implements error interface for CustomError
func (e *CustomError) Error() string {
return fmt.Sprintf("Error %d: %s", e.Code, e.Message)
}
// ValidationError represents validation failures
type ValidationError struct {
Field string
Value interface{}
Issue string
}
// Error implements error interface for ValidationError
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation failed for field '%s' with value '%v': %s",
e.Field, e.Value, e.Issue)
}
// NewCustomError creates a new custom error
func NewCustomError(code int, message string) error {
return &CustomError{Code: code, Message: message}
}
// BasicErrorReturn demonstrates simple error return
func BasicErrorReturn(x int) (int, error) {
if x < 0 {
return 0, errors.New("negative number not allowed")
}
return x * 2, nil
}
// ErrorWithFormatting uses fmt.Errorf
func ErrorWithFormatting(name string, age int) error {
if age < 0 {
return fmt.Errorf("invalid age %d for person %s", age, name)
}
if name == "" {
return fmt.Errorf("name cannot be empty")
}
return nil
}
// MultipleErrorChecks demonstrates multiple error checks
func MultipleErrorChecks(a, b int) (int, error) {
if a < 0 {
return 0, errors.New("first parameter cannot be negative")
}
if b == 0 {
return 0, errors.New("second parameter cannot be zero")
}
if a > 1000 {
return 0, errors.New("first parameter too large")
}
return a / b, nil
}
// ErrorWrapping demonstrates error wrapping (Go 1.13+)
func ErrorWrapping(filename string) error {
if filename == "" {
return fmt.Errorf("filename is empty")
}
_, err := os.Open(filename)
if err != nil {
return fmt.Errorf("failed to open file %s: %w", filename, err)
}
return nil
}
// ValidateUser validates user data
func ValidateUser(username string, age int) error {
if len(username) < 3 {
return &ValidationError{
Field: "username",
Value: username,
Issue: "must be at least 3 characters",
}
}
if age < 18 {
return &ValidationError{
Field: "age",
Value: age,
Issue: "must be 18 or older",
}
}
return nil
}
// ParseAndValidate demonstrates error handling chain
func ParseAndValidate(input string) (int, error) {
value, err := strconv.Atoi(input)
if err != nil {
return 0, fmt.Errorf("failed to parse input: %w", err)
}
if value < 0 {
return 0, NewCustomError(400, "value must be non-negative")
}
if value > 100 {
return 0, NewCustomError(400, "value must not exceed 100")
}
return value, nil
}
// ErrorTypeAssertion demonstrates error type checking
func ErrorTypeAssertion(err error) string {
if err == nil {
return "no error"
}
// Type assertion for custom error
if customErr, ok := err.(*CustomError); ok {
return fmt.Sprintf("Custom error with code: %d", customErr.Code)
}
// Type assertion for validation error
if valErr, ok := err.(*ValidationError); ok {
return fmt.Sprintf("Validation error on field: %s", valErr.Field)
}
return "unknown error type"
}
// ErrorsIs demonstrates errors.Is (Go 1.13+)
func ErrorsIs(err error) bool {
return errors.Is(err, io.EOF)
}
// ErrorsAs demonstrates errors.As (Go 1.13+)
func ErrorsAs(err error) (*CustomError, bool) {
var customErr *CustomError
if errors.As(err, &customErr) {
return customErr, true
}
return nil, false
}
// DeferredErrorHandling demonstrates defer with error handling
func DeferredErrorHandling(filename string) (err error) {
file, err := os.Open(filename)
if err != nil {
return fmt.Errorf("cannot open file: %w", err)
}
defer func() {
if closeErr := file.Close(); closeErr != nil {
if err != nil {
err = fmt.Errorf("close error: %v (original error: %w)", closeErr, err)
} else {
err = closeErr
}
}
}()
// Do something with file
_, err = file.Read(make([]byte, 100))
if err != nil && err != io.EOF {
return fmt.Errorf("read error: %w", err)
}
return nil
}
// SentinelErrors demonstrates sentinel error pattern
var (
ErrNotFound = errors.New("not found")
ErrUnauthorized = errors.New("unauthorized")
ErrForbidden = errors.New("forbidden")
)
// FindUser demonstrates sentinel error usage
func FindUser(id int) (string, error) {
if id < 0 {
return "", ErrNotFound
}
if id > 1000 {
return "", ErrUnauthorized
}
return fmt.Sprintf("user_%d", id), nil
}
// HandleUserError demonstrates handling sentinel errors
func HandleUserError(id int) string {
user, err := FindUser(id)
if err != nil {
if errors.Is(err, ErrNotFound) {
return "User not found"
}
if errors.Is(err, ErrUnauthorized) {
return "Unauthorized access"
}
return "Unknown error"
}
return user
}
// PanicToError converts panic to error
func PanicToError() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered from panic: %v", r)
}
}()
panic("something went wrong")
}
// ChainedValidation demonstrates chained error checks
func ChainedValidation(data map[string]interface{}) error {
if err := validateName(data); err != nil {
return fmt.Errorf("name validation: %w", err)
}
if err := validateAge(data); err != nil {
return fmt.Errorf("age validation: %w", err)
}
if err := validateEmail(data); err != nil {
return fmt.Errorf("email validation: %w", err)
}
return nil
}
func validateName(data map[string]interface{}) error {
name, ok := data["name"].(string)
if !ok || name == "" {
return errors.New("name is required")
}
return nil
}
func validateAge(data map[string]interface{}) error {
age, ok := data["age"].(int)
if !ok || age < 0 {
return errors.New("valid age is required")
}
return nil
}
func validateEmail(data map[string]interface{}) error {
email, ok := data["email"].(string)
if !ok || email == "" {
return errors.New("email is required")
}
return nil
}
func demonstrateErrors() {
// Test basic error
_, err := BasicErrorReturn(-1)
if err != nil {
fmt.Println("Error:", err)
}
// Test custom error
err = NewCustomError(404, "Resource not found")
fmt.Println(ErrorTypeAssertion(err))
// Test validation error
err = ValidateUser("ab", 15)
fmt.Println(err)
}
```
--------------------------------------------------------------------------------
/tests/sample_project_rust/src/traits.rs:
--------------------------------------------------------------------------------
```rust
// traits.rs - Demonstrates Rust traits and trait implementations
use std::fmt;
use std::ops::Add;
/// Basic trait definition
pub trait Describable {
fn describe(&self) -> String;
}
/// Trait with default implementation
pub trait Greetable {
fn greet(&self) -> String {
"Hello!".to_string()
}
fn formal_greet(&self) -> String;
}
/// Trait with associated types
pub trait Container {
type Item;
fn add(&mut self, item: Self::Item);
fn get(&self, index: usize) -> Option<&Self::Item>;
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// Trait with associated constants
pub trait MathConstants {
const PI: f64;
const E: f64;
}
/// Trait for conversion
pub trait FromString {
fn from_string(s: &str) -> Result<Self, String>
where
Self: Sized;
}
/// Marker trait (empty trait)
pub trait Serializable {}
// Struct definitions
#[derive(Debug, Clone)]
pub struct Rectangle {
pub width: f64,
pub height: f64,
}
#[derive(Debug, Clone)]
pub struct Circle {
pub radius: f64,
}
#[derive(Debug, Clone)]
pub struct Triangle {
pub a: f64,
pub b: f64,
pub c: f64,
}
#[derive(Debug)]
pub struct Student {
pub name: String,
pub grade: u32,
}
#[derive(Debug)]
pub struct Teacher {
pub name: String,
pub subject: String,
}
// Trait implementations
impl Describable for Rectangle {
fn describe(&self) -> String {
format!("Rectangle with width {} and height {}", self.width, self.height)
}
}
impl Describable for Circle {
fn describe(&self) -> String {
format!("Circle with radius {}", self.radius)
}
}
impl Describable for Triangle {
fn describe(&self) -> String {
format!("Triangle with sides {}, {}, {}", self.a, self.b, self.c)
}
}
impl Greetable for Student {
fn formal_greet(&self) -> String {
format!("Good day, student {}", self.name)
}
}
impl Greetable for Teacher {
fn greet(&self) -> String {
format!("Hello, I'm {}", self.name)
}
fn formal_greet(&self) -> String {
format!("Good day, Professor {}", self.name)
}
}
// Trait for area calculation
pub trait Area {
fn area(&self) -> f64;
}
impl Area for Rectangle {
fn area(&self) -> f64 {
self.width * self.height
}
}
impl Area for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
impl Area for Triangle {
fn area(&self) -> f64 {
// Heron's formula
let s = (self.a + self.b + self.c) / 2.0;
(s * (s - self.a) * (s - self.b) * (s - self.c)).sqrt()
}
}
// Trait for perimeter calculation
pub trait Perimeter {
fn perimeter(&self) -> f64;
}
impl Perimeter for Rectangle {
fn perimeter(&self) -> f64 {
2.0 * (self.width + self.height)
}
}
impl Perimeter for Circle {
fn perimeter(&self) -> f64 {
2.0 * std::f64::consts::PI * self.radius
}
}
impl Perimeter for Triangle {
fn perimeter(&self) -> f64 {
self.a + self.b + self.c
}
}
// Generic functions using traits
/// Function accepting any type implementing Describable
pub fn print_description<T: Describable>(item: &T) {
println!("{}", item.describe());
}
/// Function with multiple trait bounds
pub fn print_area_and_perimeter<T: Area + Perimeter>(shape: &T) {
println!("Area: {}, Perimeter: {}", shape.area(), shape.perimeter());
}
/// Function with where clause
pub fn compare_areas<T, U>(shape1: &T, shape2: &U) -> bool
where
T: Area,
U: Area,
{
shape1.area() > shape2.area()
}
/// Function returning impl Trait
pub fn create_circle(radius: f64) -> impl Area + Perimeter {
Circle { radius }
}
/// Generic struct with trait bounds
#[derive(Debug)]
pub struct Pair<T> {
first: T,
second: T,
}
impl<T> Pair<T> {
pub fn new(first: T, second: T) -> Self {
Self { first, second }
}
}
impl<T: PartialOrd> Pair<T> {
pub fn max(&self) -> &T {
if self.first > self.second {
&self.first
} else {
&self.second
}
}
}
impl<T: Clone> Pair<T> {
pub fn clone_first(&self) -> T {
self.first.clone()
}
}
// Trait with supertraits
pub trait Shape: Area + Perimeter + fmt::Display {
fn name(&self) -> &str;
}
impl fmt::Display for Rectangle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Rectangle({}x{})", self.width, self.height)
}
}
impl Shape for Rectangle {
fn name(&self) -> &str {
"Rectangle"
}
}
// Trait object example
pub fn total_area(shapes: &[&dyn Area]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
// Associated type example
pub struct VecContainer<T> {
items: Vec<T>,
}
impl<T> Container for VecContainer<T> {
type Item = T;
fn add(&mut self, item: Self::Item) {
self.items.push(item);
}
fn get(&self, index: usize) -> Option<&Self::Item> {
self.items.get(index)
}
fn len(&self) -> usize {
self.items.len()
}
}
// Operator overloading using traits
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Point {
pub x: i32,
pub y: i32,
}
impl Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
// Trait for custom equality
pub trait CustomEq {
fn custom_eq(&self, other: &Self) -> bool;
}
impl CustomEq for Rectangle {
fn custom_eq(&self, other: &Self) -> bool {
(self.width * self.height - other.width * other.height).abs() < 0.001
}
}
// Blanket implementations
pub trait Summary {
fn summarize(&self) -> String;
}
impl<T: Describable> Summary for T {
fn summarize(&self) -> String {
format!("Summary: {}", self.describe())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_rectangle_area() {
let rect = Rectangle { width: 10.0, height: 5.0 };
assert_eq!(rect.area(), 50.0);
}
#[test]
fn test_circle_area() {
let circle = Circle { radius: 5.0 };
let area = circle.area();
assert!((area - 78.54).abs() < 0.01);
}
#[test]
fn test_point_add() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
let p3 = p1 + p2;
assert_eq!(p3, Point { x: 4, y: 6 });
}
}
```
--------------------------------------------------------------------------------
/tests/test_graph_indexing_js.py:
--------------------------------------------------------------------------------
```python
import pytest
import os
# Path to the sample JavaScript project used in tests
SAMPLE_JS_PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "sample_project_javascript"))
# ==============================================================================
# == EXPECTED RELATIONSHIPS
# ==============================================================================
EXPECTED_STRUCTURE = [
("functions.js", "regularFunction", "Function"),
("functions.js", "greetPerson", "Function"),
("functions.js", "functionExpression", "Function"),
("functions.js", "arrowFunction", "Function"),
("classes.js", "Person", "Class"),
("classes.js", "Employee", "Class"),
("classes.js", "BankAccount", "Class"),
("objects.js", "calculator", "Variable"),
]
EXPECTED_INHERITANCE = [
pytest.param("Employee", "classes.js", "Person", "classes.js", id="Employee inherits from Person"),
]
EXPECTED_CALLS = [
pytest.param("getData", "asyncAwait.js", None, "fetchData", "asyncAwait.js", None, id="asyncAwait.getData->fetchData", marks=pytest.mark.skip(reason="JS parser does not yet detect all call relationships.")),
pytest.param("orchestrator", "functions.js", None, "regularFunction", "functions.js", None, id="functions.orchestrator->regularFunction", marks=pytest.mark.skip(reason="JS parser does not yet detect all call relationships.")),
]
EXPECTED_IMPORTS = [
pytest.param("importer.js", "defaultExport", "exporter.js", "defaultExportedFunction", id="importer.js imports defaultExport", marks=pytest.mark.xfail(reason="Symbol-level import relationships are not yet implemented for JavaScript.")),
pytest.param("importer.js", "exportedFunction", "exporter.js", "exportedFunction", id="importer.js imports exportedFunction", marks=pytest.mark.xfail(reason="Symbol-level import relationships are not yet implemented for JavaScript.")),
pytest.param("importer.js", "ExportedClass", "exporter.js", "ExportedClass", id="importer.js imports ExportedClass", marks=pytest.mark.xfail(reason="Symbol-level import relationships are not yet implemented for JavaScript.")),
]
# ==============================================================================
# == TEST IMPLEMENTATIONS
# ==============================================================================
def check_query(graph, query, description):
"""Helper function to execute a Cypher query and assert that a match is found."""
try:
result = graph.query(query)
except Exception as e:
pytest.fail(f"Query failed for {description} with error: {e}\nQuery was:\n{query}")
assert result is not None, f"Query for {description} returned None.\nQuery was:\n{query}"
assert len(result) > 0, f"Query for {description} returned no records.\nQuery was:\n{query}"
assert result[0].get('count', 0) > 0, f"No match found for {description}.\nQuery was:\n{query}"
@pytest.mark.parametrize("file_name, item_name, item_label", EXPECTED_STRUCTURE)
def test_file_contains_item(graph, file_name, item_name, item_label):
"""Verifies that a File node correctly CONTAINS a Function or Class node."""
description = f"CONTAINS from [{file_name}] to [{item_name}]"
abs_file_path = os.path.join(SAMPLE_JS_PROJECT_PATH, file_name)
query = f"""
MATCH (f:File {{path: '{abs_file_path}'}})-[:CONTAINS]->(item:{item_label} {{name: '{item_name}'}})
RETURN count(*) AS count
"""
check_query(graph, query, description)
@pytest.mark.parametrize("child_name, child_file, parent_name, parent_file", EXPECTED_INHERITANCE)
def test_inheritance_relationship(graph, child_name, child_file, parent_name, parent_file):
"""Verifies that an INHERITS relationship exists between two classes."""
description = f"INHERITS from [{child_name}] to [{parent_name}]"
child_path = os.path.join(SAMPLE_JS_PROJECT_PATH, child_file)
parent_path = os.path.join(SAMPLE_JS_PROJECT_PATH, parent_file)
query = f"""
MATCH (child:Class {{name: '{child_name}', file_path: '{child_path}'}})-[:INHERITS]->(parent:Class {{name: '{parent_name}', file_path: '{parent_path}'}})
RETURN count(*) as count
"""
check_query(graph, query, description)
@pytest.mark.parametrize("caller_name, caller_file, caller_class, callee_name, callee_file, callee_class", EXPECTED_CALLS)
def test_function_call_relationship(graph, caller_name, caller_file, caller_class, callee_name, callee_file, callee_class):
"""Verifies that a CALLS relationship exists by checking for nodes first, then the relationship."""
caller_path = os.path.join(SAMPLE_JS_PROJECT_PATH, caller_file)
callee_path = os.path.join(SAMPLE_JS_PROJECT_PATH, callee_file)
if caller_class:
caller_match = f"(caller_class:Class {{name: '{caller_class}', file_path: '{caller_path}'}})-[:CONTAINS]->(caller:Function {{name: '{caller_name}'}})"
else:
caller_match = f"(caller:Function {{name: '{caller_name}', file_path: '{caller_path}'}})"
if callee_class:
callee_match = f"(callee_class:Class {{name: '{callee_class}', file_path: '{callee_path}'}})-[:CONTAINS]->(callee:Function {{name: '{callee_name}'}})"
else:
callee_match = f"(callee:Function {{name: '{callee_name}', file_path: '{callee_path}'}})"
relationship_description = f"CALLS from [{caller_name}] to [{callee_name}]"
relationship_query = f"""
MATCH {caller_match}
MATCH {callee_match}
MATCH (caller)-[:CALLS]->(callee)
RETURN count(*) as count
"""
check_query(graph, relationship_query, relationship_description)
@pytest.mark.parametrize("importing_file, imported_symbol_alias, exporting_file, original_symbol_name", EXPECTED_IMPORTS)
def test_import_relationship(graph, importing_file, imported_symbol_alias, exporting_file, original_symbol_name):
"""Verifies that a specific IMPORTS relationship exists between a file and a symbol from another file."""
description = f"IMPORTS from [{importing_file}] of symbol [{original_symbol_name}] as [{imported_symbol_alias}] from [{exporting_file}]"
importing_path = os.path.join(SAMPLE_JS_PROJECT_PATH, importing_file)
exporting_path = os.path.join(SAMPLE_JS_PROJECT_PATH, exporting_file)
# This query is designed to fail until the feature is implemented.
# It checks for a direct relationship between the importing file and the specific imported function/class.
query = f"""
MATCH (importer:File {{path: '{importing_path}'}})-[:IMPORTS]->(symbol:Node {{name: '{original_symbol_name}', file_path: '{exporting_path}'}})
RETURN count(*) as count
"""
check_query(graph, query, description)
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/objects.js:
--------------------------------------------------------------------------------
```javascript
/**
* Sample JavaScript file demonstrating object methods and function assignments
* This file tests methods defined in object literals and prototype assignments
*/
// Object with method definitions
const calculator = {
result: 0,
// Method shorthand syntax
add(value) {
this.result += value;
return this;
},
// Method shorthand syntax with parameters
subtract(value) {
this.result -= value;
return this;
},
// Traditional method definition
multiply: function(value) {
this.result *= value;
return this;
},
// Arrow function as method (note: 'this' behaves differently)
reset: () => {
// Note: Arrow functions don't have their own 'this'
console.log('Calculator reset');
},
// Method with complex logic
calculate(operation, value) {
switch (operation) {
case 'add':
return this.add(value);
case 'subtract':
return this.subtract(value);
case 'multiply':
return this.multiply(value);
default:
throw new Error('Unknown operation');
}
},
// Getter method
get value() {
return this.result;
},
// Setter method
set value(newValue) {
this.result = newValue;
}
};
// Object with nested methods
const api = {
baseUrl: 'https://api.example.com',
users: {
// Nested method
getAll() {
return fetch(`${this.baseUrl}/users`);
},
// Nested method with parameters
getById(id) {
return fetch(`${this.baseUrl}/users/${id}`);
},
// Async nested method
async create(userData) {
const response = await fetch(`${this.baseUrl}/users`, {
method: 'POST',
body: JSON.stringify(userData)
});
return response.json();
}
},
posts: {
getAll() {
return fetch(`${this.baseUrl}/posts`);
},
getByUserId(userId) {
return fetch(`${this.baseUrl}/posts?userId=${userId}`);
}
}
};
// Constructor function with prototype methods
function Vehicle(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
// Prototype method assignment
Vehicle.prototype.getInfo = function() {
return `${this.year} ${this.make} ${this.model}`;
};
// Another prototype method
Vehicle.prototype.start = function() {
console.log(`Starting ${this.getInfo()}`);
};
// Prototype method with parameters
Vehicle.prototype.drive = function(distance) {
console.log(`Driving ${this.getInfo()} for ${distance} miles`);
};
// Static method assignment to constructor function
Vehicle.createElectric = function(make, model, year, batteryCapacity) {
const vehicle = new Vehicle(make, model, year);
vehicle.batteryCapacity = batteryCapacity;
vehicle.charge = function(percentage) {
console.log(`Charging to ${percentage}%`);
};
return vehicle;
};
// Object with methods that call other methods
const gameEngine = {
score: 0,
level: 1,
// Method that calls other methods
startGame() {
this.initializeLevel();
this.resetScore();
this.showWelcomeMessage();
},
initializeLevel() {
console.log(`Initializing level ${this.level}`);
},
resetScore() {
this.score = 0;
console.log('Score reset to 0');
},
showWelcomeMessage() {
console.log('Welcome to the game!');
},
// Method with callback parameter
processInput(input, callback) {
console.log(`Processing input: ${input}`);
if (callback && typeof callback === 'function') {
callback(input);
}
},
// Method that returns a function
createScoreHandler() {
return (points) => {
this.score += points;
console.log(`Score: ${this.score}`);
};
}
};
// Module pattern with private and public methods
const counterModule = (function() {
let count = 0;
// Private function
function validateIncrement(value) {
return typeof value === 'number' && value > 0;
}
// Return public interface
return {
// Public method
increment(value = 1) {
if (validateIncrement(value)) {
count += value;
}
},
// Public method
decrement(value = 1) {
if (validateIncrement(value)) {
count -= value;
}
},
// Public getter
getCount() {
return count;
},
// Public method that uses private function
reset() {
count = 0;
console.log('Counter reset');
}
};
})();
// Factory function that creates objects with methods
function createTimer(name) {
let startTime = null;
let endTime = null;
return {
name: name,
start() {
startTime = Date.now();
console.log(`Timer ${this.name} started`);
},
stop() {
endTime = Date.now();
console.log(`Timer ${this.name} stopped`);
},
getElapsed() {
if (startTime && endTime) {
return endTime - startTime;
}
return 0;
},
reset() {
startTime = null;
endTime = null;
console.log(`Timer ${this.name} reset`);
}
};
}
// Function that demonstrates object method usage
function demonstrateObjects() {
// Use calculator
calculator.add(10).multiply(2).subtract(5);
console.log('Calculator result:', calculator.value);
// Use vehicle
const car = new Vehicle('Toyota', 'Camry', 2022);
car.start();
car.drive(100);
// Use game engine
gameEngine.startGame();
const scoreHandler = gameEngine.createScoreHandler();
scoreHandler(100);
// Use counter module
counterModule.increment(5);
counterModule.decrement(2);
console.log('Counter value:', counterModule.getCount());
// Use timer factory
const timer = createTimer('TestTimer');
timer.start();
setTimeout(() => {
timer.stop();
console.log('Elapsed time:', timer.getElapsed());
}, 1000);
return {
calculator,
car,
gameEngine,
counterModule,
timer
};
}
// Export objects and functions
export { calculator, api, Vehicle, gameEngine, counterModule, createTimer };
export default demonstrateObjects;
```
--------------------------------------------------------------------------------
/website/src/components/HeroSection.tsx:
--------------------------------------------------------------------------------
```typescript
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Github, Download, ExternalLink } from "lucide-react";
import heroGraph from "@/assets/hero-graph.jpg";
import { useState, useEffect } from "react";
import ShowDownloads from "@/components/ShowDownloads";
import ShowStarGraph from "@/components/ShowStarGraph";
import { ThemeToggle } from "@/components/ThemeToggle";
const HeroSection = () => {
const [stars, setStars] = useState(null);
const [forks, setForks] = useState(null);
const [version, setVersion] = useState("");
useEffect(() => {
async function fetchVersion() {
try {
const res = await fetch(
"https://raw.githubusercontent.com/Shashankss1205/CodeGraphContext/main/README.md"
);
if (!res.ok) throw new Error("Failed to fetch README");
const text = await res.text();
const match = text.match(
/\*\*Version:\*\*\s*([0-9]+\.[0-9]+\.[0-9]+)/i
);
setVersion(match ? match[1] : "N/A");
} catch (err) {
console.error(err);
setVersion("N/A");
}
}
fetchVersion();
}, []);
useEffect(() => {
fetch("https://api.github.com/repos/Shashankss1205/CodeGraphContext")
.then((response) => response.json())
.then((data) => {
setStars(data.stargazers_count);
setForks(data.forks_count);
})
.catch((error) => console.error("Error fetching GitHub stats:", error));
}, []);
return (
<section className="relative min-h-screen flex items-center justify-center overflow-hidden">
{/* Header with Theme Toggle */}
<div className="absolute top-0 left-0 right-0 z-20 p-4" data-aos="fade-down">
<div className="container mx-auto flex justify-end">
<div className="rounded-full bg-white/60 backdrop-blur-md border border-gray-200 shadow-sm p-2 dark:bg-transparent dark:border-transparent dark:shadow-none">
<ThemeToggle />
</div>
</div>
</div>
{/* Background Image */}
<div
className="absolute inset-0 bg-cover bg-center bg-no-repeat opacity-20 brightness-110 saturate-110 dark:opacity-30 dark:brightness-100 dark:saturate-100"
style={{ backgroundImage: `url(${heroGraph})` }}
/>
{/* Gradient Overlay */}
<div className="absolute inset-0 bg-gradient-to-b from-white/60 via-white/40 to-white/80 dark:from-background/90 dark:via-background/80 dark:to-background/90" />
{/* Content */}
<div className="relative z-10 container mx-auto px-4 text-center max-w-5xl">
<div className="animate-float-up" data-aos="fade-up">
<Badge variant="secondary" className="mb-6 text-sm font-medium">
<div className="w-2 h-2 bg-accent rounded-full mr-2 animate-graph-pulse" />
Version {version} • MIT License
</Badge>
<h1 className="text-3xl sm:text-4xl md:text-5xl lg:text-6xl xl:text-7xl font-bold mb-6 bg-gradient-to-r from-purple-700 via-indigo-700 to-purple-900 dark:bg-gradient-primary bg-clip-text py-2 text-transparent leading-tight tracking-tight drop-shadow-[0_2px_8px_rgba(0,0,0,0.15)]">
CodeGraphContext
</h1>
<p className="text-xl md:text-2xl text-muted-foreground mb-4 leading-relaxed">
An MCP server that indexes local code into a
</p>
<p className="text-xl md:text-2xl text-accent font-semibold mb-8">
knowledge graph for AI assistants
</p>
<div className="flex flex-col sm:flex-row gap-4 justify-center items-center mb-12" data-aos="fade-up" data-aos-delay="200">
<Button size="lg" className="bg-gradient-to-r from-purple-600 via-indigo-600 to-purple-800 text-primary-foreground hover:opacity-90 transition-all duration-300 shadow-glow ring-1 ring-primary/20 dark:bg-gradient-primary" asChild>
<a href="https://pypi.org/project/codegraphcontext/" target="_blank" rel="noopener noreferrer">
<Download className="mr-2 h-5 w-5" />
pip install codegraphcontext
</a>
</Button>
<Button variant="outline" size="lg" asChild className="border-gray-300 hover:border-primary/60 bg-white/80 backdrop-blur-sm shadow-sm transition-smooth text-gray-900 dark:bg-transparent dark:text-foreground dark:border-primary/30">
<a href="https://github.com/Shashankss1205/CodeGraphContext" target="_blank" rel="noopener noreferrer">
<Github className="mr-2 h-5 w-5" />
View on GitHub
<ExternalLink className="ml-2 h-4 w-4" />
</a>
</Button>
<Button variant="ghost" size="lg" asChild>
<a href="https://shashankss1205.github.io/CodeGraphContext/" target="_blank" rel="noopener noreferrer" className="flex items-center gap-2">
<ExternalLink className="h-5 w-5" />
Documentation
</a>
</Button>
</div>
{/* Stats */}
<div className="flex flex-wrap justify-center gap-8 text-sm text-muted-foreground" data-aos="fade-up" data-aos-delay="400">
<div className="flex items-center gap-2">
<div className="w-3 h-3 bg-graph-node-1 rounded-full animate-graph-pulse" />
{stars !== null ? <span>{stars} GitHub Stars</span> : <span>Loading...</span>}
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 bg-graph-node-2 rounded-full animate-graph-pulse" style={{animationDelay: '0.5s'}} />
{forks !== null ? <span>{forks} Forks</span> : <span>Loading...</span>}
</div>
<div className="flex items-center gap-2">
<div className="w-3 h-3 bg-graph-node-3 rounded-full animate-graph-pulse" style={{animationDelay: '1s'}} />
<span><ShowDownloads /></span>
</div>
</div>
</div>
</div>
{/* Floating Graph Nodes */}
<div className="absolute top-20 left-10 w-8 h-8 graph-node animate-graph-pulse" style={{animationDelay: '0.2s'}} />
<div className="absolute top-40 right-20 w-6 h-6 graph-node animate-graph-pulse" style={{animationDelay: '0.8s'}} />
<div className="absolute bottom-32 left-20 w-10 h-10 graph-node animate-graph-pulse" style={{animationDelay: '1.2s'}} />
<div className="absolute bottom-20 right-10 w-7 h-7 graph-node animate-graph-pulse" style={{animationDelay: '0.6s'}} />
</section>
);
};
export default HeroSection;
```
--------------------------------------------------------------------------------
/tests/sample_project_rust/src/smart_pointers.rs:
--------------------------------------------------------------------------------
```rust
// smart_pointers.rs - Demonstrates Rust smart pointers
use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
use std::sync::Arc;
// Box - heap allocation
/// Basic Box usage
pub fn box_example() -> Box<i32> {
Box::new(42)
}
/// Recursive type with Box
#[derive(Debug)]
pub enum List {
Cons(i32, Box<List>),
Nil,
}
impl List {
pub fn new() -> Self {
List::Nil
}
pub fn prepend(self, value: i32) -> Self {
List::Cons(value, Box::new(self))
}
pub fn len(&self) -> usize {
match self {
List::Cons(_, tail) => 1 + tail.len(),
List::Nil => 0,
}
}
}
/// Box with trait object
pub trait Shape {
fn area(&self) -> f64;
}
pub struct Circle {
radius: f64,
}
pub struct Rectangle {
width: f64,
height: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
impl Shape for Rectangle {
fn area(&self) -> f64 {
self.width * self.height
}
}
pub fn create_shapes() -> Vec<Box<dyn Shape>> {
vec![
Box::new(Circle { radius: 5.0 }),
Box::new(Rectangle {
width: 10.0,
height: 5.0,
}),
]
}
// Rc - reference counting
/// Shared ownership with Rc
pub fn rc_example() {
let data = Rc::new(vec![1, 2, 3, 4, 5]);
let data2 = Rc::clone(&data);
let data3 = Rc::clone(&data);
println!("Data: {:?}, count: {}", data, Rc::strong_count(&data));
}
/// Graph structure with Rc
#[derive(Debug)]
pub struct Node {
value: i32,
children: Vec<Rc<Node>>,
}
impl Node {
pub fn new(value: i32) -> Rc<Self> {
Rc::new(Self {
value,
children: Vec::new(),
})
}
pub fn value(&self) -> i32 {
self.value
}
}
/// Tree with Rc and Weak
#[derive(Debug)]
pub struct TreeNode {
value: i32,
parent: RefCell<Weak<TreeNode>>,
children: RefCell<Vec<Rc<TreeNode>>>,
}
impl TreeNode {
pub fn new(value: i32) -> Rc<Self> {
Rc::new(Self {
value,
parent: RefCell::new(Weak::new()),
children: RefCell::new(Vec::new()),
})
}
pub fn add_child(self: &Rc<Self>, child: Rc<TreeNode>) {
*child.parent.borrow_mut() = Rc::downgrade(self);
self.children.borrow_mut().push(child);
}
}
// RefCell - interior mutability
/// RefCell for interior mutability
pub struct MockMessenger {
pub sent_messages: RefCell<Vec<String>>,
}
impl MockMessenger {
pub fn new() -> Self {
Self {
sent_messages: RefCell::new(Vec::new()),
}
}
pub fn send(&self, message: &str) {
self.sent_messages.borrow_mut().push(message.to_string());
}
pub fn message_count(&self) -> usize {
self.sent_messages.borrow().len()
}
}
/// Combining Rc and RefCell
pub struct SharedData {
data: Rc<RefCell<Vec<i32>>>,
}
impl SharedData {
pub fn new() -> Self {
Self {
data: Rc::new(RefCell::new(Vec::new())),
}
}
pub fn add(&self, value: i32) {
self.data.borrow_mut().push(value);
}
pub fn get(&self, index: usize) -> Option<i32> {
self.data.borrow().get(index).copied()
}
pub fn clone_ref(&self) -> SharedData {
SharedData {
data: Rc::clone(&self.data),
}
}
}
// Cell - for Copy types
pub struct CellExample {
value: Cell<i32>,
}
impl CellExample {
pub fn new(value: i32) -> Self {
Self {
value: Cell::new(value),
}
}
pub fn get(&self) -> i32 {
self.value.get()
}
pub fn set(&self, value: i32) {
self.value.set(value);
}
pub fn increment(&self) {
let current = self.value.get();
self.value.set(current + 1);
}
}
// Weak references
pub fn weak_reference_example() {
let strong = Rc::new(42);
let weak = Rc::downgrade(&strong);
println!("Strong count: {}", Rc::strong_count(&strong));
println!("Weak count: {}", Rc::weak_count(&strong));
match weak.upgrade() {
Some(value) => println!("Value: {}", value),
None => println!("Value has been dropped"),
}
}
// Custom smart pointer
pub struct MyBox<T> {
value: T,
}
impl<T> MyBox<T> {
pub fn new(value: T) -> Self {
Self { value }
}
}
impl<T> std::ops::Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<T> std::ops::DerefMut for MyBox<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}
// Drop trait
pub struct CustomDrop {
data: String,
}
impl CustomDrop {
pub fn new(data: String) -> Self {
println!("Creating CustomDrop with: {}", data);
Self { data }
}
}
impl Drop for CustomDrop {
fn drop(&mut self) {
println!("Dropping CustomDrop with: {}", self.data);
}
}
// Arc for thread-safe reference counting
use std::sync::Mutex;
use std::thread;
pub fn arc_example() {
let data = Arc::new(Mutex::new(vec![1, 2, 3]));
let mut handles = vec![];
for i in 0..3 {
let data = Arc::clone(&data);
let handle = thread::spawn(move || {
let mut data = data.lock().unwrap();
data.push(i);
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {:?}", data.lock().unwrap());
}
// Cow - Clone on Write
use std::borrow::Cow;
pub fn cow_example(input: &str) -> Cow<str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input)
}
}
pub fn cow_modify(mut data: Cow<[i32]>) -> Cow<[i32]> {
data.to_mut().push(4);
data
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_list() {
let list = List::new().prepend(3).prepend(2).prepend(1);
assert_eq!(list.len(), 3);
}
#[test]
fn test_shared_data() {
let data = SharedData::new();
let data2 = data.clone_ref();
data.add(1);
data2.add(2);
assert_eq!(data.get(0), Some(1));
assert_eq!(data.get(1), Some(2));
assert_eq!(data2.get(0), Some(1));
}
#[test]
fn test_cell() {
let cell = CellExample::new(5);
assert_eq!(cell.get(), 5);
cell.increment();
assert_eq!(cell.get(), 6);
}
#[test]
fn test_mock_messenger() {
let messenger = MockMessenger::new();
messenger.send("hello");
messenger.send("world");
assert_eq!(messenger.message_count(), 2);
}
#[test]
fn test_cow() {
let borrowed = cow_example("hello");
assert!(matches!(borrowed, Cow::Borrowed(_)));
let owned = cow_example("hello world");
assert!(matches!(owned, Cow::Owned(_)));
}
}
```
--------------------------------------------------------------------------------
/tests/sample_project_go/packages_imports.go:
--------------------------------------------------------------------------------
```go
// packages_imports.go - Demonstrates Go package imports and usage
package main
import (
// Standard library imports
"fmt"
"io"
"math"
"math/rand"
"net/http"
"os"
"strings"
"time"
// Aliased imports
str "strings"
// Dot imports (imports all exported names directly)
// . "fmt" // Uncomment to use - not recommended in production
// Blank imports (for side effects only)
_ "image/png"
// Local package import (would be actual import in real project)
// "github.com/user/project/module"
)
// StandardLibraryUsage demonstrates standard library usage
func StandardLibraryUsage() {
// fmt package
fmt.Println("Hello from fmt")
// strings package
upper := strings.ToUpper("hello")
fmt.Println(upper)
// math package
sqrt := math.Sqrt(16)
fmt.Printf("Square root: %.2f\n", sqrt)
// time package
now := time.Now()
fmt.Println("Current time:", now.Format(time.RFC3339))
// rand package
rand.Seed(time.Now().UnixNano())
randomNum := rand.Intn(100)
fmt.Println("Random number:", randomNum)
}
// AliasedImportUsage demonstrates aliased imports
func AliasedImportUsage() {
// Using str alias for strings package
result := str.Contains("hello world", "world")
fmt.Println("Contains:", result)
trimmed := str.TrimSpace(" spaces ")
fmt.Println("Trimmed:", trimmed)
}
// FileOperations demonstrates os and io packages
func FileOperations() error {
// Create a file
file, err := os.Create("example.txt")
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer file.Close()
// Write to file
_, err = io.WriteString(file, "Hello, File!\n")
if err != nil {
return fmt.Errorf("failed to write to file: %w", err)
}
// Read file
content, err := os.ReadFile("example.txt")
if err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
fmt.Println("File content:", string(content))
// Clean up
os.Remove("example.txt")
return nil
}
// HTTPClientExample demonstrates net/http package
func HTTPClientExample() error {
// Make HTTP request
resp, err := http.Get("https://api.github.com")
if err != nil {
return fmt.Errorf("failed to make request: %w", err)
}
defer resp.Body.Close()
fmt.Println("Status:", resp.Status)
// Read response body
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
fmt.Println("Response length:", len(body))
return nil
}
// HTTPServerExample demonstrates creating an HTTP server
func HTTPServerExample() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
})
http.HandleFunc("/api/users", handleUsers)
// This would start the server (commented out for sample)
// http.ListenAndServe(":8080", nil)
}
func handleUsers(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
fmt.Fprintf(w, "Getting users")
case http.MethodPost:
fmt.Fprintf(w, "Creating user")
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
// StringsPackageUsage demonstrates extensive strings package usage
func StringsPackageUsage() {
// Various string operations
text := "Hello, World! Hello, Go!"
contains := strings.Contains(text, "World")
hasPrefix := strings.HasPrefix(text, "Hello")
hasSuffix := strings.HasSuffix(text, "Go!")
count := strings.Count(text, "Hello")
index := strings.Index(text, "World")
split := strings.Split(text, " ")
joined := strings.Join(split, "-")
replaced := strings.Replace(text, "Hello", "Hi", -1)
fmt.Printf("Contains: %v, Prefix: %v, Suffix: %v\n", contains, hasPrefix, hasSuffix)
fmt.Printf("Count: %d, Index: %d\n", count, index)
fmt.Printf("Split: %v\n", split)
fmt.Printf("Joined: %s\n", joined)
fmt.Printf("Replaced: %s\n", replaced)
}
// MathPackageUsage demonstrates math package
func MathPackageUsage() {
// Math constants
fmt.Println("Pi:", math.Pi)
fmt.Println("E:", math.E)
// Math functions
fmt.Println("Sqrt(16):", math.Sqrt(16))
fmt.Println("Pow(2, 10):", math.Pow(2, 10))
fmt.Println("Max(10, 20):", math.Max(10, 20))
fmt.Println("Min(10, 20):", math.Min(10, 20))
fmt.Println("Abs(-42):", math.Abs(-42))
fmt.Println("Ceil(4.2):", math.Ceil(4.2))
fmt.Println("Floor(4.8):", math.Floor(4.8))
fmt.Println("Round(4.5):", math.Round(4.5))
}
// TimePackageUsage demonstrates time package
func TimePackageUsage() {
// Current time
now := time.Now()
fmt.Println("Current time:", now)
// Time formatting
formatted := now.Format("2006-01-02 15:04:05")
fmt.Println("Formatted:", formatted)
// Parsing time
parsed, _ := time.Parse("2006-01-02", "2024-01-15")
fmt.Println("Parsed:", parsed)
// Time arithmetic
tomorrow := now.Add(24 * time.Hour)
yesterday := now.Add(-24 * time.Hour)
fmt.Println("Tomorrow:", tomorrow.Format("2006-01-02"))
fmt.Println("Yesterday:", yesterday.Format("2006-01-02"))
// Duration
duration := 2 * time.Hour
fmt.Println("Duration:", duration)
// Sleep
// time.Sleep(time.Second)
}
// OSPackageUsage demonstrates os package
func OSPackageUsage() {
// Environment variables
os.Setenv("MY_VAR", "my_value")
value := os.Getenv("MY_VAR")
fmt.Println("Environment variable:", value)
// Command line arguments
args := os.Args
fmt.Println("Program name:", args[0])
// Working directory
wd, _ := os.Getwd()
fmt.Println("Working directory:", wd)
// File info
fileInfo, err := os.Stat("packages_imports.go")
if err == nil {
fmt.Println("File size:", fileInfo.Size())
fmt.Println("Is directory:", fileInfo.IsDir())
fmt.Println("Modified:", fileInfo.ModTime())
}
}
// IOPackageUsage demonstrates io package
func IOPackageUsage() {
// String reader
reader := strings.NewReader("Hello from io package")
// Read all
content, _ := io.ReadAll(reader)
fmt.Println("Content:", string(content))
// Copy example (would copy from one reader/writer to another)
// io.Copy(dst, src)
}
// MultiplePackageUsage uses multiple packages together
func MultiplePackageUsage() error {
// Combine time, strings, and fmt
now := time.Now()
formatted := now.Format(time.RFC3339)
upper := strings.ToUpper(formatted)
final := fmt.Sprintf("Current time: %s", upper)
// Combine math and fmt
result := math.Sqrt(math.Pow(3, 2) + math.Pow(4, 2))
output := fmt.Sprintf("Hypotenuse: %.2f", result)
fmt.Println(final)
fmt.Println(output)
return nil
}
// PackageInitPattern demonstrates initialization patterns
var (
initialized bool
config map[string]string
)
func init() {
// This runs automatically when package is imported
initialized = true
config = make(map[string]string)
config["version"] = "1.0.0"
config["env"] = "development"
fmt.Println("Package initialized")
}
// GetConfig returns the config
func GetConfig(key string) string {
return config[key]
}
func demonstrateImports() {
StandardLibraryUsage()
AliasedImportUsage()
StringsPackageUsage()
MathPackageUsage()
TimePackageUsage()
OSPackageUsage()
IOPackageUsage()
MultiplePackageUsage()
}
```