This is page 2 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/ui/calendar.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
function Calendar({ className, classNames, showOutsideDays = true, ...props }: CalendarProps) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(
buttonVariants({ variant: "outline" }),
"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100",
),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell: "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
day: cn(buttonVariants({ variant: "ghost" }), "h-9 w-9 p-0 font-normal aria-selected:opacity-100"),
day_range_end: "day-range-end",
day_selected:
"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
day_today: "bg-accent text-accent-foreground",
day_outside:
"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}}
components={{
IconLeft: ({ ..._props }) => <ChevronLeft className="h-4 w-4" />,
IconRight: ({ ..._props }) => <ChevronRight className="h-4 w-4" />,
}}
{...props}
/>
);
}
Calendar.displayName = "Calendar";
export { Calendar };
```
--------------------------------------------------------------------------------
/tests/sample_project_rust/src/modules.rs:
--------------------------------------------------------------------------------
```rust
// modules.rs - Demonstrates Rust module system and organization
// Nested modules
pub mod geometry {
pub mod shapes {
pub struct Circle {
pub radius: f64,
}
pub struct Rectangle {
pub width: f64,
pub height: f64,
}
impl Circle {
pub fn new(radius: f64) -> Self {
Self { radius }
}
pub fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
impl Rectangle {
pub fn new(width: f64, height: f64) -> Self {
Self { width, height }
}
pub fn area(&self) -> f64 {
self.width * self.height
}
}
}
pub mod calculations {
use super::shapes::{Circle, Rectangle};
pub fn total_area(circle: &Circle, rectangle: &Rectangle) -> f64 {
circle.area() + rectangle.area()
}
}
}
// Module with private items
pub mod data {
pub struct PublicStruct {
pub public_field: i32,
private_field: i32,
}
impl PublicStruct {
pub fn new(public_field: i32, private_field: i32) -> Self {
Self {
public_field,
private_field,
}
}
pub fn get_private(&self) -> i32 {
self.private_field
}
}
pub fn public_function() -> i32 {
private_function() + 10
}
fn private_function() -> i32 {
42
}
}
// Re-exports
pub mod utils {
pub use super::geometry::shapes::Circle;
pub use super::geometry::shapes::Rectangle;
pub fn create_default_circle() -> Circle {
Circle::new(1.0)
}
}
// Module with use statements
pub mod operations {
use std::collections::HashMap;
pub fn create_map() -> HashMap<String, i32> {
let mut map = HashMap::new();
map.insert("one".to_string(), 1);
map.insert("two".to_string(), 2);
map
}
}
// Glob imports (use with caution)
pub mod prelude {
pub use super::geometry::shapes::*;
pub use super::data::*;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_circle_area() {
let circle = geometry::shapes::Circle::new(5.0);
let area = circle.area();
assert!((area - 78.54).abs() < 0.01);
}
#[test]
fn test_public_struct() {
let s = data::PublicStruct::new(10, 20);
assert_eq!(s.public_field, 10);
assert_eq!(s.get_private(), 20);
}
}
```
--------------------------------------------------------------------------------
/website/src/components/ui/pagination.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils";
import { ButtonProps, buttonVariants } from "@/components/ui/button";
const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (
<nav
role="navigation"
aria-label="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
);
Pagination.displayName = "Pagination";
const PaginationContent = React.forwardRef<HTMLUListElement, React.ComponentProps<"ul">>(
({ className, ...props }, ref) => (
<ul ref={ref} className={cn("flex flex-row items-center gap-1", className)} {...props} />
),
);
PaginationContent.displayName = "PaginationContent";
const PaginationItem = React.forwardRef<HTMLLIElement, React.ComponentProps<"li">>(({ className, ...props }, ref) => (
<li ref={ref} className={cn("", className)} {...props} />
));
PaginationItem.displayName = "PaginationItem";
type PaginationLinkProps = {
isActive?: boolean;
} & Pick<ButtonProps, "size"> &
React.ComponentProps<"a">;
const PaginationLink = ({ className, isActive, size = "icon", ...props }: PaginationLinkProps) => (
<a
aria-current={isActive ? "page" : undefined}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className,
)}
{...props}
/>
);
PaginationLink.displayName = "PaginationLink";
const PaginationPrevious = ({ className, ...props }: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink aria-label="Go to previous page" size="default" className={cn("gap-1 pl-2.5", className)} {...props}>
<ChevronLeft className="h-4 w-4" />
<span>Previous</span>
</PaginationLink>
);
PaginationPrevious.displayName = "PaginationPrevious";
const PaginationNext = ({ className, ...props }: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink aria-label="Go to next page" size="default" className={cn("gap-1 pr-2.5", className)} {...props}>
<span>Next</span>
<ChevronRight className="h-4 w-4" />
</PaginationLink>
);
PaginationNext.displayName = "PaginationNext";
const PaginationEllipsis = ({ className, ...props }: React.ComponentProps<"span">) => (
<span aria-hidden className={cn("flex h-9 w-9 items-center justify-center", className)} {...props}>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More pages</span>
</span>
);
PaginationEllipsis.displayName = "PaginationEllipsis";
export {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
};
```
--------------------------------------------------------------------------------
/docs/docs/cli.md:
--------------------------------------------------------------------------------
```markdown
# CLI Reference
The CodeGraphContext CLI provides a set of commands to manage the server, index your code, and interact with the code graph.
## `cgc setup`
Runs the interactive setup wizard to configure the server and database connection. This helps users set up a local Docker-based Neo4j instance or connect to a remote one.
**Usage:**
```bash
cgc setup
```
## `cgc start`
Starts the CodeGraphContext MCP server, which listens for JSON-RPC requests from stdin.
**Usage:**
```bash
cgc start
```
## `cgc index [PATH]`
Indexes a directory or file by adding it to the code graph. If no path is provided, it indexes the current directory.
**Arguments:**
* `PATH` (optional): Path to the directory or file to index. Defaults to the current directory.
**Usage:**
```bash
cgc index /path/to/your/project
```
### Ignoring Files (`.cgcignore`)
You can tell CodeGraphContext to ignore specific files and directories by creating a `.cgcignore` file in the root of your project. This file uses the same syntax as `.gitignore`.
When you run `cgc index`, the command will look for a `.cgcignore` file in the directory being indexed and exclude any files or directories that match the patterns in the file.
**Example `.cgcignore` file:**
```
# Ignore build artifacts
/build/
/dist/
# Ignore dependencies
/node_modules/
/vendor/
# Ignore logs
*.log
```
## `cgc delete <PATH>`
Deletes a repository from the code graph.
**Arguments:**
* `PATH` (required): Path of the repository to delete from the code graph.
**Usage:**
```bash
cgc delete /path/to/your/project
```
## `cgc visualize [QUERY]`
Generates a URL to visualize a Cypher query in the Neo4j Browser. If no query is provided, a default query will be used.
**Arguments:**
* `QUERY` (optional): The Cypher query to visualize.
**Usage:**
```bash
cgc visualize "MATCH (n) RETURN n"
```
## `cgc list_repos`
Lists all indexed repositories.
**Usage:**
```bash
cgc list_repos
```
## `cgc add_package <PACKAGE_NAME>`
Adds a Python package to the code graph.
**Arguments:**
* `PACKAGE_NAME` (required): Name of the Python package to add.
**Usage:**
```bash
cgc add_package requests
```
## `cgc cypher <QUERY>`
Executes a read-only Cypher query.
**Arguments:**
* `QUERY` (required): The read-only Cypher query to execute.
**Usage:**
```bash
cgc cypher "MATCH (n:Function) RETURN n.name"
```
## `cgc list_mcp_tools`
Lists all available tools and their descriptions.
**Usage:**
```bash
cgc list_mcp_tools
```
## `cgc help`
Show the main help message and exit.
**Usage:**
```bash
cgc help
```
## `cgc version`
Show the application version.
**Usage:**
```bash
cgc --version
```
or
```bash
cgc version
```
```
--------------------------------------------------------------------------------
/website/src/components/ui/breadcrumb.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils";
const Breadcrumb = React.forwardRef<
HTMLElement,
React.ComponentPropsWithoutRef<"nav"> & {
separator?: React.ReactNode;
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />);
Breadcrumb.displayName = "Breadcrumb";
const BreadcrumbList = React.forwardRef<HTMLOListElement, React.ComponentPropsWithoutRef<"ol">>(
({ className, ...props }, ref) => (
<ol
ref={ref}
className={cn(
"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
className,
)}
{...props}
/>
),
);
BreadcrumbList.displayName = "BreadcrumbList";
const BreadcrumbItem = React.forwardRef<HTMLLIElement, React.ComponentPropsWithoutRef<"li">>(
({ className, ...props }, ref) => (
<li ref={ref} className={cn("inline-flex items-center gap-1.5", className)} {...props} />
),
);
BreadcrumbItem.displayName = "BreadcrumbItem";
const BreadcrumbLink = React.forwardRef<
HTMLAnchorElement,
React.ComponentPropsWithoutRef<"a"> & {
asChild?: boolean;
}
>(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a";
return <Comp ref={ref} className={cn("transition-colors hover:text-foreground", className)} {...props} />;
});
BreadcrumbLink.displayName = "BreadcrumbLink";
const BreadcrumbPage = React.forwardRef<HTMLSpanElement, React.ComponentPropsWithoutRef<"span">>(
({ className, ...props }, ref) => (
<span
ref={ref}
role="link"
aria-disabled="true"
aria-current="page"
className={cn("font-normal text-foreground", className)}
{...props}
/>
),
);
BreadcrumbPage.displayName = "BreadcrumbPage";
const BreadcrumbSeparator = ({ children, className, ...props }: React.ComponentProps<"li">) => (
<li role="presentation" aria-hidden="true" className={cn("[&>svg]:size-3.5", className)} {...props}>
{children ?? <ChevronRight />}
</li>
);
BreadcrumbSeparator.displayName = "BreadcrumbSeparator";
const BreadcrumbEllipsis = ({ className, ...props }: React.ComponentProps<"span">) => (
<span
role="presentation"
aria-hidden="true"
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
);
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis";
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
};
```
--------------------------------------------------------------------------------
/website/src/components/ui/table.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { cn } from "@/lib/utils";
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
</div>
),
);
Table.displayName = "Table";
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />,
);
TableHeader.displayName = "TableHeader";
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
),
);
TableBody.displayName = "TableBody";
const TableFooter = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(
({ className, ...props }, ref) => (
<tfoot ref={ref} className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)} {...props} />
),
);
TableFooter.displayName = "TableFooter";
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50", className)}
{...props}
/>
),
);
TableRow.displayName = "TableRow";
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className,
)}
{...props}
/>
),
);
TableHead.displayName = "TableHead";
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(
({ className, ...props }, ref) => (
<td ref={ref} className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)} {...props} />
),
);
TableCell.displayName = "TableCell";
const TableCaption = React.forwardRef<HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement>>(
({ className, ...props }, ref) => (
<caption ref={ref} className={cn("mt-4 text-sm text-muted-foreground", className)} {...props} />
),
);
TableCaption.displayName = "TableCaption";
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
```
--------------------------------------------------------------------------------
/docs/docs/installation.md:
--------------------------------------------------------------------------------
```markdown
## 🧩 Installation Guide
Welcome to **CodeGraphContext**! This guide provides a clear and seamless path to installing and configuring the tool, from prerequisites to launching your server.
## ⚙️ Prerequisites
Ensure the following are installed before you begin:
- **Python**: Version 3.8 or higher.
- **AI Agentic Coding Tool**: An MCP-compatible AI assistant (e.g., Gemini, Claude) if you plan to use the MCP server.
## 🚀 Getting Started
Follow these steps to set up **CodeGraphContext** effortlessly.
### 1. Install from PyPI
Install the `codegraphcontext` package directly from PyPI using pip:
```bash
pip install codegraphcontext
```
### 2. Run the Setup Wizard
Launch the interactive setup wizard to configure your Neo4j database and development environment:
```bash
cgc setup
```
The wizard guides you through a series of intuitive prompts to tailor your setup.
## 🧭 "Step-by-Step Guide for the Setup Wizard"
When you run `cgc setup`, the wizard offers a thoughtful journey through configuration. Follow these steps to complete your setup with ease:
**1. Select Your Database Location**
Choose where your Neo4j database will reside:
- **Local (Recommended)**: Host Neo4j on your machine for simplicity.
- **Docker**: With Docker installed, the wizard crafts a `docker-compose.yml` file and launches a Neo4j container seamlessly.
- **Local Binary**: On Debian-based systems (e.g., Ubuntu) or Mac Systems, the wizard installs Neo4j directly with your permission.
- **Hosted**: Connect to a remote Neo4j instance, such as AuraDB, by providing your database URI, username, and password.
- **Existing Instance**: For an existing Neo4j server (local or remote), enter its connection credentials.
**2. Configure Your Development Environment**
Integrate CodeGraphContext with your preferred development tool for a harmonious workflow. Select from supported options:
- VS Code
- Cursor
- Windsurf
- Claude
- Gemini CLI
- ChatGPT Codex
- Cline
- RooCode
- Amazon Q Developer
The wizard automatically updates configuration files to align with your choice.
Upon completing the prompts, the wizard creates two essential files:
- **`mcp.json`**: Placed in your working directory, this file configures the MCP server.
- **`.env`**: Stored securely in `~/.codegraphcontext`, this file safeguards your Neo4j credentials.
These files ensure smooth communication between CodeGraphContext, your Neo4j instance, and your AI assistant.
### 3. Start the Server
Once configuration is complete, launch the MCP server with:
```bash
cgc start
```
Your **CodeGraphContext** server is now active, ready to power AI-assisted graph queries.
## Next Steps
With **CodeGraphContext** installed and configured, you’re ready to explore its AI-powered capabilities. Happy coding ✨!
```
--------------------------------------------------------------------------------
/tests/test_typescript_parser.py:
--------------------------------------------------------------------------------
```python
import pytest
from pathlib import Path
import time
# Import the helper function from the conftest.py file
from .conftest import call_tool
# Define the path to the TypeScript sample project
TS_SAMPLE_PROJECT_PATH = str(Path(__file__).parent / "sample_project_typescript")
def wait_for_job_completion(server, job_id, timeout=60):
"""Helper function to wait for an indexing job to complete."""
start_time = time.time()
while True:
if time.time() - start_time > timeout:
pytest.fail(f"Job {job_id} timed out after {timeout} seconds.")
status_result = call_tool(server, "check_job_status", {"job_id": job_id})
job_status = status_result.get("job", {}).get("status")
if job_status == "completed":
break
elif job_status in ["failed", "cancelled"]:
pytest.fail(f"Indexing job failed with status: {job_status}")
time.sleep(1)
# This test uses the 'server' fixture from conftest.py
# Pytest automatically starts the cgc server and passes in a communication function.
def test_typescript_interfaces_and_types_are_indexed(server):
"""
This is an integration test. It indexes the TypeScript sample project
and then queries the live database to verify the results.
"""
# ARRANGE: First, delete any previous data for this project to ensure a clean slate.
call_tool(server, "delete_repository", {"repo_path": TS_SAMPLE_PROJECT_PATH})
# ACT (Part 1): Index the entire TypeScript sample project.
add_result = call_tool(server, "add_code_to_graph", {"path": TS_SAMPLE_PROJECT_PATH})
assert add_result.get("success") is True, "Failed to start indexing job"
job_id = add_result.get("job_id")
# Wait for the indexing to finish.
wait_for_job_completion(server, job_id)
# ACT (Part 2): Query the database for the interfaces and types we expect to find.
interface_query = "MATCH (i:Interface {name: 'User'}) RETURN i.name AS name"
type_alias_query = "MATCH (t:TypeAlias {name: 'UserID'}) RETURN t.name AS name"
interface_result = call_tool(server, "execute_cypher_query", {"cypher_query": interface_query})
type_alias_result = call_tool(server, "execute_cypher_query", {"cypher_query": type_alias_query})
# ASSERT: Check that the queries returned the expected results from the database.
assert interface_result.get("success") is True
assert len(interface_result.get("results", [])) == 1, "Should find exactly one 'User' interface"
assert interface_result["results"][0]["name"] == "User"
assert type_alias_result.get("success") is True
assert len(type_alias_result.get("results", [])) == 1, "Should find exactly one 'UserID' type alias"
assert type_alias_result["results"][0]["name"] == "UserID"
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/functions.js:
--------------------------------------------------------------------------------
```javascript
/**
* Sample JavaScript file demonstrating various function definitions
* This file tests function declarations, arrow functions, and method definitions
*/
// Regular function declaration
function regularFunction(param1, param2) {
console.log('Regular function called with:', param1, param2);
return param1 + param2;
}
/**
* Function with JSDoc documentation
* @param {string} name - The name to greet
* @param {number} age - The age of the person
* @returns {string} A greeting message
*/
function greetPerson(name, age = 25) {
return `Hello ${name}, you are ${age} years old!`;
}
// Function expression assigned to variable
const functionExpression = function(x, y) {
return x * y;
};
// Arrow function with multiple parameters
const arrowFunction = (a, b, c) => {
const result = a + b + c;
return result;
};
// Arrow function with single parameter (no parentheses)
const singleParamArrow = x => x * 2;
// Arrow function with no parameters
const noParamsArrow = () => {
console.log('No parameters arrow function');
return 42;
};
// Arrow function with rest parameters
const restParamsFunction = (...args) => {
return args.reduce((sum, val) => sum + val, 0);
};
// Arrow function with destructuring parameters
const destructuringParams = ({name, age}) => {
return `${name} is ${age} years old`;
};
// Higher-order function
const higherOrderFunction = (callback) => {
return function(value) {
return callback(value * 2);
};
};
// Immediately Invoked Function Expression (IIFE)
const iife = (function() {
const privateVar = 'secret';
return function() {
return privateVar;
};
})();
// Function with complex parameters
function complexParams(required, optional = 'default', ...rest) {
console.log('Required:', required);
console.log('Optional:', optional);
console.log('Rest:', rest);
}
// Async function
async function asyncFunction(url) {
try {
const response = await fetch(url);
return await response.json();
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// Async arrow function
const asyncArrowFunction = async (data) => {
const processed = await processData(data);
return processed;
};
// Generator function
function* generatorFunction(start, end) {
for (let i = start; i <= end; i++) {
yield i;
}
}
// Function that calls other functions
function orchestrator() {
const result1 = regularFunction(5, 3);
const result2 = functionExpression(4, 6);
const result3 = arrowFunction(1, 2, 3);
return {
sum: result1,
product: result2,
total: result3
};
}
// Export functions for module usage
export { regularFunction, greetPerson, arrowFunction };
export default orchestrator;
```
--------------------------------------------------------------------------------
/tests/test_tree_sitter/test_file.py:
--------------------------------------------------------------------------------
```python
import os
from pathlib import Path
from src.codegraphcontext.tools.languages.python import PythonTreeSitterParser
class MockParser:
def parse(self, source_bytes):
class MockTree:
@property
def root_node(self):
return None # You can mock this deeper if needed
return MockTree()
class MockQuery:
def captures(self, node):
return [] # Simulate no matches for now
class MockLanguage:
def query(self, query_str):
return MockQuery()
class MockGenericParserWrapper:
def __init__(self):
self.language_name = "python"
self.language = MockLanguage()
self.parser = MockParser()
def test_super_resolution():
# Simulated parsed output from two files
parsed = [
{
"type": "function_call",
"full_name": "super().greet",
"class_context": "B",
"name": "greet"
},
{
"type": "class",
"name": "B",
"bases": ["A"]
},
{
"type": "class",
"name": "A",
"bases": []
},
{
"type": "function",
"name": "greet",
"class_context": "A",
"file_path": "class_instantiation.py"
},
{
"type": "function",
"name": "greet",
"class_context": "Z",
"file_path": "complex_classes.py"
}
]
# Find the super().greet() call
target_call = next(
(item for item in parsed if item.get("type") == "function_call" and item.get("full_name") == "super().greet"),
None
)
assert target_call is not None, "super().greet() call not found"
# Simulated resolution logic
current_class = target_call.get("class_context")
method_name = target_call.get("name")
class_map = {
cls["name"]: cls
for cls in parsed
if cls.get("type") == "class"
}
resolved = None
if current_class and current_class in class_map:
bases = class_map[current_class].get("bases", [])
for base in bases:
base_class = class_map.get(base)
if base_class:
for item in parsed:
if (
item.get("type") == "function"
and item.get("name") == method_name
and item.get("class_context") == base
):
resolved = f"{item.get('file_path')}:{base}.{method_name}"
break
if resolved:
break
assert resolved is not None, "Resolution failed: no matching method found in base classes"
assert not resolved.endswith("Z.greet"), f"Bug: super().greet() incorrectly resolved to {resolved}"
```
--------------------------------------------------------------------------------
/tests/sample_project_go/structs_methods.go:
--------------------------------------------------------------------------------
```go
// structs_methods.go - Demonstrates Go structs and methods
package main
import "fmt"
// Person represents a basic struct
type Person struct {
Name string
Age int
}
// Employee extends Person concept with additional fields
type Employee struct {
Person
ID int
Position string
Salary float64
}
// AnonymousFieldStruct uses anonymous fields
type AnonymousFieldStruct struct {
string
int
bool
}
// PrivateFieldStruct demonstrates private fields
type PrivateFieldStruct struct {
PublicField string
privateField int // unexported field
}
// NewPerson is a constructor function
func NewPerson(name string, age int) *Person {
return &Person{
Name: name,
Age: age,
}
}
// Greet is a value receiver method
func (p Person) Greet() string {
return fmt.Sprintf("Hello, my name is %s", p.Name)
}
// HaveBirthday is a pointer receiver method (modifies struct)
func (p *Person) HaveBirthday() {
p.Age++
}
// IsAdult demonstrates method with return value
func (p Person) IsAdult() bool {
return p.Age >= 18
}
// NewEmployee creates a new employee
func NewEmployee(name string, age, id int, position string) *Employee {
return &Employee{
Person: Person{
Name: name,
Age: age,
},
ID: id,
Position: position,
}
}
// GetDetails is a method on embedded struct
func (e Employee) GetDetails() string {
return fmt.Sprintf("%s (%d) - %s [ID: %d]", e.Name, e.Age, e.Position, e.ID)
}
// Promote modifies employee position
func (e *Employee) Promote(newPosition string, newSalary float64) {
e.Position = newPosition
e.Salary = newSalary
}
// GivesRaise calculates new salary
func (e *Employee) GiveRaise(percentage float64) {
e.Salary = e.Salary * (1 + percentage/100)
}
// SetPrivateField demonstrates accessing private fields through methods
func (p *PrivateFieldStruct) SetPrivateField(val int) {
p.privateField = val
}
// GetPrivateField gets the private field value
func (p *PrivateFieldStruct) GetPrivateField() int {
return p.privateField
}
// MethodCallingMethod demonstrates internal method calls
func (p Person) FullIntroduction() string {
greeting := p.Greet()
ageStatus := "minor"
if p.IsAdult() {
ageStatus = "adult"
}
return fmt.Sprintf("%s and I am a %s", greeting, ageStatus)
}
// CompareAge compares two persons
func (p Person) CompareAge(other Person) string {
if p.Age > other.Age {
return fmt.Sprintf("%s is older than %s", p.Name, other.Name)
} else if p.Age < other.Age {
return fmt.Sprintf("%s is younger than %s", p.Name, other.Name)
}
return fmt.Sprintf("%s and %s are the same age", p.Name, other.Name)
}
func demonstrateStructs() {
person := NewPerson("Alice", 30)
fmt.Println(person.Greet())
person.HaveBirthday()
employee := NewEmployee("Bob", 25, 1001, "Developer")
employee.Promote("Senior Developer", 90000)
fmt.Println(employee.GetDetails())
}
```
--------------------------------------------------------------------------------
/website/package.json:
--------------------------------------------------------------------------------
```json
{
"name": "vite_react_shadcn_ts",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"build:dev": "vite build --mode development",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@hookform/resolvers": "^3.10.0",
"@radix-ui/react-accordion": "^1.2.11",
"@radix-ui/react-alert-dialog": "^1.1.14",
"@radix-ui/react-aspect-ratio": "^1.1.7",
"@radix-ui/react-avatar": "^1.1.10",
"@radix-ui/react-checkbox": "^1.3.2",
"@radix-ui/react-collapsible": "^1.1.11",
"@radix-ui/react-context-menu": "^2.2.15",
"@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-dropdown-menu": "^2.1.15",
"@radix-ui/react-hover-card": "^1.1.14",
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-menubar": "^1.1.15",
"@radix-ui/react-navigation-menu": "^1.2.13",
"@radix-ui/react-popover": "^1.1.14",
"@radix-ui/react-progress": "^1.1.7",
"@radix-ui/react-radio-group": "^1.3.7",
"@radix-ui/react-scroll-area": "^1.2.9",
"@radix-ui/react-select": "^2.2.5",
"@radix-ui/react-separator": "^1.1.7",
"@radix-ui/react-slider": "^1.3.5",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-switch": "^1.2.5",
"@radix-ui/react-tabs": "^1.1.12",
"@radix-ui/react-toast": "^1.2.14",
"@radix-ui/react-toggle": "^1.1.9",
"@radix-ui/react-toggle-group": "^1.1.10",
"@radix-ui/react-tooltip": "^1.2.7",
"@supabase/supabase-js": "^2.75.0",
"@tanstack/react-query": "^5.83.0",
"@types/aos": "^3.0.7",
"aos": "^2.3.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.6.0",
"framer-motion": "^12.23.22",
"input-otp": "^1.4.2",
"lucide-react": "^0.462.0",
"next-themes": "^0.3.0",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.61.1",
"react-icons": "^5.5.0",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.9",
"react-router-dom": "^6.30.1",
"recharts": "^2.15.4",
"sonner": "^1.7.4",
"tailwind-merge": "^2.6.0",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.9",
"zod": "^3.25.76"
},
"devDependencies": {
"@eslint/js": "^9.32.0",
"@tailwindcss/typography": "^0.5.16",
"@types/node": "^22.16.5",
"@types/react": "^18.3.23",
"@types/react-dom": "^18.3.7",
"@vitejs/plugin-react-swc": "^3.11.0",
"autoprefixer": "^10.4.21",
"eslint": "^9.32.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^15.15.0",
"postcss": "^8.5.6",
"tailwindcss": "^3.4.17",
"typescript": "^5.8.3",
"typescript-eslint": "^8.38.0",
"vite": "^5.4.19"
}
}
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/query_tool_languages/cpp_toolkit.py:
--------------------------------------------------------------------------------
```python
class CppToolkit:
"""Handles Neo4j queries for C++ file graph."""
def get_cypher_query(query: str) -> str:
"""
Returns a Cypher query string based on the query type requested.
Supported query types:
- functions
- classes
- imports
- structs
- enums
- unions
- macros
- variables
"""
query = query.strip().lower()
if query == "functions":
return """
MATCH (f:Function)
RETURN f.name AS name, f.file_path AS file_path,
f.line_number AS line_number, f.docstring AS docstring
ORDER BY f.file_path, f.line_number
"""
elif query == "classes":
return """
MATCH (c:Class)
RETURN c.name AS name, c.file_path AS file_path,
c.line_number AS line_number, c.docstring AS docstring
ORDER BY c.file_path, c.line_number
"""
elif query == "imports":
return """
MATCH (f:File)-[i:IMPORTS]->(m:Module)
RETURN f.name AS file_name, m.name AS module_name,
m.full_import_name AS full_import_name, m.alias AS alias
ORDER BY f.name
"""
elif query == "structs":
return """
MATCH (s:Struct)
RETURN s.name AS name, s.file_path AS file_path,
s.line_number AS line_number, s.fields AS fields
ORDER BY s.file_path, s.line_number
"""
elif query == "enums":
return """
MATCH (e:Enum)
RETURN e.name AS name, e.file_path AS file_path,
e.line_number AS line_number, e.values AS values
ORDER BY e.file_path, e.line_number
"""
elif query == "unions":
return """
MATCH (u:Union)
RETURN u.name AS name, u.file_path AS file_path,
u.line_number AS line_number, u.members AS members
ORDER BY u.file_path, u.line_number
"""
elif query == "macros":
return """
MATCH (m:Macro)
RETURN m.name AS name, m.file_path AS file_path,
m.line_number AS line_number, m.value AS value
ORDER BY m.file_path, m.line_number
"""
elif query == "variables":
return """
MATCH (v:Variable)
RETURN v.name AS name, v.file_path AS file_path,
v.line_number AS line_number, v.value AS value,
v.context AS context
ORDER BY v.file_path, v.line_number
"""
else:
raise ValueError(f"Unsupported query type: {query}")
```
--------------------------------------------------------------------------------
/website/src/components/ui/drawer.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { Drawer as DrawerPrimitive } from "vaul";
import { cn } from "@/lib/utils";
const Drawer = ({ shouldScaleBackground = true, ...props }: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
<DrawerPrimitive.Root shouldScaleBackground={shouldScaleBackground} {...props} />
);
Drawer.displayName = "Drawer";
const DrawerTrigger = DrawerPrimitive.Trigger;
const DrawerPortal = DrawerPrimitive.Portal;
const DrawerClose = DrawerPrimitive.Close;
const DrawerOverlay = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Overlay ref={ref} className={cn("fixed inset-0 z-50 bg-black/80", className)} {...props} />
));
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName;
const DrawerContent = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DrawerPortal>
<DrawerOverlay />
<DrawerPrimitive.Content
ref={ref}
className={cn(
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
className,
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
));
DrawerContent.displayName = "DrawerContent";
const DrawerHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)} {...props} />
);
DrawerHeader.displayName = "DrawerHeader";
const DrawerFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("mt-auto flex flex-col gap-2 p-4", className)} {...props} />
);
DrawerFooter.displayName = "DrawerFooter";
const DrawerTitle = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
DrawerTitle.displayName = DrawerPrimitive.Title.displayName;
const DrawerDescription = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
DrawerDescription.displayName = DrawerPrimitive.Description.displayName;
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
};
```
--------------------------------------------------------------------------------
/website/src/components/FeaturesSection.tsx:
--------------------------------------------------------------------------------
```typescript
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { GitBranch, Eye, Zap, Terminal } from "lucide-react";
const features = [
{
icon: GitBranch,
title: "Code Indexing",
description: "Analyzes code and builds a comprehensive knowledge graph of its components, relationships, and dependencies.",
color: "graph-node-1"
},
{
icon: Eye,
title: "Relationship Analysis",
description: "Query for callers, callees, class hierarchies, and complex code relationships through natural language.",
color: "graph-node-2"
},
{
icon: Zap,
title: "Live Updates",
description: "Watches local files for changes and automatically updates the graph in real-time as you code.",
color: "graph-node-3"
},
{
icon: Terminal,
title: "Interactive Setup",
description: "User-friendly command-line wizard for easy setup with Neo4j, Docker, or hosted database configurations.",
color: "graph-node-1"
}
];
const FeaturesSection = () => {
return (
<section className="py-24 px-4">
<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">
Powerful Features
</h2>
<p className="text-xl text-muted-foreground max-w-3xl mx-auto">
Transform your codebase into an intelligent knowledge graph that AI assistants can understand and navigate
</p>
</div>
<div className="grid md:grid-cols-2 gap-8">
{features.map((feature, index) => (
<div key={index} data-aos="fade-up" data-aos-delay={index * 100}>
<Card
className="border-border/50 hover:border-primary/30 transition-smooth group hover:shadow-glow animate-float-up dark:bg-gradient-card dark:bg-card/50 dark:border-border/30 dark:hover:border-primary/40 bg-white/95 border-gray-200/50 hover:border-primary/50 shadow-sm h-full"
style={{ animationDelay: `${index * 0.1}s` }}
>
<CardHeader>
<div className="flex items-center gap-4 mb-4">
<div className={`p-3 rounded-xl bg-${feature.color}/10 border border-${feature.color}/20 group-hover:bg-${feature.color}/20 transition-smooth dark:bg-${feature.color}/20 dark:border-${feature.color}/30 bg-${feature.color}/5 border-${feature.color}/15`}>
<feature.icon className={`h-6 w-6 text-${feature.color}`} />
</div>
<CardTitle className="text-xl font-semibold dark:text-foreground text-gray-900">{feature.title}</CardTitle>
</div>
<CardDescription className="text-base text-muted-foreground leading-relaxed dark:text-muted-foreground text-gray-600">
{feature.description}
</CardDescription>
</CardHeader>
</Card>
</div>
))}
</div>
</div>
</section>
);
};
export default FeaturesSection;
```
--------------------------------------------------------------------------------
/website/public/placeholder.svg:
--------------------------------------------------------------------------------
```
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1200" fill="none"><rect width="1200" height="1200" fill="#EAEAEA" rx="3"/><g opacity=".5"><g opacity=".5"><path fill="#FAFAFA" d="M600.709 736.5c-75.454 0-136.621-61.167-136.621-136.62 0-75.454 61.167-136.621 136.621-136.621 75.453 0 136.62 61.167 136.62 136.621 0 75.453-61.167 136.62-136.62 136.62Z"/><path stroke="#C9C9C9" stroke-width="2.418" d="M600.709 736.5c-75.454 0-136.621-61.167-136.621-136.62 0-75.454 61.167-136.621 136.621-136.621 75.453 0 136.62 61.167 136.62 136.621 0 75.453-61.167 136.62-136.62 136.62Z"/></g><path stroke="url(#a)" stroke-width="2.418" d="M0-1.209h553.581" transform="scale(1 -1) rotate(45 1163.11 91.165)"/><path stroke="url(#b)" stroke-width="2.418" d="M404.846 598.671h391.726"/><path stroke="url(#c)" stroke-width="2.418" d="M599.5 795.742V404.017"/><path stroke="url(#d)" stroke-width="2.418" d="m795.717 796.597-391.441-391.44"/><path fill="#fff" d="M600.709 656.704c-31.384 0-56.825-25.441-56.825-56.824 0-31.384 25.441-56.825 56.825-56.825 31.383 0 56.824 25.441 56.824 56.825 0 31.383-25.441 56.824-56.824 56.824Z"/><g clip-path="url(#e)"><path fill="#666" fill-rule="evenodd" d="M616.426 586.58h-31.434v16.176l3.553-3.554.531-.531h9.068l.074-.074 8.463-8.463h2.565l7.18 7.181V586.58Zm-15.715 14.654 3.698 3.699 1.283 1.282-2.565 2.565-1.282-1.283-5.2-5.199h-6.066l-5.514 5.514-.073.073v2.876a2.418 2.418 0 0 0 2.418 2.418h26.598a2.418 2.418 0 0 0 2.418-2.418v-8.317l-8.463-8.463-7.181 7.181-.071.072Zm-19.347 5.442v4.085a6.045 6.045 0 0 0 6.046 6.045h26.598a6.044 6.044 0 0 0 6.045-6.045v-7.108l1.356-1.355-1.282-1.283-.074-.073v-17.989h-38.689v23.43l-.146.146.146.147Z" clip-rule="evenodd"/></g><path stroke="#C9C9C9" stroke-width="2.418" d="M600.709 656.704c-31.384 0-56.825-25.441-56.825-56.824 0-31.384 25.441-56.825 56.825-56.825 31.383 0 56.824 25.441 56.824 56.825 0 31.383-25.441 56.824-56.824 56.824Z"/></g><defs><linearGradient id="a" x1="554.061" x2="-.48" y1=".083" y2=".087" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="b" x1="796.912" x2="404.507" y1="599.963" y2="599.965" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="c" x1="600.792" x2="600.794" y1="403.677" y2="796.082" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><linearGradient id="d" x1="404.85" x2="796.972" y1="403.903" y2="796.02" gradientUnits="userSpaceOnUse"><stop stop-color="#C9C9C9" stop-opacity="0"/><stop offset=".208" stop-color="#C9C9C9"/><stop offset=".792" stop-color="#C9C9C9"/><stop offset="1" stop-color="#C9C9C9" stop-opacity="0"/></linearGradient><clipPath id="e"><path fill="#fff" d="M581.364 580.535h38.689v38.689h-38.689z"/></clipPath></defs></svg>
```
--------------------------------------------------------------------------------
/docs/docs/architecture.md:
--------------------------------------------------------------------------------
```markdown
# Architecture Documentation
This document provides a detailed overview of the architecture of the CodeGraphContext project.
## High-Level Overview
The project is a client-server application designed to analyze and visualize codebases. It consists of:
* **A Python backend:** This is the core of the application, responsible for parsing and analyzing code, building a graph representation of the codebase, and exposing this data through an API.
* **A web-based frontend:** A user interface for interacting with the backend, visualizing the code graph, and exploring the codebase.
* **A command-line interface (CLI):** For managing the backend and performing analysis from the terminal.
## Backend Architecture
The backend is a Python application located in the `src/codegraphcontext` directory.
### Core Components
The `src/codegraphcontext/core` directory contains the fundamental building blocks of the backend:
* **Database:** A graph database is used to store the code graph. This allows for efficient querying of relationships between code elements (e.g., function calls, class inheritance).
* **Jobs:** Asynchronous jobs are used for long-running tasks like indexing a new codebase. This prevents the application from becoming unresponsive.
* **Watcher:** A file system watcher monitors the codebase for changes and triggers re-indexing, keeping the code graph up-to-date.
### Tools
The `src/codegraphcontext/tools` directory contains the logic for code analysis:
* **Graph Builder:** This component is responsible for parsing the code and building the graph representation that is stored in the database.
* **Code Finder:** Provides functionality to search for specific code elements within the indexed codebase.
* **Import Extractor:** This tool analyzes the import statements in the code to understand dependencies between modules.
### Server
The `src/codegraphcontext/server.py` file implements the API server. It exposes the functionality of the backend to the frontend through a JSON-RPC API.
### CLI
The `src/codegraphcontext/cli` directory contains the implementation of the command-line interface. It allows users to:
* Start and stop the backend server.
* Index new projects.
* Run analysis tools from the command line.
## Frontend Architecture
The frontend is a modern web application located in the `website/` directory.
* **Framework:** It is built using React and TypeScript.
* **Build Tool:** Vite is used for fast development and building the application.
* **Component-Based:** The UI is organized into reusable components, located in `website/src/components`. This includes UI elements like buttons and dialogs, as well as higher-level components for different sections of the application.
* **Styling:** Tailwind CSS is used for styling the application.
## Testing
The `tests/` directory contains the test suite for the project.
* **Integration Tests:** `test_cgc_integration.py` contains tests that verify the interaction between different components of the backend.
* **Unit Tests:** Other files in this directory contain unit tests for specific modules and functions.
* **Sample Project:** The `tests/sample_project` directory contains a variety of Python files used as input for testing the code analysis tools.
```
--------------------------------------------------------------------------------
/organizer/docs.md:
--------------------------------------------------------------------------------
```markdown
# Architecture Documentation
This document provides a detailed overview of the architecture of the CodeGraphContext project.
## High-Level Overview
The project is a client-server application designed to analyze and visualize codebases. It consists of:
* **A Python backend:** This is the core of the application, responsible for parsing and analyzing code, building a graph representation of the codebase, and exposing this data through an API.
* **A web-based frontend:** A user interface for interacting with the backend, visualizing the code graph, and exploring the codebase.
* **A command-line interface (CLI):** For managing the backend and performing analysis from the terminal.
## Backend Architecture
The backend is a Python application located in the `src/codegraphcontext` directory.
### Core Components
The `src/codegraphcontext/core` directory contains the fundamental building blocks of the backend:
* **Database:** A graph database is used to store the code graph. This allows for efficient querying of relationships between code elements (e.g., function calls, class inheritance).
* **Jobs:** Asynchronous jobs are used for long-running tasks like indexing a new codebase. This prevents the application from becoming unresponsive.
* **Watcher:** A file system watcher monitors the codebase for changes and triggers re-indexing, keeping the code graph up-to-date.
### Tools
The `src/codegraphcontext/tools` directory contains the logic for code analysis:
* **Graph Builder:** This component is responsible for parsing the code and building the graph representation that is stored in the database.
* **Code Finder:** Provides functionality to search for specific code elements within the indexed codebase.
* **Import Extractor:** This tool analyzes the import statements in the code to understand dependencies between modules.
### Server
The `src/codegraphcontext/server.py` file implements the API server. It exposes the functionality of the backend to the frontend through a JSON-RPC API.
### CLI
The `src/codegraphcontext/cli` directory contains the implementation of the command-line interface. It allows users to:
* Start and stop the backend server.
* Index new projects.
* Run analysis tools from the command line.
## Frontend Architecture
The frontend is a modern web application located in the `website/` directory.
* **Framework:** It is built using React and TypeScript.
* **Build Tool:** Vite is used for fast development and building the application.
* **Component-Based:** The UI is organized into reusable components, located in `website/src/components`. This includes UI elements like buttons and dialogs, as well as higher-level components for different sections of the application.
* **Styling:** Tailwind CSS is used for styling the application.
## Testing
The `tests/` directory contains the test suite for the project.
* **Integration Tests:** `test_cgc_integration.py` contains tests that verify the interaction between different components of the backend.
* **Unit Tests:** Other files in this directory contain unit tests for specific modules and functions.
* **Sample Project:** The `tests/sample_project` directory contains a variety of Python files used as input for testing the code analysis tools.
```
--------------------------------------------------------------------------------
/website/tailwind.config.ts:
--------------------------------------------------------------------------------
```typescript
import type { Config } from "tailwindcss";
export default {
darkMode: ["class"],
content: ["./pages/**/*.{ts,tsx}", "./components/**/*.{ts,tsx}", "./app/**/*.{ts,tsx}", "./src/**/*.{ts,tsx}"],
prefix: "",
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
sidebar: {
DEFAULT: "hsl(var(--sidebar-background))",
foreground: "hsl(var(--sidebar-foreground))",
primary: "hsl(var(--sidebar-primary))",
"primary-foreground": "hsl(var(--sidebar-primary-foreground))",
accent: "hsl(var(--sidebar-accent))",
"accent-foreground": "hsl(var(--sidebar-accent-foreground))",
border: "hsl(var(--sidebar-border))",
ring: "hsl(var(--sidebar-ring))",
},
// Graph-specific colors
"graph-node-1": "hsl(var(--graph-node-1))",
"graph-node-2": "hsl(var(--graph-node-2))",
"graph-node-3": "hsl(var(--graph-node-3))",
"graph-edge": "hsl(var(--graph-edge))",
},
backgroundImage: {
"gradient-primary": "var(--gradient-primary)",
"gradient-hero": "var(--gradient-hero)",
"gradient-card": "var(--gradient-card)",
},
boxShadow: {
"glow": "var(--shadow-glow)",
"card": "var(--shadow-card)",
},
transitionTimingFunction: {
"smooth": "var(--transition-smooth)",
"bounce": "var(--transition-bounce)",
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: {
height: "0",
},
to: {
height: "var(--radix-accordion-content-height)",
},
},
"accordion-up": {
from: {
height: "var(--radix-accordion-content-height)",
},
to: {
height: "0",
},
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
plugins: [require("tailwindcss-animate")],
} satisfies Config;
```
--------------------------------------------------------------------------------
/src/codegraphcontext/tools/advanced_language_query_tool.py:
--------------------------------------------------------------------------------
```python
import re
import logging
#importing all the language toolkits
from ..tools.query_tool_languages.c_toolkit import CToolkit
from ..tools.query_tool_languages.cpp_toolkit import CppToolkit
from ..tools.query_tool_languages.go_toolkit import GoToolkit
from ..tools.query_tool_languages.java_toolkit import JavaToolkit
from ..tools.query_tool_languages.javascript_toolkit import JavascriptToolkit
from ..tools.query_tool_languages.python_toolkit import PythonToolkit
from ..tools.query_tool_languages.ruby_toolkit import RubyToolkit
from ..tools.query_tool_languages.rust_toolkit import RustToolkit
from ..tools.query_tool_languages.typescript_toolkit import TypescriptToolkit
from ..core.database import DatabaseManager
from ..utils.debug_log import debug_log
logger = logging.getLogger(__name__)
class Advanced_language_query:
"""
Tool implementation for executing a read-only language specific Cypher query.
Important: Includes a safety check to prevent any database modification
by disallowing keywords like CREATE, MERGE, DELETE, etc.
"""
TOOLKITS = {
"c": CToolkit,
"cpp": CppToolkit,
"go": GoToolkit,
"java": JavaToolkit,
"javascript": JavascriptToolkit,
"python": PythonToolkit,
"ruby": RubyToolkit,
"rust": RustToolkit,
"typescript": TypescriptToolkit
}
Supported_queries = {
"repository": "Repository",
"directory": "Directory",
"file": "File",
"module": "Module",
"function": "Function",
"class": "Class",
"struct": "Struct",
"enum": "Enum",
"union": "Union",
"macro": "Macro",
"variable": "Variable"
}
def __init__(self, db_manager: DatabaseManager):
self.db_manager = db_manager
def advanced_language_query(self, language: str, query: str):
# Validating whether query is valid or not
query = query.strip().lower()
if query not in self.Supported_queries:
raise ValueError(
f"Unsupported query type '{query}'"
f"Supported: {', '.join(self.Supported_queries.keys())}"
)
label = self.Supported_queries[query]
# Set toolkit for the specified language
language = language.lower()
if language not in self.TOOLKITS:
raise ValueError(f"Unsupported language: {language}")
self.toolkit = self.TOOLKITS[language]()
# Getting the language query
cypher_query = self.toolkit.get_cypher_query(label)
try:
debug_log(f"Executing Cypher query: {cypher_query}")
with self.db_manager.get_driver().session() as session:
result = session.run(cypher_query)
# Convert results to a list of dictionaries for clean JSON serialization
records = [record.data() for record in result]
return {
"success": True,
"language": language,
"query": cypher_query,
"results": records
}
except Exception as e:
debug_log(f"Error executing Cypher query: {str(e)}")
return {
"error": "An unexpected error occurred while executing the query.",
"details": str(e)
}
```
--------------------------------------------------------------------------------
/docs/docs/use_cases.md:
--------------------------------------------------------------------------------
```markdown
# Real World Use Cases
CodeGraphContext can be a powerful ally in your daily coding journey. Here are some real-world scenarios where it can significantly boost your productivity and understanding of a codebase:
1. **Onboarding New Developers:** A new team member can quickly get up to speed by asking questions like:
- "Where is the authentication logic handled?"
- "Show me the main entry point of the application."
2. **Impact Analysis:** Before making a change, assess the potential ripple effects:
- "What other parts of the code will be affected if I change the `calculate_total` function?"
3. **Code Review:** Gain context on pull requests faster:
- "Show me the callers of this new function."
- "Does this change introduce any new dependencies?"
4. **Debugging:** Trace execution flows to pinpoint the source of a bug:
- "Show me the call chain from `handle_request` to `process_payment`."
5. **Refactoring:** Identify and plan large-scale code changes:
- "Find all instances of the deprecated `OldApiClass`."
- "List all functions that use the `urllib` library so I can replace them with `requests`."
6. **Identifying Code Smells:** Proactively find areas that need improvement:
- "Find the 10 most complex functions in the codebase."
- "Show me functions with more than 5 arguments."
7. **Security Audits:** Search for potentially vulnerable code patterns:
- "Find all functions that use the `eval` function."
- "Show me where raw SQL queries are being executed."
8. **Automated Documentation:** Use the tool's understanding of the code to generate documentation. (This is what this agent is doing!)
9. **Dependency Management:** Understand how your project uses its dependencies:
- "Which files import the `requests` library?"
- "Are there any circular dependencies between modules?"
10. **Cleaning Up Unused Code:** Keep your codebase lean and maintainable:
- "Is there any dead or unused code in this project?"
11. **Exploring a Large Codebase:** Navigate large, unfamiliar projects with ease:
- "List all the classes in the `core` module."
- "What are the top-level functions in the `utils` directory?"
12. **Enforcing Coding Standards:** Check for adherence to team conventions:
- "Find all functions that are not decorated with `@log_execution`."
- "Show me all public methods that don't have a docstring."
13. **Discovering API Usage:** Find examples of how to use internal or external APIs:
- "Show me how other parts of the code use the `UserService`."
14. **Improving Test Coverage:** Identify areas that may lack test coverage:
- "Find all functions that are not called by any test files."
15. **Visualizing Code Structure:** Get a bird's-eye view of your project's architecture:
- "Generate a graph visualization of the `auth` module and its dependencies."
16. **Learning a New Framework:** Understand how a new framework operates by exploring its source code.
17. **Code Archeology:** Investigate legacy code to understand its history and purpose.
18. **Planning a Migration:** Identify all points of contact when migrating a library or framework:
- "Find all the places where the `old_payment_gateway` is used."
19. **Knowledge Sharing:** Use the code graph as a centralized, always-up-to-date knowledge base for your team.
20. **Automated Code Reviews:** Integrate CodeGraphContext into your CI/CD pipeline to automatically flag potential issues in pull requests.
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.stemmer.support.min.js:
--------------------------------------------------------------------------------
```javascript
!function(r,t){"function"==typeof define&&define.amd?define(t):"object"==typeof exports?module.exports=t():t()(r.lunr)}(this,function(){return function(r){r.stemmerSupport={Among:function(r,t,i,s){if(this.toCharArray=function(r){for(var t=r.length,i=new Array(t),s=0;s<t;s++)i[s]=r.charCodeAt(s);return i},!r&&""!=r||!t&&0!=t||!i)throw"Bad Among initialisation: s:"+r+", substring_i: "+t+", result: "+i;this.s_size=r.length,this.s=this.toCharArray(r),this.substring_i=t,this.result=i,this.method=s},SnowballProgram:function(){var r;return{bra:0,ket:0,limit:0,cursor:0,limit_backward:0,setCurrent:function(t){r=t,this.cursor=0,this.limit=t.length,this.limit_backward=0,this.bra=this.cursor,this.ket=this.limit},getCurrent:function(){var t=r;return r=null,t},in_grouping:function(t,i,s){if(this.cursor<this.limit){var e=r.charCodeAt(this.cursor);if(e<=s&&e>=i&&(e-=i,t[e>>3]&1<<(7&e)))return this.cursor++,!0}return!1},in_grouping_b:function(t,i,s){if(this.cursor>this.limit_backward){var e=r.charCodeAt(this.cursor-1);if(e<=s&&e>=i&&(e-=i,t[e>>3]&1<<(7&e)))return this.cursor--,!0}return!1},out_grouping:function(t,i,s){if(this.cursor<this.limit){var e=r.charCodeAt(this.cursor);if(e>s||e<i)return this.cursor++,!0;if(e-=i,!(t[e>>3]&1<<(7&e)))return this.cursor++,!0}return!1},out_grouping_b:function(t,i,s){if(this.cursor>this.limit_backward){var e=r.charCodeAt(this.cursor-1);if(e>s||e<i)return this.cursor--,!0;if(e-=i,!(t[e>>3]&1<<(7&e)))return this.cursor--,!0}return!1},eq_s:function(t,i){if(this.limit-this.cursor<t)return!1;for(var s=0;s<t;s++)if(r.charCodeAt(this.cursor+s)!=i.charCodeAt(s))return!1;return this.cursor+=t,!0},eq_s_b:function(t,i){if(this.cursor-this.limit_backward<t)return!1;for(var s=0;s<t;s++)if(r.charCodeAt(this.cursor-t+s)!=i.charCodeAt(s))return!1;return this.cursor-=t,!0},find_among:function(t,i){for(var s=0,e=i,n=this.cursor,u=this.limit,o=0,h=0,c=!1;;){for(var a=s+(e-s>>1),f=0,l=o<h?o:h,_=t[a],m=l;m<_.s_size;m++){if(n+l==u){f=-1;break}if(f=r.charCodeAt(n+l)-_.s[m])break;l++}if(f<0?(e=a,h=l):(s=a,o=l),e-s<=1){if(s>0||e==s||c)break;c=!0}}for(;;){var _=t[s];if(o>=_.s_size){if(this.cursor=n+_.s_size,!_.method)return _.result;var b=_.method();if(this.cursor=n+_.s_size,b)return _.result}if((s=_.substring_i)<0)return 0}},find_among_b:function(t,i){for(var s=0,e=i,n=this.cursor,u=this.limit_backward,o=0,h=0,c=!1;;){for(var a=s+(e-s>>1),f=0,l=o<h?o:h,_=t[a],m=_.s_size-1-l;m>=0;m--){if(n-l==u){f=-1;break}if(f=r.charCodeAt(n-1-l)-_.s[m])break;l++}if(f<0?(e=a,h=l):(s=a,o=l),e-s<=1){if(s>0||e==s||c)break;c=!0}}for(;;){var _=t[s];if(o>=_.s_size){if(this.cursor=n-_.s_size,!_.method)return _.result;var b=_.method();if(this.cursor=n-_.s_size,b)return _.result}if((s=_.substring_i)<0)return 0}},replace_s:function(t,i,s){var e=s.length-(i-t),n=r.substring(0,t),u=r.substring(i);return r=n+s+u,this.limit+=e,this.cursor>=i?this.cursor+=e:this.cursor>t&&(this.cursor=t),e},slice_check:function(){if(this.bra<0||this.bra>this.ket||this.ket>this.limit||this.limit>r.length)throw"faulty slice operation"},slice_from:function(r){this.slice_check(),this.replace_s(this.bra,this.ket,r)},slice_del:function(){this.slice_from("")},insert:function(r,t,i){var s=this.replace_s(r,t,i);r<=this.bra&&(this.bra+=s),r<=this.ket&&(this.ket+=s)},slice_to:function(){return this.slice_check(),r.substring(this.bra,this.ket)},eq_v_b:function(r){return this.eq_s_b(r.length,r)}}}},r.trimmerSupport={generateTrimmer:function(r){var t=new RegExp("^[^"+r+"]+"),i=new RegExp("[^"+r+"]+$");return function(r){return"function"==typeof r.update?r.update(function(r){return r.replace(t,"").replace(i,"")}):r.replace(t,"").replace(i,"")}}}}});
```
--------------------------------------------------------------------------------
/src/codegraphcontext/cli/setup_macos.py:
--------------------------------------------------------------------------------
```python
# src/codegraphcontext/cli/setup_macos.py
import platform
import time
from pathlib import Path
def _has_brew(run_command, console) -> bool:
return run_command(["which", "brew"], console, check=False) is not None
def _brew_install_neo4j(run_command, console) -> str:
if run_command(["brew", "install", "neo4j@5"], console, check=False):
return "neo4j@5"
if run_command(["brew", "install", "neo4j"], console, check=False):
return "neo4j"
return ""
def _brew_start(service: str, run_command, console) -> bool:
return run_command(["brew", "services", "start", service], console, check=False) is not None
def _set_initial_password(new_pw: str, run_command, console) -> bool:
cmd = [
"cypher-shell",
"-u", "neo4j",
"-p", "neo4j",
f"ALTER CURRENT USER SET PASSWORD FROM 'neo4j' TO '{new_pw}'",
]
return run_command(cmd, console, check=False) is not None
def setup_macos_binary(console, prompt, run_command, _generate_mcp_json):
"""Automates Neo4j install & config on macOS via Homebrew."""
os_name = platform.system()
console.print(f"Detected Operating System: [bold yellow]{os_name}[/bold yellow]")
if os_name != "Darwin":
console.print("[yellow]This installer is for macOS only.[/yellow]")
return
console.print("[bold]Starting automated Neo4j installation for macOS.[/bold]")
if not prompt([{
"type": "confirm",
"message": "Proceed with Homebrew-based install of Neo4j?",
"name": "proceed",
"default": True
}]).get("proceed"):
return
console.print("\n[bold]Step: Checking for Homebrew...[/bold]")
if not _has_brew(run_command, console):
console.print(
"[bold red]Homebrew not found.[/bold red] "
"Install from [bold blue]https://brew.sh[/bold blue] and re-run this setup."
)
return
console.print("\n[bold]Step: Installing Neo4j via Homebrew...[/bold]")
service = _brew_install_neo4j(run_command, console)
if not service:
console.print("[bold red]Failed to install Neo4j via Homebrew.[/bold red]")
return
console.print(f"\n[bold]Step: Starting Neo4j service ({service})...[/bold]")
if not _brew_start(service, run_command, console):
console.print("[bold red]Failed to start Neo4j with brew services.[/bold red]")
return
while True:
answers = prompt([
{"type": "password", "message": "Enter a new password for Neo4j:", "name": "pw"},
{"type": "password", "message": "Confirm the new password:", "name": "pw2"},
]) or {}
if not answers:
return
pw, pw2 = answers.get("pw"), answers.get("pw2")
if pw and pw == pw2:
new_password = pw
break
console.print("[red]Passwords do not match or are empty. Please try again.[/red]")
console.print("\n[yellow]Waiting 10 seconds for Neo4j to finish starting...[/yellow]")
time.sleep(10)
console.print("\n[bold]Step: Setting initial password with cypher-shell...[/bold]")
if not _set_initial_password(new_password, run_command, console):
console.print(
"[bold red]Failed to set the initial password.[/bold red]\n"
"Try manually:\n"
" cypher-shell -u neo4j -p neo4j \"ALTER CURRENT USER SET PASSWORD FROM 'neo4j' TO '<your_pw>'\""
)
return
creds = {"uri": "neo4j://localhost:7687", "username": "neo4j", "password": new_password}
_generate_mcp_json(creds)
env_path = Path.home() / ".codegraphcontext" / ".env"
console.print(f"\n[bold green]All done![/bold green] Neo4j running. Credentials saved to: [bold]{env_path}[/bold]")
```
--------------------------------------------------------------------------------
/website/src/components/ui/dialog.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
```
--------------------------------------------------------------------------------
/tests/sample_project_rust/src/basic_functions.rs:
--------------------------------------------------------------------------------
```rust
// basic_functions.rs - Demonstrates basic Rust function patterns and ownership
use std::fmt;
/// Simple function with single return value
pub fn simple_function(x: i32) -> i32 {
x * 2
}
/// Multiple return values using tuple
pub fn multiple_returns(a: i32, b: i32) -> (i32, i32, i32) {
(a + b, a - b, a * b)
}
/// Function with Result return type for error handling
pub fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
Err("Division by zero".to_string())
} else {
Ok(a / b)
}
}
/// Function with Option return type
pub fn find_first_even(numbers: &[i32]) -> Option<i32> {
for &num in numbers {
if num % 2 == 0 {
return Some(num);
}
}
None
}
/// Function demonstrating ownership transfer
pub fn take_ownership(s: String) -> usize {
let len = s.len();
println!("Taking ownership of: {}", s);
len
}
/// Function borrowing immutably
pub fn borrow_read(s: &String) -> usize {
s.len()
}
/// Function borrowing mutably
pub fn borrow_write(s: &mut String) {
s.push_str(" - modified");
}
/// Function returning borrowed reference with lifetime
pub fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
/// Generic function with trait bound
pub fn print_it<T: fmt::Display>(item: T) {
println!("Item: {}", item);
}
/// Generic function with multiple trait bounds
pub fn compare_and_print<T: PartialOrd + fmt::Display>(a: T, b: T) {
if a > b {
println!("{} is greater than {}", a, b);
} else {
println!("{} is less than or equal to {}", a, b);
}
}
/// Higher-order function taking closure
pub fn apply_twice<F>(f: F, x: i32) -> i32
where
F: Fn(i32) -> i32,
{
f(f(x))
}
/// Function returning closure
pub fn make_multiplier(factor: i32) -> impl Fn(i32) -> i32 {
move |x| x * factor
}
/// Recursive function
pub fn factorial(n: u32) -> u32 {
match n {
0 | 1 => 1,
_ => n * factorial(n - 1),
}
}
/// Fibonacci using recursion
pub fn fibonacci(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}
/// Function with slice parameter
pub fn sum_slice(numbers: &[i32]) -> i32 {
numbers.iter().sum()
}
/// Function with vector parameter (takes ownership)
pub fn sort_vector(mut vec: Vec<i32>) -> Vec<i32> {
vec.sort();
vec
}
/// Function demonstrating early return
pub fn validate_age(age: i32) -> Result<i32, String> {
if age < 0 {
return Err("Age cannot be negative".to_string());
}
if age > 150 {
return Err("Age is unrealistic".to_string());
}
Ok(age)
}
/// Function with default parameters using Option
pub fn greet(name: &str, title: Option<&str>) -> String {
match title {
Some(t) => format!("Hello, {} {}", t, name),
None => format!("Hello, {}", name),
}
}
/// Variadic-like function using slice
pub fn sum_all(numbers: &[i32]) -> i32 {
numbers.iter().sum()
}
/// Function with multiple lifetimes
pub fn first_word<'a, 'b>(s1: &'a str, s2: &'b str) -> &'a str {
s1.split_whitespace().next().unwrap_or(s1)
}
/// Associated function (like static method)
pub fn from_string(s: String) -> Result<i32, std::num::ParseIntError> {
s.parse()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple_function() {
assert_eq!(simple_function(5), 10);
}
#[test]
fn test_multiple_returns() {
let (sum, diff, prod) = multiple_returns(10, 3);
assert_eq!(sum, 13);
assert_eq!(diff, 7);
assert_eq!(prod, 30);
}
#[test]
fn test_divide() {
assert_eq!(divide(10, 2), Ok(5));
assert!(divide(10, 0).is_err());
}
#[test]
fn test_factorial() {
assert_eq!(factorial(5), 120);
}
}
```
--------------------------------------------------------------------------------
/website/src/hooks/use-toast.ts:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import type { ToastActionElement, ToastProps } from "@/components/ui/toast";
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1000000;
type ToasterToast = ToastProps & {
id: string;
title?: React.ReactNode;
description?: React.ReactNode;
action?: ToastActionElement;
};
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const;
let count = 0;
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER;
return count.toString();
}
type ActionType = typeof actionTypes;
type Action =
| {
type: ActionType["ADD_TOAST"];
toast: ToasterToast;
}
| {
type: ActionType["UPDATE_TOAST"];
toast: Partial<ToasterToast>;
}
| {
type: ActionType["DISMISS_TOAST"];
toastId?: ToasterToast["id"];
}
| {
type: ActionType["REMOVE_TOAST"];
toastId?: ToasterToast["id"];
};
interface State {
toasts: ToasterToast[];
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return;
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId);
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
});
}, TOAST_REMOVE_DELAY);
toastTimeouts.set(toastId, timeout);
};
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
};
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) => (t.id === action.toast.id ? { ...t, ...action.toast } : t)),
};
case "DISMISS_TOAST": {
const { toastId } = action;
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId);
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id);
});
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t,
),
};
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
};
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
};
}
};
const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] };
function dispatch(action: Action) {
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
}
type Toast = Omit<ToasterToast, "id">;
function toast({ ...props }: Toast) {
const id = genId();
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
});
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id });
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss();
},
},
});
return {
id: id,
dismiss,
update,
};
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState);
React.useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
};
}
export { useToast, toast };
```
--------------------------------------------------------------------------------
/website/src/components/ui/form.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { Slot } from "@radix-ui/react-slot";
import { Controller, ControllerProps, FieldPath, FieldValues, FormProvider, useFormContext } from "react-hook-form";
import { cn } from "@/lib/utils";
import { Label } from "@/components/ui/label";
const Form = FormProvider;
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName;
};
const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue);
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
);
};
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>");
}
const { id } = itemContext;
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
};
type FormItemContextValue = {
id: string;
};
const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue);
const FormItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
);
},
);
FormItem.displayName = "FormItem";
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField();
return <Label ref={ref} className={cn(error && "text-destructive", className)} htmlFor={formItemId} {...props} />;
});
FormLabel.displayName = "FormLabel";
const FormControl = React.forwardRef<React.ElementRef<typeof Slot>, React.ComponentPropsWithoutRef<typeof Slot>>(
({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`}
aria-invalid={!!error}
{...props}
/>
);
},
);
FormControl.displayName = "FormControl";
const FormDescription = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField();
return <p ref={ref} id={formDescriptionId} className={cn("text-sm text-muted-foreground", className)} {...props} />;
},
);
FormDescription.displayName = "FormDescription";
const FormMessage = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message) : children;
if (!body) {
return null;
}
return (
<p ref={ref} id={formMessageId} className={cn("text-sm font-medium text-destructive", className)} {...props}>
{body}
</p>
);
},
);
FormMessage.displayName = "FormMessage";
export { useFormField, Form, FormItem, FormLabel, FormControl, FormDescription, FormMessage, FormField };
```
--------------------------------------------------------------------------------
/docs/docs/troubleshooting.md:
--------------------------------------------------------------------------------
```markdown
# CodeGraphContext Troubleshooting Guide
Use this checklist whenever `cgc setup` or `cgc start` doesn’t behave as expected. It keeps the happy path short, but includes the fallback steps when something goes wrong.
## 1. Prerequisites at a glance
- **Windows + PowerShell** commands below assume the `py` launcher. Adapt to `python3` if you’re on macOS/Linux.
- **Python 3.11** (recommended). Run `py -3.11 --version` to confirm.
- **Neo4j account** (only required if you prefer Neo4j AuraDB instead of Docker).
## 2. Create and activate a virtual environment
From the repository root (`CodeGraphContext/`):
```powershell
py -3.11 -m venv venv
.\venv\Scripts\python.exe -m pip install --upgrade pip
```
- On Windows, Neo4j driver 6.x can crash with `AttributeError: socket.EAI_ADDRFAMILY`. If you see that, run:
```powershell
.\venv\Scripts\python.exe -m pip install "neo4j<6"
```
## 3. Run the setup wizard (preferred)
Launch the wizard:
```powershell
.\venv\Scripts\cgc.exe setup
```
> **Tip:** If you want the wizard to spin up a local Neo4j instance for you, make sure **Docker Desktop** is installed and running before you launch `cgc setup`. If Docker isn’t running, the setup wizard will fail when it tries to install Neo4j locally.
What happens next:
- The wizard checks for Docker. If it’s running, it can auto-provision a local Neo4j instance for you.
- Alternatively, you can supply credentials for an existing Neo4j AuraDB database.
- At the end, it generates:
- `mcp.json` in your project directory (stores the MCP server command + env vars).
- `~/.codegraphcontext/.env` containing `NEO4J_URI`, `NEO4J_USERNAME`, `NEO4J_PASSWORD`.
Make sure the Docker container (or remote Neo4j) is still running before you start the server.
## 4. Start the MCP server
Once the wizard completes successfully:
```powershell
.\venv\Scripts\cgc.exe start
```
Expected output includes:
```text
Starting CodeGraphContext Server...
...
MCP Server is running. Waiting for requests...
```
If you instead see:
```text
Configuration Error: Neo4j credentials must be set via environment variables
```
then either no credentials were saved, or the wizard was skipped—see the manual alternative below.
## 5. Manual credential setup (fallback)
If you prefer not to use the wizard or need to fix a broken configuration:
1. Create a `mcp.json` (or edit the one that exists) in the repository root:
```json
{
"mcpServers": {
"CodeGraphContext": {
"command": "cgc",
"args": ["start"],
"env": {
"NEO4J_URI": "neo4j+s://YOUR-HOSTNAME:7687",
"NEO4J_USERNAME": "neo4j",
"NEO4J_PASSWORD": "super-secret-password"
}
}
}
}
```
2. (Optional) Also create `%USERPROFILE%\.codegraphcontext\.env` with the same key/value pairs. The CLI loads that file automatically.
3. Re-run:
```powershell
.\venv\Scripts\cgc.exe start
```
## 6. Common issues & fixes
| Symptom | Likely Cause | Fix |
| --- | --- | --- |
| `Configuration Error: Neo4j credentials must be set…` | `mcp.json`/`.env` missing or empty | Run `cgc setup` again **with Docker running**, or create the files manually (section 5). |
| `AttributeError: socket.EAI_ADDRFAMILY` | Neo4j 6.x bug on Windows | Install the 5.x driver: `.\venv\Scripts\python.exe -m pip install "neo4j<6"` and retry. |
| Setup wizard fails while pulling Docker image | Docker Desktop not running or Docker permissions missing | Start Docker Desktop, wait for it to report “Running”, then rerun `cgc setup`. |
| Server exits immediately with no log | Neo4j instance is offline | Check Docker container status or AuraDB dashboard; restart Neo4j and call `cgc start` again. |
## 7. After the server is running
- Keep the virtual environment active whenever you run `cgc` commands.
- Use `pytest` from the same env to run tests:
```powershell
.\venv\Scripts\pytest
```
- Front-end website lives under `website/` if you need to run `npm run dev`.
When in doubt, re-run the wizard with Docker active—it regenerates the configuration files without touching your code. Let me know if any section needs clarifying! :)
```
--------------------------------------------------------------------------------
/organizer/troubleshoot.md:
--------------------------------------------------------------------------------
```markdown
# CodeGraphContext Troubleshooting Guide
Use this checklist whenever `cgc setup` or `cgc start` doesn’t behave as expected. It keeps the happy path short, but includes the fallback steps when something goes wrong.
## 1. Prerequisites at a glance
- **Windows + PowerShell** commands below assume the `py` launcher. Adapt to `python3` if you’re on macOS/Linux.
- **Python 3.11** (recommended). Run `py -3.11 --version` to confirm.
- **Git** for cloning the repository.
- **Docker Desktop** installed *and running* before you launch `cgc setup` if you want the wizard to spin up a local Neo4j for you.
- **Neo4j account** (only required if you prefer Neo4j AuraDB instead of Docker).
> **Tip:** If Docker isn’t running, the setup wizard will fail when it tries to install Neo4j locally.
## 2. Create and activate a virtual environment
From the repository root (`CodeGraphContext/`):
```powershell
py -3.11 -m venv venv
.\venv\Scripts\python.exe -m pip install --upgrade pip
```
- On Windows, Neo4j driver 6.x can crash with `AttributeError: socket.EAI_ADDRFAMILY`. If you see that, run:
```powershell
.\venv\Scripts\python.exe -m pip install "neo4j<6"
```
## 3. Run the setup wizard (preferred)
Launch the wizard:
```powershell
.\venv\Scripts\cgc.exe setup
```
What happens next:
- The wizard checks for Docker. If it’s running, it can auto-provision a local Neo4j instance for you.
- Alternatively, you can supply credentials for an existing Neo4j AuraDB database.
- At the end, it generates:
- `mcp.json` in your project directory (stores the MCP server command + env vars).
- `~/.codegraphcontext/.env` containing `NEO4J_URI`, `NEO4J_USERNAME`, `NEO4J_PASSWORD`.
Make sure the Docker container (or remote Neo4j) is still running before you start the server.
## 4. Start the MCP server
Once the wizard completes successfully:
```powershell
.\venv\Scripts\cgc.exe start
```
Expected output includes:
```text
Starting CodeGraphContext Server...
...
MCP Server is running. Waiting for requests...
```
If you instead see:
```text
Configuration Error: Neo4j credentials must be set via environment variables
```
then either no credentials were saved, or the wizard was skipped—see the manual alternative below.
## 5. Manual credential setup (fallback)
If you prefer not to use the wizard or need to fix a broken configuration:
1. Create a `mcp.json` (or edit the one that exists) in the repository root:
```json
{
"mcpServers": {
"CodeGraphContext": {
"command": "cgc",
"args": ["start"],
"env": {
"NEO4J_URI": "neo4j+s://YOUR-HOSTNAME:7687",
"NEO4J_USERNAME": "neo4j",
"NEO4J_PASSWORD": "super-secret-password"
}
}
}
}
```
2. (Optional) Also create `%USERPROFILE%\.codegraphcontext\.env` with the same key/value pairs. The CLI loads that file automatically.
3. Re-run:
```powershell
.\venv\Scripts\cgc.exe start
```
## 6. Common issues & fixes
| Symptom | Likely Cause | Fix |
| --- | --- | --- |
| `Configuration Error: Neo4j credentials must be set…` | `mcp.json`/`.env` missing or empty | Run `cgc setup` again **with Docker running**, or create the files manually (section 5). |
| `AttributeError: socket.EAI_ADDRFAMILY` | Neo4j 6.x bug on Windows | Install the 5.x driver: `.\venv\Scripts\python.exe -m pip install "neo4j<6"` and retry. |
| Setup wizard fails while pulling Docker image | Docker Desktop not running or Docker permissions missing | Start Docker Desktop, wait for it to report “Running”, then rerun `cgc setup`. |
| Server exits immediately with no log | Neo4j instance is offline | Check Docker container status or AuraDB dashboard; restart Neo4j and call `cgc start` again. |
## 7. After the server is running
- Keep the virtual environment active whenever you run `cgc` commands.
- Use `pytest` from the same env to run tests:
```powershell
.\venv\Scripts\pytest
```
- Front-end website lives under `website/` if you need to run `npm run dev`.
When in doubt, re-run the wizard with Docker active—it regenerates the configuration files without touching your code. Let me know if any section needs clarifying! :)
```
--------------------------------------------------------------------------------
/website/src/components/ui/sheet.tsx:
--------------------------------------------------------------------------------
```typescript
import * as SheetPrimitive from "@radix-ui/react-dialog";
import { cva, type VariantProps } from "class-variance-authority";
import { X } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
const Sheet = SheetPrimitive.Root;
const SheetTrigger = SheetPrimitive.Trigger;
const SheetClose = SheetPrimitive.Close;
const SheetPortal = SheetPrimitive.Portal;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
ref={ref}
/>
));
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
const sheetVariants = cva(
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
{
variants: {
side: {
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
bottom:
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
right:
"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
},
},
defaultVariants: {
side: "right",
},
},
);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<React.ElementRef<typeof SheetPrimitive.Content>, SheetContentProps>(
({ side = "right", className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
{children}
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
),
);
SheetContent.displayName = SheetPrimitive.Content.displayName;
const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
);
SheetHeader.displayName = "SheetHeader";
const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
);
SheetFooter.displayName = "SheetFooter";
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title ref={ref} className={cn("text-lg font-semibold text-foreground", className)} {...props} />
));
SheetTitle.displayName = SheetPrimitive.Title.displayName;
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
SheetDescription.displayName = SheetPrimitive.Description.displayName;
export {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetOverlay,
SheetPortal,
SheetTitle,
SheetTrigger,
};
```
--------------------------------------------------------------------------------
/tests/sample_project_go/interfaces.go:
--------------------------------------------------------------------------------
```go
// interfaces.go - Demonstrates Go interfaces
package main
import (
"fmt"
"math"
)
// Shape is a basic interface
type Shape interface {
Area() float64
Perimeter() float64
}
// Drawable extends Shape interface
type Drawable interface {
Shape
Draw() string
}
// Named is a simple interface
type Named interface {
GetName() string
}
// Circle implements Shape
type Circle struct {
Radius float64
Name string
}
// Rectangle implements Shape
type Rectangle struct {
Width float64
Height float64
Name string
}
// Triangle implements Shape
type Triangle struct {
A, B, C float64
Name string
}
// Area implements Shape interface for Circle
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
// Perimeter implements Shape interface for Circle
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.Radius
}
// Draw implements Drawable interface for Circle
func (c Circle) Draw() string {
return fmt.Sprintf("Drawing circle with radius %.2f", c.Radius)
}
// GetName implements Named interface for Circle
func (c Circle) GetName() string {
return c.Name
}
// Area implements Shape interface for Rectangle
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// Perimeter implements Shape interface for Rectangle
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
// Draw implements Drawable interface for Rectangle
func (r Rectangle) Draw() string {
return fmt.Sprintf("Drawing rectangle %.2fx%.2f", r.Width, r.Height)
}
// GetName implements Named interface for Rectangle
func (r Rectangle) GetName() string {
return r.Name
}
// Area implements Shape interface for Triangle
func (t Triangle) Area() float64 {
// Heron's formula
s := (t.A + t.B + t.C) / 2
return math.Sqrt(s * (s - t.A) * (s - t.B) * (s - t.C))
}
// Perimeter implements Shape interface for Triangle
func (t Triangle) Perimeter() float64 {
return t.A + t.B + t.C
}
// GetName implements Named interface for Triangle
func (t Triangle) GetName() string {
return t.Name
}
// CalculateTotalArea accepts interface and calculates total
func CalculateTotalArea(shapes []Shape) float64 {
total := 0.0
for _, shape := range shapes {
total += shape.Area()
}
return total
}
// PrintShapeInfo uses interface for polymorphism
func PrintShapeInfo(s Shape) {
fmt.Printf("Area: %.2f, Perimeter: %.2f\n", s.Area(), s.Perimeter())
}
// DrawIfPossible uses type assertion
func DrawIfPossible(s Shape) string {
if drawable, ok := s.(Drawable); ok {
return drawable.Draw()
}
return "Shape is not drawable"
}
// DescribeShape uses type switch
func DescribeShape(s Shape) string {
switch v := s.(type) {
case Circle:
return fmt.Sprintf("Circle with radius %.2f", v.Radius)
case Rectangle:
return fmt.Sprintf("Rectangle with dimensions %.2fx%.2f", v.Width, v.Height)
case Triangle:
return fmt.Sprintf("Triangle with sides %.2f, %.2f, %.2f", v.A, v.B, v.C)
default:
return "Unknown shape"
}
}
// EmptyInterface demonstrates empty interface usage
func EmptyInterface(data interface{}) string {
switch v := data.(type) {
case int:
return fmt.Sprintf("Integer: %d", v)
case string:
return fmt.Sprintf("String: %s", v)
case Shape:
return fmt.Sprintf("Shape with area: %.2f", v.Area())
default:
return fmt.Sprintf("Unknown type: %T", v)
}
}
// InterfaceComposition demonstrates interface embedding
type ComplexShape interface {
Shape
Named
Volume() float64
}
// ProcessShapes processes multiple shapes
func ProcessShapes(shapes ...Shape) map[string]float64 {
results := make(map[string]float64)
totalArea := 0.0
totalPerimeter := 0.0
for _, shape := range shapes {
totalArea += shape.Area()
totalPerimeter += shape.Perimeter()
}
results["total_area"] = totalArea
results["total_perimeter"] = totalPerimeter
results["count"] = float64(len(shapes))
return results
}
func demonstrateInterfaces() {
circle := Circle{Radius: 5.0, Name: "MyCircle"}
rectangle := Rectangle{Width: 10.0, Height: 5.0, Name: "MyRectangle"}
shapes := []Shape{circle, rectangle}
fmt.Printf("Total area: %.2f\n", CalculateTotalArea(shapes))
fmt.Println(DescribeShape(circle))
fmt.Println(DrawIfPossible(circle))
}
```
--------------------------------------------------------------------------------
/website/src/components/ExamplesSection.tsx:
--------------------------------------------------------------------------------
```typescript
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { MessageCircle, Search, Eye, BarChart3 } from "lucide-react";
import { motion } from "framer-motion";
const examplesData = [
{
icon: MessageCircle,
category: "Indexing",
title: "Add Projects to Graph",
examples: [
"Please index the code in the `/path/to/my-project` directory.",
"Add the project at `~/dev/my-app` to the code graph."
]
},
{
icon: Search,
category: "Analysis",
title: "Code Relationships",
examples: [
"Show me all functions that call `process_data()`",
"Find the class hierarchy for `BaseProcessor`"
]
},
{
icon: Eye,
category: "Monitoring",
title: "Live Updates",
examples: [
"Watch the `/project` directory for changes.",
"Keep the graph updated for my active development."
]
},
{
icon: BarChart3,
category: "Insights",
title: "Code Quality",
examples: [
"Find dead code in my project",
"Show the most complex functions by cyclomatic complexity"
]
}
];
const ExamplesSection = () => {
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">
Natural Language Interface
</h2>
<p className="text-xl text-muted-foreground max-w-3xl mx-auto">
Interact with your code graph using plain English. No complex queries or syntax to learn.
</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
{examplesData.map((example, index) => (
<div key={index} data-aos="fade-up" data-aos-delay={index * 100}>
<Card className="h-full border-border/50 group animate-float-up bg-white/95 dark:bg-card/50 shadow-sm hover:shadow-lg transition-shadow duration-300">
<CardHeader>
<div className="flex items-center gap-4 mb-4">
<div className="p-3 rounded-xl bg-primary/5 border border-primary/15 group-hover:bg-primary/10 transition-colors dark:bg-primary/20 dark:border-primary/30">
<example.icon className="h-6 w-6 text-primary" />
</div>
<div>
<Badge variant="secondary" className="mb-2">{example.category}</Badge>
<CardTitle className="text-xl font-semibold">{example.title}</CardTitle>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
{example.examples.map((text, idx) => (
<div key={idx} className="p-3 rounded-md border-l-4 border-accent/30 bg-muted/30 hover:border-accent/60 transition-colors">
<p className="text-sm text-muted-foreground italic">"{text}"</p>
</div>
))}
</div>
</CardContent>
</Card>
</div>
))}
</div>
<div className="text-center mt-16" data-aos="fade-up" data-aos-delay="200">
<Card className="max-w-2xl mx-auto bg-white/95 dark:bg-card/50 shadow-sm p-2">
<CardContent className="pt-8">
<h3 className="text-2xl font-bold mb-4">Ready to enhance your AI assistant?</h3>
<p className="text-muted-foreground mb-6">
Start building intelligent code understanding today with CodeGraphContext.
</p>
<div className="p-3 rounded-md bg-muted/40 max-w-md mx-auto border shadow-inner">
<code className="text-accent font-mono">$ pip install codegraphcontext</code>
</div>
</CardContent>
</Card>
</div>
</div>
</section>
);
};
export default ExamplesSection;
```
--------------------------------------------------------------------------------
/website/src/components/ui/alert-dialog.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
)}
{...props}
ref={ref}
/>
));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
);
AlertDialogHeader.displayName = "AlertDialogHeader";
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)} {...props} />
);
AlertDialogFooter.displayName = "AlertDialogFooter";
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title ref={ref} className={cn("text-lg font-semibold", className)} {...props} />
));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
{...props}
/>
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};
```
--------------------------------------------------------------------------------
/tests/sample_project_go/util/helpers.go:
--------------------------------------------------------------------------------
```go
// Package util provides utility functions for the sample project
package util
import (
"fmt"
"strings"
)
// StringUtils provides string utility functions
type StringUtils struct{}
// Reverse reverses a string
func (su StringUtils) Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
// IsPalindrome checks if a string is a palindrome
func (su StringUtils) IsPalindrome(s string) bool {
s = strings.ToLower(strings.ReplaceAll(s, " ", ""))
return s == su.Reverse(s)
}
// MathUtils provides math utility functions
type MathUtils struct{}
// Factorial calculates factorial
func (mu MathUtils) Factorial(n int) int {
if n <= 1 {
return 1
}
return n * mu.Factorial(n-1)
}
// Fibonacci calculates fibonacci number
func (mu MathUtils) Fibonacci(n int) int {
if n <= 1 {
return n
}
return mu.Fibonacci(n-1) + mu.Fibonacci(n-2)
}
// GCD calculates greatest common divisor
func (mu MathUtils) GCD(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
// LCM calculates least common multiple
func (mu MathUtils) LCM(a, b int) int {
return (a * b) / mu.GCD(a, b)
}
// SliceUtils provides slice utility functions
type SliceUtils struct{}
// Sum calculates sum of integers
func (su SliceUtils) Sum(nums []int) int {
total := 0
for _, num := range nums {
total += num
}
return total
}
// Average calculates average
func (su SliceUtils) Average(nums []int) float64 {
if len(nums) == 0 {
return 0
}
return float64(su.Sum(nums)) / float64(len(nums))
}
// Max finds maximum value
func (su SliceUtils) Max(nums []int) int {
if len(nums) == 0 {
return 0
}
max := nums[0]
for _, num := range nums {
if num > max {
max = num
}
}
return max
}
// Min finds minimum value
func (su SliceUtils) Min(nums []int) int {
if len(nums) == 0 {
return 0
}
min := nums[0]
for _, num := range nums {
if num < min {
min = num
}
}
return min
}
// Unique removes duplicates from slice
func (su SliceUtils) Unique(nums []int) []int {
seen := make(map[int]bool)
result := []int{}
for _, num := range nums {
if !seen[num] {
seen[num] = true
result = append(result, num)
}
}
return result
}
// Validator provides validation functions
type Validator struct{}
// IsEmail checks if string is valid email format (simplified)
func (v Validator) IsEmail(email string) bool {
return strings.Contains(email, "@") && strings.Contains(email, ".")
}
// IsURL checks if string is valid URL format (simplified)
func (v Validator) IsURL(url string) bool {
return strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://")
}
// IsEmpty checks if string is empty or whitespace
func (v Validator) IsEmpty(s string) bool {
return strings.TrimSpace(s) == ""
}
// Logger provides logging functionality
type Logger struct {
Prefix string
}
// NewLogger creates a new logger
func NewLogger(prefix string) *Logger {
return &Logger{Prefix: prefix}
}
// Info logs info message
func (l Logger) Info(message string) {
fmt.Printf("[%s] INFO: %s\n", l.Prefix, message)
}
// Error logs error message
func (l Logger) Error(message string) {
fmt.Printf("[%s] ERROR: %s\n", l.Prefix, message)
}
// Debug logs debug message
func (l Logger) Debug(message string) {
fmt.Printf("[%s] DEBUG: %s\n", l.Prefix, message)
}
// Helper functions (package-level)
// Capitalize capitalizes first letter of string
func Capitalize(s string) string {
if len(s) == 0 {
return s
}
return strings.ToUpper(s[:1]) + s[1:]
}
// Truncate truncates string to specified length
func Truncate(s string, length int) string {
if len(s) <= length {
return s
}
return s[:length] + "..."
}
// Contains checks if slice contains value
func Contains(slice []string, value string) bool {
for _, item := range slice {
if item == value {
return true
}
}
return false
}
// Map applies function to each element
func Map(slice []int, fn func(int) int) []int {
result := make([]int, len(slice))
for i, v := range slice {
result[i] = fn(v)
}
return result
}
// Filter filters slice based on predicate
func Filter(slice []int, predicate func(int) bool) []int {
result := []int{}
for _, v := range slice {
if predicate(v) {
result = append(result, v)
}
}
return result
}
```
--------------------------------------------------------------------------------
/docs/docs/server.md:
--------------------------------------------------------------------------------
```markdown
# MCPServer
The `MCPServer` class is the core of the CodeGraphContext application. It orchestrates all the major components, including database management, background job tracking, file system watching, and tool handling.
## Initialization
The server is initialized with an asyncio event loop. Upon initialization, it sets up the following components:
- `DatabaseManager`: Manages the connection to the Neo4j database.
- `JobManager`: Tracks the status of background jobs, such as code indexing.
- `CodeWatcher`: Monitors the file system for changes to keep the code graph up-to-date.
- `GraphBuilder`: Builds the code graph from the source code.
- `CodeFinder`: Provides tools for searching and analyzing the code graph.
## Tool Manifest
The `MCPServer` exposes a set of tools to the AI assistant. These tools are defined in the `_init_tools` method. Here is a list of available tools:
### `add_code_to_graph`
Performs a one-time scan of a local folder to add its code to the graph. Ideal for indexing libraries, dependencies, or projects not being actively modified. Returns a job ID for background processing.
### `check_job_status`
Check the status and progress of a background job.
### `list_jobs`
List all background jobs and their current status.
### `find_code`
Find relevant code snippets related to a keyword (e.g., function name, class name, or content).
### `analyze_code_relationships`
Analyze code relationships like 'who calls this function' or 'class hierarchy'. Supported query types include: find_callers, find_callees, find_all_callers, find_all_callees, find_importers, who_modifies, class_hierarchy, overrides, dead_code, call_chain, module_deps, variable_scope, find_complexity, find_functions_by_argument, find_functions_by_decorator.
### `watch_directory`
Performs an initial scan of a directory and then continuously monitors it for changes, automatically keeping the graph up-to-date. Ideal for projects under active development. Returns a job ID for the initial scan.
### `execute_cypher_query`
This is an advanced tool for directly querying the underlying Neo4j graph using a read-only Cypher query. It should be used as a fallback when other tools cannot answer very specific or complex questions about the code graph.
**Schema Overview:**
The code graph has the following structure:
* **Nodes:**
* `Repository`: Represents a project repository.
* `File`: Represents a single source code file.
* `Module`: Represents a package or a module.
* `Class`: Represents a class definition.
* `Function`: Represents a function or method definition.
* **Properties:**
* Nodes have properties like `name`, `path`, `cyclomatic_complexity` (for functions), and `code`.
* **Relationships:**
* `CONTAINS`: e.g., `(:File)-[:CONTAINS]->(:Function)`
* `CALLS`: e.g., `(:Function)-[:CALLS]->(:Function)`
* `IMPORTS`: e.g., `(:File)-[:IMPORTS]->(:Module)`
* `INHERITS`: e.g., `(:Class)-[:INHERITS]->(:Class)`
### `add_package_to_graph`
Add a Python package to Neo4j graph by discovering its location. Returns immediately with job ID.
### `find_dead_code`
Find potentially unused functions (dead code) across the entire indexed codebase, optionally excluding functions with specific decorators.
### `calculate_cyclomatic_complexity`
Calculate the cyclomatic complexity of a specific function to measure its complexity.
### `find_most_complex_functions`
Find the most complex functions in the codebase based on cyclomatic complexity.
### `list_indexed_repositories`
List all indexed repositories.
### `delete_repository`
Delete an indexed repository from the graph.
### `visualize_graph_query`
Generates a URL to visualize the results of a Cypher query in the Neo4j Browser. The user can open this URL in their web browser to see the graph visualization.
### `list_watched_paths`
Lists all directories currently being watched for live file changes.
### `unwatch_directory`
Stops watching a directory for live file changes.
## Other Methods
- `get_database_status()`: Returns the current connection status of the Neo4j database.
- `get_local_package_path(package_name)`: Finds the local installation path of a Python package.
- `run()`: Runs the main server loop, listening for JSON-RPC requests from stdin.
- `shutdown()`: Gracefully shuts down the server and its components.
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.sv.min.js:
--------------------------------------------------------------------------------
```javascript
/*!
* Lunr languages, `Swedish` 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.sv=function(){this.pipeline.reset(),this.pipeline.add(e.sv.trimmer,e.sv.stopWordFilter,e.sv.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.sv.stemmer))},e.sv.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.sv.trimmer=e.trimmerSupport.generateTrimmer(e.sv.wordCharacters),e.Pipeline.registerFunction(e.sv.trimmer,"trimmer-sv"),e.sv.stemmer=function(){var r=e.stemmerSupport.Among,n=e.stemmerSupport.SnowballProgram,t=new function(){function e(){var e,r=w.cursor+3;if(o=w.limit,0<=r||r<=w.limit){for(a=r;;){if(e=w.cursor,w.in_grouping(l,97,246)){w.cursor=e;break}if(w.cursor=e,w.cursor>=w.limit)return;w.cursor++}for(;!w.out_grouping(l,97,246);){if(w.cursor>=w.limit)return;w.cursor++}o=w.cursor,o<a&&(o=a)}}function t(){var e,r=w.limit_backward;if(w.cursor>=o&&(w.limit_backward=o,w.cursor=w.limit,w.ket=w.cursor,e=w.find_among_b(u,37),w.limit_backward=r,e))switch(w.bra=w.cursor,e){case 1:w.slice_del();break;case 2:w.in_grouping_b(d,98,121)&&w.slice_del()}}function i(){var e=w.limit_backward;w.cursor>=o&&(w.limit_backward=o,w.cursor=w.limit,w.find_among_b(c,7)&&(w.cursor=w.limit,w.ket=w.cursor,w.cursor>w.limit_backward&&(w.bra=--w.cursor,w.slice_del())),w.limit_backward=e)}function s(){var e,r;if(w.cursor>=o){if(r=w.limit_backward,w.limit_backward=o,w.cursor=w.limit,w.ket=w.cursor,e=w.find_among_b(m,5))switch(w.bra=w.cursor,e){case 1:w.slice_del();break;case 2:w.slice_from("lös");break;case 3:w.slice_from("full")}w.limit_backward=r}}var a,o,u=[new r("a",-1,1),new r("arna",0,1),new r("erna",0,1),new r("heterna",2,1),new r("orna",0,1),new r("ad",-1,1),new r("e",-1,1),new r("ade",6,1),new r("ande",6,1),new r("arne",6,1),new r("are",6,1),new r("aste",6,1),new r("en",-1,1),new r("anden",12,1),new r("aren",12,1),new r("heten",12,1),new r("ern",-1,1),new r("ar",-1,1),new r("er",-1,1),new r("heter",18,1),new r("or",-1,1),new r("s",-1,2),new r("as",21,1),new r("arnas",22,1),new r("ernas",22,1),new r("ornas",22,1),new r("es",21,1),new r("ades",26,1),new r("andes",26,1),new r("ens",21,1),new r("arens",29,1),new r("hetens",29,1),new r("erns",21,1),new r("at",-1,1),new r("andet",-1,1),new r("het",-1,1),new r("ast",-1,1)],c=[new r("dd",-1,-1),new r("gd",-1,-1),new r("nn",-1,-1),new r("dt",-1,-1),new r("gt",-1,-1),new r("kt",-1,-1),new r("tt",-1,-1)],m=[new r("ig",-1,1),new r("lig",0,1),new r("els",-1,1),new r("fullt",-1,3),new r("löst",-1,2)],l=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,32],d=[119,127,149],w=new n;this.setCurrent=function(e){w.setCurrent(e)},this.getCurrent=function(){return w.getCurrent()},this.stem=function(){var r=w.cursor;return e(),w.limit_backward=r,w.cursor=w.limit,t(),w.cursor=w.limit,i(),w.cursor=w.limit,s(),!0}};return function(e){return"function"==typeof e.update?e.update(function(e){return t.setCurrent(e),t.stem(),t.getCurrent()}):(t.setCurrent(e),t.stem(),t.getCurrent())}}(),e.Pipeline.registerFunction(e.sv.stemmer,"stemmer-sv"),e.sv.stopWordFilter=e.generateStopWordFilter("alla allt att av blev bli blir blivit de dem den denna deras dess dessa det detta dig din dina ditt du där då efter ej eller en er era ert ett från för ha hade han hans har henne hennes hon honom hur här i icke ingen inom inte jag ju kan kunde man med mellan men mig min mina mitt mot mycket ni nu när någon något några och om oss på samma sedan sig sin sina sitta själv skulle som så sådan sådana sådant till under upp ut utan vad var vara varför varit varje vars vart vem vi vid vilka vilkas vilken vilket vår våra vårt än är åt över".split(" ")),e.Pipeline.registerFunction(e.sv.stopWordFilter,"stopWordFilter-sv")}});
```
--------------------------------------------------------------------------------
/scripts/post_install_fix.sh:
--------------------------------------------------------------------------------
```bash
#!/bin/bash
set -e
echo "Running Post Install fix for CodeGraphContext..."
detect_shell_config() {
# Windows PowerShell detection
if [[ "$OS" == "Windows_NT" ]] && [[ -n "$PROFILE" ]]; then
echo "$PROFILE"
return
fi
# Unix/Linux/Mac shell detection
if [ "$SHELL" = "/bin/bash" ] || [ "$SHELL" = "/usr/bin/bash" ]; then
echo "$HOME/.bashrc"
elif [ "$SHELL" = "/bin/zsh" ] || [ "$SHELL" = "/usr/bin/zsh" ]; then
echo "$HOME/.zshrc"
elif [ -n "$BASH_VERSION" ]; then
echo "$HOME/.bashrc"
elif [ -n "$ZSH_VERSION" ]; then
echo "$HOME/.zshrc"
else
echo "$HOME/.profile"
fi
}
# Add to PATH for Windows PowerShell
fix_windows_path() {
local profile_file="$1"
local path_line='$env:PATH = "$env:USERPROFILE\.local\bin;$env:PATH"'
echo "Using PowerShell profile: $profile_file"
# Create profile directory if needed
local profile_dir=$(dirname "$profile_file")
mkdir -p "$profile_dir" 2>/dev/null || true
# Check if already configured
if [[ -f "$profile_file" ]] && grep -q ".local" "$profile_file"; then
echo "PATH is already configured in PowerShell profile"
else
echo "Adding to PowerShell PATH..."
echo "" >> "$profile_file"
echo "# Added by CodeGraphContext" >> "$profile_file"
echo "$path_line" >> "$profile_file"
echo "Added PATH to PowerShell profile"
fi
# Add to current session (Windows style)
export PATH="$USERPROFILE/.local/bin:$PATH"
echo "⚠️ Please restart PowerShell or run: . \$PROFILE"
}
# Add to PATH for Linux/Mac
fix_unix_path() {
local config_file="$1"
local path_line='export PATH="$HOME/.local/bin:$PATH"'
echo "Using shell config: $config_file"
# check if PATH is already configured
if [ -f "$config_file" ] && grep -q ".local/bin" "$config_file"; then
echo "PATH is already configured in $config_file"
else
echo "Adding ~/.local/bin to PATH..."
echo "" >> "$config_file"
echo "# Added by CodeGraphContext" >> "$config_file"
echo "$path_line" >> "$config_file"
echo "Added PATH to $config_file"
fi
# Source the config for current session
echo "Sourcing/Reloading shell config for current session..."
export PATH="$HOME/.local/bin:$PATH"
# source it
if [ -f "$config_file" ]; then
source "$config_file" 2>/dev/null || true
fi
}
# Main PATH fixing function
fix_path() {
local config_file=$(detect_shell_config)
# Check if we're on Windows
if [[ "$OS" == "Windows_NT" ]] && [[ -n "$PROFILE" ]]; then
fix_windows_path "$config_file"
else
fix_unix_path "$config_file"
fi
}
check_cgc() {
if command -v cgc >/dev/null 2>&1; then
return 0
else
return 1
fi
}
# Get potential cgc locations based on platform
get_cgc_locations() {
if [[ "$OS" == "Windows_NT" ]]; then
# Windows locations
echo "$USERPROFILE/.local/bin/cgc.exe"
echo "$USERPROFILE/.local/bin/cgc"
echo "$HOME/.local/bin/cgc.exe"
echo "$HOME/.local/bin/cgc"
else
# Linux/Mac locations
echo "$HOME/.local/bin/cgc"
fi
}
# Main execution
if check_cgc; then
echo "✅ cgc (CodeGraphContext) is already available!"
else
echo "⚠️ cgc command not found, fixing PATH..."
# Check if cgc exists in expected locations
cgc_found=false
for cgc_path in $(get_cgc_locations); do
if [[ -f "$cgc_path" ]]; then
cgc_found=true
echo "📍 Found cgc at: $cgc_path"
break
fi
done
if [[ "$cgc_found" == true ]]; then
fix_path
# Check again
if check_cgc; then
echo "✅ cgc command (CodeGraphContext) is now available to use!"
echo "You can now run: cgc setup"
else
if [[ "$OS" == "Windows_NT" ]]; then
echo "⚠️ Please restart PowerShell or run: . \$PROFILE"
else
echo "❌ There seems to still be an issue... Please reload your terminal manually."
fi
fi
else
if [[ "$OS" == "Windows_NT" ]]; then
echo "❌ cgc not found in expected Windows locations. Please reinstall:"
echo " pip install codegraphcontext"
else
echo "❌ cgc not found in ~/.local/bin. Please reinstall:"
echo " pip install codegraphcontext"
fi
fi
fi
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.da.min.js:
--------------------------------------------------------------------------------
```javascript
/*!
* Lunr languages, `Danish` 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.da=function(){this.pipeline.reset(),this.pipeline.add(e.da.trimmer,e.da.stopWordFilter,e.da.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.da.stemmer))},e.da.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.da.trimmer=e.trimmerSupport.generateTrimmer(e.da.wordCharacters),e.Pipeline.registerFunction(e.da.trimmer,"trimmer-da"),e.da.stemmer=function(){var r=e.stemmerSupport.Among,i=e.stemmerSupport.SnowballProgram,n=new function(){function e(){var e,r=f.cursor+3;if(d=f.limit,0<=r&&r<=f.limit){for(a=r;;){if(e=f.cursor,f.in_grouping(w,97,248)){f.cursor=e;break}if(f.cursor=e,e>=f.limit)return;f.cursor++}for(;!f.out_grouping(w,97,248);){if(f.cursor>=f.limit)return;f.cursor++}d=f.cursor,d<a&&(d=a)}}function n(){var e,r;if(f.cursor>=d&&(r=f.limit_backward,f.limit_backward=d,f.ket=f.cursor,e=f.find_among_b(c,32),f.limit_backward=r,e))switch(f.bra=f.cursor,e){case 1:f.slice_del();break;case 2:f.in_grouping_b(p,97,229)&&f.slice_del()}}function t(){var e,r=f.limit-f.cursor;f.cursor>=d&&(e=f.limit_backward,f.limit_backward=d,f.ket=f.cursor,f.find_among_b(l,4)?(f.bra=f.cursor,f.limit_backward=e,f.cursor=f.limit-r,f.cursor>f.limit_backward&&(f.cursor--,f.bra=f.cursor,f.slice_del())):f.limit_backward=e)}function s(){var e,r,i,n=f.limit-f.cursor;if(f.ket=f.cursor,f.eq_s_b(2,"st")&&(f.bra=f.cursor,f.eq_s_b(2,"ig")&&f.slice_del()),f.cursor=f.limit-n,f.cursor>=d&&(r=f.limit_backward,f.limit_backward=d,f.ket=f.cursor,e=f.find_among_b(m,5),f.limit_backward=r,e))switch(f.bra=f.cursor,e){case 1:f.slice_del(),i=f.limit-f.cursor,t(),f.cursor=f.limit-i;break;case 2:f.slice_from("løs")}}function o(){var e;f.cursor>=d&&(e=f.limit_backward,f.limit_backward=d,f.ket=f.cursor,f.out_grouping_b(w,97,248)?(f.bra=f.cursor,u=f.slice_to(u),f.limit_backward=e,f.eq_v_b(u)&&f.slice_del()):f.limit_backward=e)}var a,d,u,c=[new r("hed",-1,1),new r("ethed",0,1),new r("ered",-1,1),new r("e",-1,1),new r("erede",3,1),new r("ende",3,1),new r("erende",5,1),new r("ene",3,1),new r("erne",3,1),new r("ere",3,1),new r("en",-1,1),new r("heden",10,1),new r("eren",10,1),new r("er",-1,1),new r("heder",13,1),new r("erer",13,1),new r("s",-1,2),new r("heds",16,1),new r("es",16,1),new r("endes",18,1),new r("erendes",19,1),new r("enes",18,1),new r("ernes",18,1),new r("eres",18,1),new r("ens",16,1),new r("hedens",24,1),new r("erens",24,1),new r("ers",16,1),new r("ets",16,1),new r("erets",28,1),new r("et",-1,1),new r("eret",30,1)],l=[new r("gd",-1,-1),new r("dt",-1,-1),new r("gt",-1,-1),new r("kt",-1,-1)],m=[new r("ig",-1,1),new r("lig",0,1),new r("elig",1,1),new r("els",-1,1),new r("løst",-1,2)],w=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,48,0,128],p=[239,254,42,3,0,0,0,0,0,0,0,0,0,0,0,0,16],f=new i;this.setCurrent=function(e){f.setCurrent(e)},this.getCurrent=function(){return f.getCurrent()},this.stem=function(){var r=f.cursor;return e(),f.limit_backward=r,f.cursor=f.limit,n(),f.cursor=f.limit,t(),f.cursor=f.limit,s(),f.cursor=f.limit,o(),!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.da.stemmer,"stemmer-da"),e.da.stopWordFilter=e.generateStopWordFilter("ad af alle alt anden at blev blive bliver da de dem den denne der deres det dette dig din disse dog du efter eller en end er et for fra ham han hans har havde have hende hendes her hos hun hvad hvis hvor i ikke ind jeg jer jo kunne man mange med meget men mig min mine mit mod ned noget nogle nu når og også om op os over på selv sig sin sine sit skal skulle som sådan thi til ud under var vi vil ville vor være været".split(" ")),e.Pipeline.registerFunction(e.da.stopWordFilter,"stopWordFilter-da")}});
```
--------------------------------------------------------------------------------
/docs/docs/tools.md:
--------------------------------------------------------------------------------
```markdown
# Tools
The `tools` directory contains the logic for code analysis, including building the graph, finding code, and extracting imports.
## `GraphBuilder`
The `GraphBuilder` class in `graph_builder.py` is responsible for parsing the source code and building the graph representation that is stored in the Neo4j database.
### `TreeSitterParser`
`GraphBuilder` uses the `TreeSitterParser` class, which is a generic parser wrapper for a specific language using the tree-sitter library. This allows CodeGraphContext to support multiple programming languages in a modular way.
### Graph Building Process
The graph building process consists of several steps:
1. **Pre-scan for Imports:** A quick scan of all files to build a global map of where every symbol is defined.
2. **Parse Files:** Each file is parsed in detail to extract its structure, including functions, classes, variables, and imports.
3. **Add Nodes to Graph:** The extracted code elements are added to the graph as nodes.
4. **Create Relationships:** Relationships between the nodes are created, such as `CALLS` for function calls and `INHERITS` for class inheritance.
## `CodeFinder`
The `CodeFinder` class in `code_finder.py` provides functionality to search for specific code elements and analyze their relationships within the indexed codebase.
### Key Methods
- `find_by_function_name()`: Finds functions by name.
- `find_by_class_name()`: Finds classes by name.
- `find_by_variable_name()`: Finds variables by name.
- `find_by_content()`: Finds code by content matching in source or docstrings.
- `find_related_code()`: Finds code related to a query using multiple search strategies.
- `analyze_code_relationships()`: Analyzes different types of code relationships, such as callers, callees, importers, and class hierarchies.
## `ImportExtractor`
The `ImportExtractor` class in `import_extractor.py` is a utility for extracting package and module imports from source code files of various programming languages. It uses the most appropriate parsing technique for each language, such as AST for Python and regular expressions for JavaScript.
# Tools Exploration
There are a total of 14 tools available to the users, and here we have attached illustrative demos for each one of them.
## find_code Tool
The `find_code` tool allows users to search for code snippets, functions, classes, and variables within the codebase using natural language queries. This tool helps developers understand and navigate large codebases efficiently.
Below is an embedded link to a demo video showcasing the usage of the `find_code` tool in action.
[](https://drive.google.com/file/d/1ojCDIIAwcir9e3jgHHIVC5weZ9nuIQcs/view?usp=drive_link)
---
## watch_directory Tool
The `watch_directory` tool allows users to monitor a specified directory for file changes, additions, or deletions in real-time. It helps developers automate workflows such as triggering scripts, updating indexes, or syncing files whenever changes occur in the directory.
Below is an embedded link to a demo video showcasing the usage of the `watch_directory` tool in a development environment.
[](https://drive.google.com/file/d/1OEjcS2iwwymss99zLidbeBjcblferKBX/view?usp=drive_link)
---
## analyze_code_relationships Tool
The `analyze_code_relationships` tool in CodeGraphContext is designed to let users query and explore the various relationships between code elements in a codebase, represented as a graph in Neo4j.
### Relationship Types That Can Be Analyzed
- **CALLS:** Finds which functions call or are called by a function.
- **CALLED_BY:** Finds all functions that directly or indirectly call a target function (inverse of CALLS).
- **INHERITS_FROM:** Finds class inheritance relationships; which classes inherit from which.
- **CONTAINS:** Shows containment (which classes/functions are inside which modules or files).
- **IMPLEMENTS:** Shows which classes implement an interface.
- **IMPORTS:** Identifies which files or modules import a specific module.
- **DEFINED_IN:** Locates where an entity (function/class) is defined.
- **HAS_ARGUMENT:** Shows relationships from functions to their arguments.
- **DECLARES:** Finds variables declared in functions or classes.
Below is an embedded link to a demo video showcasing the usage of the `analyse_code_relationships` tool.
[](https://drive.google.com/file/d/154M_lTPbg9_Gj9bd2ErnAVbJArSbcb2M/view?usp=drive_link)
---
```
--------------------------------------------------------------------------------
/docs/site/assets/javascripts/lunr/min/lunr.no.min.js:
--------------------------------------------------------------------------------
```javascript
/*!
* Lunr languages, `Norwegian` 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.no=function(){this.pipeline.reset(),this.pipeline.add(e.no.trimmer,e.no.stopWordFilter,e.no.stemmer),this.searchPipeline&&(this.searchPipeline.reset(),this.searchPipeline.add(e.no.stemmer))},e.no.wordCharacters="A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꞭꞰ-ꞷꟷ-ꟿꬰ-ꭚꭜ-ꭤff-stA-Za-z",e.no.trimmer=e.trimmerSupport.generateTrimmer(e.no.wordCharacters),e.Pipeline.registerFunction(e.no.trimmer,"trimmer-no"),e.no.stemmer=function(){var r=e.stemmerSupport.Among,n=e.stemmerSupport.SnowballProgram,i=new function(){function e(){var e,r=w.cursor+3;if(a=w.limit,0<=r||r<=w.limit){for(s=r;;){if(e=w.cursor,w.in_grouping(d,97,248)){w.cursor=e;break}if(e>=w.limit)return;w.cursor=e+1}for(;!w.out_grouping(d,97,248);){if(w.cursor>=w.limit)return;w.cursor++}a=w.cursor,a<s&&(a=s)}}function i(){var e,r,n;if(w.cursor>=a&&(r=w.limit_backward,w.limit_backward=a,w.ket=w.cursor,e=w.find_among_b(m,29),w.limit_backward=r,e))switch(w.bra=w.cursor,e){case 1:w.slice_del();break;case 2:n=w.limit-w.cursor,w.in_grouping_b(c,98,122)?w.slice_del():(w.cursor=w.limit-n,w.eq_s_b(1,"k")&&w.out_grouping_b(d,97,248)&&w.slice_del());break;case 3:w.slice_from("er")}}function t(){var e,r=w.limit-w.cursor;w.cursor>=a&&(e=w.limit_backward,w.limit_backward=a,w.ket=w.cursor,w.find_among_b(u,2)?(w.bra=w.cursor,w.limit_backward=e,w.cursor=w.limit-r,w.cursor>w.limit_backward&&(w.cursor--,w.bra=w.cursor,w.slice_del())):w.limit_backward=e)}function o(){var e,r;w.cursor>=a&&(r=w.limit_backward,w.limit_backward=a,w.ket=w.cursor,e=w.find_among_b(l,11),e?(w.bra=w.cursor,w.limit_backward=r,1==e&&w.slice_del()):w.limit_backward=r)}var s,a,m=[new r("a",-1,1),new r("e",-1,1),new r("ede",1,1),new r("ande",1,1),new r("ende",1,1),new r("ane",1,1),new r("ene",1,1),new r("hetene",6,1),new r("erte",1,3),new r("en",-1,1),new r("heten",9,1),new r("ar",-1,1),new r("er",-1,1),new r("heter",12,1),new r("s",-1,2),new r("as",14,1),new r("es",14,1),new r("edes",16,1),new r("endes",16,1),new r("enes",16,1),new r("hetenes",19,1),new r("ens",14,1),new r("hetens",21,1),new r("ers",14,1),new r("ets",14,1),new r("et",-1,1),new r("het",25,1),new r("ert",-1,3),new r("ast",-1,1)],u=[new r("dt",-1,-1),new r("vt",-1,-1)],l=[new r("leg",-1,1),new r("eleg",0,1),new r("ig",-1,1),new r("eig",2,1),new r("lig",2,1),new r("elig",4,1),new r("els",-1,1),new r("lov",-1,1),new r("elov",7,1),new r("slov",7,1),new r("hetslov",9,1)],d=[17,65,16,1,0,0,0,0,0,0,0,0,0,0,0,0,48,0,128],c=[119,125,149,1],w=new n;this.setCurrent=function(e){w.setCurrent(e)},this.getCurrent=function(){return w.getCurrent()},this.stem=function(){var r=w.cursor;return e(),w.limit_backward=r,w.cursor=w.limit,i(),w.cursor=w.limit,t(),w.cursor=w.limit,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.no.stemmer,"stemmer-no"),e.no.stopWordFilter=e.generateStopWordFilter("alle at av bare begge ble blei bli blir blitt både båe da de deg dei deim deira deires dem den denne der dere deres det dette di din disse ditt du dykk dykkar då eg ein eit eitt eller elles en enn er et ett etter for fordi fra før ha hadde han hans har hennar henne hennes her hjå ho hoe honom hoss hossen hun hva hvem hver hvilke hvilken hvis hvor hvordan hvorfor i ikke ikkje ikkje ingen ingi inkje inn inni ja jeg kan kom korleis korso kun kunne kva kvar kvarhelst kven kvi kvifor man mange me med medan meg meget mellom men mi min mine mitt mot mykje ned no noe noen noka noko nokon nokor nokre nå når og også om opp oss over på samme seg selv si si sia sidan siden sin sine sitt sjøl skal skulle slik so som som somme somt så sånn til um upp ut uten var vart varte ved vere verte vi vil ville vore vors vort vår være være vært å".split(" ")),e.Pipeline.registerFunction(e.no.stopWordFilter,"stopWordFilter-no")}});
```
--------------------------------------------------------------------------------
/tests/sample_project_go/goroutines_channels.go:
--------------------------------------------------------------------------------
```go
// goroutines_channels.go - Demonstrates Go concurrency patterns
package main
import (
"fmt"
"sync"
"time"
)
// SimpleGoroutine demonstrates basic goroutine
func SimpleGoroutine(id int) {
fmt.Printf("Goroutine %d starting\n", id)
time.Sleep(time.Millisecond * 100)
fmt.Printf("Goroutine %d done\n", id)
}
// ChannelSender sends data to a channel
func ChannelSender(ch chan<- int, values []int) {
for _, v := range values {
ch <- v
}
close(ch)
}
// ChannelReceiver receives data from a channel
func ChannelReceiver(ch <-chan int, done chan<- bool) {
sum := 0
for v := range ch {
sum += v
}
fmt.Printf("Sum: %d\n", sum)
done <- true
}
// BufferedChannelExample demonstrates buffered channels
func BufferedChannelExample() {
ch := make(chan string, 3)
ch <- "first"
ch <- "second"
ch <- "third"
fmt.Println(<-ch)
fmt.Println(<-ch)
fmt.Println(<-ch)
}
// SelectExample demonstrates select statement
func SelectExample(ch1, ch2 chan string) string {
select {
case msg1 := <-ch1:
return fmt.Sprintf("Received from ch1: %s", msg1)
case msg2 := <-ch2:
return fmt.Sprintf("Received from ch2: %s", msg2)
case <-time.After(time.Second):
return "Timeout"
}
}
// Worker demonstrates worker pool pattern
func Worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
fmt.Printf("Worker %d processing job %d\n", id, job)
time.Sleep(time.Millisecond * 50)
results <- job * 2
}
}
// WorkerPool creates a pool of workers
func WorkerPool(numWorkers int, numJobs int) []int {
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
var wg sync.WaitGroup
// Start workers
for w := 1; w <= numWorkers; w++ {
wg.Add(1)
go Worker(w, jobs, results, &wg)
}
// Send jobs
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs)
// Wait and collect results
go func() {
wg.Wait()
close(results)
}()
var output []int
for result := range results {
output = append(output, result)
}
return output
}
// Counter demonstrates mutex for safe concurrent access
type Counter struct {
mu sync.Mutex
value int
}
// Increment safely increments counter
func (c *Counter) Increment() {
c.mu.Lock()
defer c.mu.Unlock()
c.value++
}
// GetValue safely gets counter value
func (c *Counter) GetValue() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.value
}
// RWMutexExample demonstrates read-write mutex
type ConcurrentMap struct {
mu sync.RWMutex
data map[string]int
}
// Set adds or updates a value
func (cm *ConcurrentMap) Set(key string, value int) {
cm.mu.Lock()
defer cm.mu.Unlock()
cm.data[key] = value
}
// Get retrieves a value
func (cm *ConcurrentMap) Get(key string) (int, bool) {
cm.mu.RLock()
defer cm.mu.RUnlock()
val, ok := cm.data[key]
return val, ok
}
// OnceExample demonstrates sync.Once
var once sync.Once
var instance *Singleton
type Singleton struct {
data string
}
// GetSingleton returns singleton instance
func GetSingleton() *Singleton {
once.Do(func() {
fmt.Println("Creating singleton instance")
instance = &Singleton{data: "singleton data"}
})
return instance
}
// PipelineStage1 first stage of pipeline
func PipelineStage1(input <-chan int, output chan<- int) {
for num := range input {
output <- num * 2
}
close(output)
}
// PipelineStage2 second stage of pipeline
func PipelineStage2(input <-chan int, output chan<- int) {
for num := range input {
output <- num + 10
}
close(output)
}
// Pipeline demonstrates pipeline pattern
func Pipeline(numbers []int) []int {
stage1 := make(chan int)
stage2 := make(chan int)
// Input
go func() {
for _, num := range numbers {
stage1 <- num
}
close(stage1)
}()
// Stage 1
go PipelineStage1(stage1, stage2)
// Collect results
var results []int
for result := range stage2 {
results = append(results, result)
}
return results
}
// FanOut sends data to multiple channels
func FanOut(input <-chan int, outputs []chan<- int) {
for val := range input {
for _, out := range outputs {
out <- val
}
}
for _, out := range outputs {
close(out)
}
}
// FanIn merges multiple channels into one
func FanIn(inputs ...<-chan int) <-chan int {
output := make(chan int)
var wg sync.WaitGroup
for _, input := range inputs {
wg.Add(1)
go func(ch <-chan int) {
defer wg.Done()
for val := range ch {
output <- val
}
}(input)
}
go func() {
wg.Wait()
close(output)
}()
return output
}
func demonstrateConcurrency() {
// Simple goroutines
for i := 1; i <= 3; i++ {
go SimpleGoroutine(i)
}
// Worker pool
results := WorkerPool(3, 5)
fmt.Println("Results:", results)
time.Sleep(time.Second)
}
```
--------------------------------------------------------------------------------
/tests/sample_project_javascript/classes.js:
--------------------------------------------------------------------------------
```javascript
/**
* Sample JavaScript file demonstrating class definitions and methods
* This file tests class declarations, methods, static methods, and inheritance
*/
// Basic class declaration
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// Instance method
greet() {
return `Hello, I'm ${this.name} and I'm ${this.age} years old`;
}
/**
* Method with JSDoc documentation
* @param {number} years - Number of years to add
* @returns {void}
*/
celebrateBirthday(years = 1) {
this.age += years;
console.log(`Happy birthday! Now ${this.age} years old`);
}
// Getter method
get info() {
return `${this.name} (${this.age})`;
}
// Setter method
set info(value) {
const [name, age] = value.split(' ');
this.name = name;
this.age = parseInt(age);
}
// Static method
static createAdult(name) {
return new Person(name, 18);
}
// Static method with parameters
static compare(person1, person2) {
return person1.age - person2.age;
}
}
// Class inheritance
class Employee extends Person {
constructor(name, age, jobTitle, salary) {
super(name, age);
this.jobTitle = jobTitle;
this.salary = salary;
}
// Override parent method
greet() {
return `${super.greet()}. I work as a ${this.jobTitle}`;
}
// New method specific to Employee
work() {
console.log(`${this.name} is working as a ${this.jobTitle}`);
}
// Method with complex parameters
updateSalary(newSalary, reason = 'performance review') {
const oldSalary = this.salary;
this.salary = newSalary;
console.log(`Salary updated from ${oldSalary} to ${newSalary} due to ${reason}`);
}
// Static method in child class
static createIntern(name, age) {
return new Employee(name, age, 'Intern', 0);
}
}
// Class with private fields (modern JavaScript)
class BankAccount {
#balance = 0;
#accountNumber;
constructor(accountNumber, initialBalance = 0) {
this.#accountNumber = accountNumber;
this.#balance = initialBalance;
}
// Public method accessing private field
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
return this.#balance;
}
throw new Error('Amount must be positive');
}
// Public method accessing private field
withdraw(amount) {
if (amount > 0 && amount <= this.#balance) {
this.#balance -= amount;
return this.#balance;
}
throw new Error('Invalid withdrawal amount');
}
// Getter for private field
get balance() {
return this.#balance;
}
// Private method
#validateTransaction(amount) {
return amount > 0 && amount <= this.#balance;
}
}
// Class with static properties and methods
class MathUtils {
static PI = 3.14159;
static E = 2.71828;
static add(a, b) {
return a + b;
}
static multiply(a, b) {
return a * b;
}
static circleArea(radius) {
return MathUtils.PI * radius * radius;
}
}
// Class expression assigned to variable
const AnonymousClass = class {
constructor(value) {
this.value = value;
}
getValue() {
return this.value;
}
};
// Mixin pattern using classes
const Flyable = (Base) => class extends Base {
fly() {
console.log(`${this.name} is flying!`);
}
};
const Swimmable = (Base) => class extends Base {
swim() {
console.log(`${this.name} is swimming!`);
}
};
// Class using mixins
class Duck extends Swimmable(Flyable(Person)) {
constructor(name) {
super(name, 0); // Ducks don't have human age
this.species = 'Duck';
}
quack() {
console.log(`${this.name} says: Quack!`);
}
}
// Function that creates and uses class instances
function demonstrateClasses() {
const person = new Person('Alice', 30);
const employee = new Employee('Bob', 25, 'Developer', 75000);
const account = new BankAccount('12345', 1000);
const duck = new Duck('Donald');
// Call various methods
console.log(person.greet());
console.log(employee.greet());
employee.work();
account.deposit(500);
console.log('Balance:', account.balance);
duck.quack();
duck.fly();
duck.swim();
return {
person,
employee,
account,
duck
};
}
// Export classes
export { Person, Employee, BankAccount, MathUtils, Duck };
export default demonstrateClasses;
```
--------------------------------------------------------------------------------
/website/src/components/ui/toast.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import * as ToastPrimitives from "@radix-ui/react-toast";
import { cva, type VariantProps } from "class-variance-authority";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
const ToastProvider = ToastPrimitives.Provider;
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className,
)}
{...props}
/>
));
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive: "destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return <ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props} />;
});
Toast.displayName = ToastPrimitives.Root.displayName;
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors group-[.destructive]:border-muted/40 hover:bg-secondary group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 group-[.destructive]:focus:ring-destructive disabled:pointer-events-none disabled:opacity-50",
className,
)}
{...props}
/>
));
ToastAction.displayName = ToastPrimitives.Action.displayName;
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity group-hover:opacity-100 group-[.destructive]:text-red-300 hover:text-foreground group-[.destructive]:hover:text-red-50 focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className,
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
));
ToastClose.displayName = ToastPrimitives.Close.displayName;
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title ref={ref} className={cn("text-sm font-semibold", className)} {...props} />
));
ToastTitle.displayName = ToastPrimitives.Title.displayName;
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description ref={ref} className={cn("text-sm opacity-90", className)} {...props} />
));
ToastDescription.displayName = ToastPrimitives.Description.displayName;
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
type ToastActionElement = React.ReactElement<typeof ToastAction>;
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
};
```
--------------------------------------------------------------------------------
/src/codegraphcontext/core/jobs.py:
--------------------------------------------------------------------------------
```python
# src/codegraphcontext/core/jobs.py
"""
This module defines the data structures and manager for handling long-running,
background jobs, such as code indexing.
"""
import uuid
import threading
from datetime import datetime, timedelta
from dataclasses import dataclass, asdict
from enum import Enum
from typing import Any, Dict, List, Optional
from pathlib import Path
class JobStatus(Enum):
"""Enumeration for the possible statuses of a background job."""
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
CANCELLED = "cancelled"
@dataclass
class JobInfo:
"""
A data class to hold all information about a single background job.
This makes it easy to track the job's progress, status, and results.
"""
job_id: str
status: JobStatus
start_time: datetime
end_time: Optional[datetime] = None
total_files: int = 0
processed_files: int = 0
current_file: Optional[str] = None
estimated_duration: Optional[float] = None
actual_duration: Optional[float] = None
errors: List[str] = None
result: Optional[Dict[str, Any]] = None
path: Optional[str] = None
is_dependency: bool = False
def __post_init__(self):
"""Ensures the errors list is initialized after the object is created."""
if self.errors is None:
self.errors = []
@property
def progress_percentage(self) -> float:
"""Calculates the completion percentage of the job."""
if self.total_files == 0:
return 0.0
return (self.processed_files / self.total_files) * 100
@property
def estimated_time_remaining(self) -> Optional[float]:
"""Calculates the estimated time remaining based on the average time per file."""
if self.status != JobStatus.RUNNING or self.processed_files == 0:
return None
elapsed = (datetime.now() - self.start_time).total_seconds()
avg_time_per_file = elapsed / self.processed_files
remaining_files = self.total_files - self.processed_files
return remaining_files * avg_time_per_file
class JobManager:
"""
A thread-safe manager for creating, updating, and retrieving information
about background jobs. It stores job information in memory.
"""
def __init__(self):
self.jobs: Dict[str, JobInfo] = {}
self.lock = threading.Lock() # A lock to ensure thread-safe access to the jobs dictionary.
def create_job(self, path: str, is_dependency: bool = False) -> str:
"""Creates a new job, assigns it a unique ID, and stores it."""
job_id = str(uuid.uuid4())
with self.lock:
self.jobs[job_id] = JobInfo(
job_id=job_id,
status=JobStatus.PENDING,
start_time=datetime.now(),
path=path,
is_dependency=is_dependency
)
return job_id
def update_job(self, job_id: str, **kwargs):
"""Updates the information for a specific job in a thread-safe manner."""
with self.lock:
if job_id in self.jobs:
job = self.jobs[job_id]
for key, value in kwargs.items():
if hasattr(job, key):
setattr(job, key, value)
def get_job(self, job_id: str) -> Optional[JobInfo]:
"""Retrieves the information for a single job."""
with self.lock:
return self.jobs.get(job_id)
def list_jobs(self) -> List[JobInfo]:
"""Returns a list of all jobs currently in the manager."""
with self.lock:
return list(self.jobs.values())
def find_active_job_by_path(self, path: str) -> Optional[JobInfo]:
"""Finds the most recent, currently active (pending or running) job for a given path."""
with self.lock:
path_obj = Path(path).resolve()
matching_jobs = sorted(
[job for job in self.jobs.values() if job.path and Path(job.path).resolve() == path_obj],
key=lambda j: j.start_time,
reverse=True
)
for job in matching_jobs:
if job.status in [JobStatus.PENDING, JobStatus.RUNNING]:
return job
return None
def cleanup_old_jobs(self, max_age_hours: int = 24):
"""Removes old, completed jobs from memory to prevent memory leaks."""
cutoff_time = datetime.now() - timedelta(hours=max_age_hours)
with self.lock:
jobs_to_remove = [
job_id for job_id, job in self.jobs.items()
if job.end_time and job.end_time < cutoff_time
]
for job_id in jobs_to_remove:
del self.jobs[job_id]
```
--------------------------------------------------------------------------------
/website/src/components/ui/command.tsx:
--------------------------------------------------------------------------------
```typescript
import * as React from "react";
import { type DialogProps } from "@radix-ui/react-dialog";
import { Command as CommandPrimitive } from "cmdk";
import { Search } from "lucide-react";
import { cn } from "@/lib/utils";
import { Dialog, DialogContent } from "@/components/ui/dialog";
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
className,
)}
{...props}
/>
));
Command.displayName = CommandPrimitive.displayName;
interface CommandDialogProps extends DialogProps {}
const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0 shadow-lg">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
);
};
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
/>
</div>
));
CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
));
CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => <CommandPrimitive.Empty ref={ref} className="py-6 text-center text-sm" {...props} />);
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
className,
)}
{...props}
/>
));
CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator ref={ref} className={cn("-mx-1 h-px bg-border", className)} {...props} />
));
CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",
className,
)}
{...props}
/>
));
CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
return <span className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)} {...props} />;
};
CommandShortcut.displayName = "CommandShortcut";
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};
```