defsource

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 10, 2026 License: GPL-3.0 Imports: 8 Imported by: 0

README

defsource

defsource is a Go library for crawling, indexing, and searching source-code documentation. It parses documentation from upstream sources into a single SQLite database backed by FTS5, then exposes a small client API for resolving libraries and querying documentation snippets with BM25 relevance ranking. Results can be returned as structured data or as pre-formatted, token-budgeted text suitable for feeding to downstream tools.

Go Reference

Features

  • Full-text search over indexed documentation using SQLite FTS5 with BM25 ranking.
  • all (AND) and any (OR) search modes, selectable per query.
  • Library resolution that matches a name and re-ranks candidates against a query.
  • Structured snippet results plus a pre-formatted, token-budgeted text rendering.
  • Pluggable storage: open a SQLite-backed client, or inject any store.Store implementation for testing.
  • Wrapper/delegation chain resolution so a snippet can carry the underlying source it forwards to.

Requirements

  • Go 1.25.3 or newer.
  • CGO enabled (CGO_ENABLED=1) with a working C compiler, because the SQLite driver is implemented via cgo.
  • The sqlite_fts5 build tag, which enables FTS5 full-text search support in the SQLite driver.

Installation

go get github.com/hatlesswizard/defsource

Because the library depends on cgo and FTS5, build and test commands must enable CGO and pass the sqlite_fts5 tag:

CGO_ENABLED=1 go build -tags sqlite_fts5 ./...

Library Usage

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/hatlesswizard/defsource"
)

func main() {
	// Open (or create) a SQLite database backed by FTS5.
	client, err := defsource.New("docs.db", defsource.WithTokenBudget(4000))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	ctx := context.Background()

	// List the libraries that have been indexed into the database.
	libraries, err := client.ListLibraries(ctx)
	if err != nil {
		log.Fatal(err)
	}
	for _, lib := range libraries {
		fmt.Printf("%s (%s) — %d snippets\n", lib.Name, lib.ID, lib.SnippetCount)
	}

	if len(libraries) == 0 {
		return
	}

	// Query documentation for the first library, using OR (any) semantics.
	result, err := client.QueryDocs(ctx, libraries[0].ID, "query posts by author",
		defsource.WithSearchMode("any"))
	if err != nil {
		log.Fatal(err)
	}

	// Each snippet carries structured fields...
	for _, snippet := range result.Snippets {
		fmt.Printf("%s %s\n", snippet.EntityName, snippet.MethodName)
	}

	// ...and result.Text holds a pre-formatted, token-budgeted rendering.
	fmt.Println(result.Text)
}

The client also exposes ResolveLibrary (match a library by name and re-rank against a query) and ListEntities (summarise the classes and functions in a library). See the package reference for the full API.

Testing

CGO_ENABLED=1 go test -tags sqlite_fts5 ./...

License

This project is licensed under the GNU General Public License v3.0. See the LICENSE file for the full text.

Documentation

Overview

Package defsource provides a Go client for querying WordPress PHP documentation indexed from source code. Use New to open (or create) a SQLite database backed by FTS5, then call QueryDocs, ResolveLibrary, ListLibraries, or ListEntities. Use NewWithStore to inject any store.Store implementation — useful for testing.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the main entry point for querying WordPress PHP documentation. Construct one with New (SQLite-backed) or NewWithStore (custom store).

func New

func New(dbPath string, opts ...Option) (*Client, error)

New creates a Client backed by the SQLite database at dbPath. The database is created if it does not exist; FTS5 migrations are applied automatically. Requires CGO_ENABLED=1 and the sqlite_fts5 build tag.

func NewWithStore added in v0.1.3

func NewWithStore(s store.Store, opts ...Option) *Client

NewWithStore creates a Client backed by the provided store.Store implementation. This constructor satisfies the Dependency Inversion Principle: callers can inject any store implementation — including in-memory fakes for unit tests — without depending on the SQLite package.

func (*Client) Close

func (c *Client) Close() error

Close releases the underlying store resources. It must be called when the Client is no longer needed to avoid leaking database connections.

func (*Client) ListEntities

func (c *Client) ListEntities(ctx context.Context, libraryID string) ([]EntityInfo, error)

ListEntities returns summary information about every entity (class or function) belonging to the library identified by libraryID.

func (*Client) ListLanguages added in v0.1.4

func (c *Client) ListLanguages(ctx context.Context) ([]LanguageInfo, error)

ListLanguages returns all distinct languages that have at least one indexed library in the store, along with the count of libraries per language.

func (*Client) ListLibraries

func (c *Client) ListLibraries(ctx context.Context) ([]Library, error)

ListLibraries returns all indexed libraries. SnippetCount is computed on demand for libraries whose stored count is zero.

func (*Client) ListLibrariesByLanguage added in v0.1.4

func (c *Client) ListLibrariesByLanguage(ctx context.Context, language string) ([]Library, error)

ListLibrariesByLanguage returns indexed libraries filtered by programming language. SnippetCount is computed on demand for libraries whose stored count is zero.

func (*Client) QueryDocs

func (c *Client) QueryDocs(ctx context.Context, libraryID, query string, opts ...QueryOption) (*DocResult, error)

QueryDocs retrieves documentation snippets for the library identified by libraryID that are relevant to query. opts may include WithSearchMode to control FTS5 AND/OR semantics. Returns a DocResult containing raw snippets and a pre-formatted text string budget-limited by the client's token budget.

func (*Client) QueryDocsByLanguage added in v0.1.4

func (c *Client) QueryDocsByLanguage(ctx context.Context, language, query string, opts ...QueryOption) (*DocResult, error)

QueryDocsByLanguage performs a cross-library documentation search within a single language. It queries all libraries for the given language and merges results by relevance. The returned DocResult uses "cross-language" as the Library field.

func (*Client) ResolveLibrary

func (c *Client) ResolveLibrary(ctx context.Context, query, libraryName string) ([]Library, error)

ResolveLibrary searches for libraries whose name matches libraryName, then re-ranks the results against query for relevance. At most 5 libraries are returned. SnippetCount is computed on demand when the store has not cached it.

type DocResult

type DocResult struct {
	// Library is the libraryID that was queried.
	Library string `json:"library"`

	// Query is the search query string that produced these results.
	Query string `json:"query"`

	// Snippets contains the individual documentation entries ranked by relevance.
	Snippets []DocSnippet `json:"snippets"`

	// Text is a pre-formatted Markdown representation of Snippets, truncated
	// to the client's token budget.
	Text string `json:"text"`
}

DocResult is the response from QueryDocs.

type DocSnippet

type DocSnippet = source.DocSnippet

DocSnippet is re-exported from internal/source for the public API. It is the canonical type for a single documentation entry returned by QueryDocs; callers may use either defsource.DocSnippet or source.DocSnippet — they are identical types.

type EntityInfo

type EntityInfo struct {
	// Name is the display name of the entity (e.g., "WP_Query").
	Name string `json:"name"`

	// Slug is the URL-derived unique identifier for the entity within its library.
	Slug string `json:"slug"`

	// Kind is the entity type: "class" or "function".
	Kind string `json:"kind"`

	// Description is the PHPDoc summary for the entity.
	Description string `json:"description"`

	// MethodCount is the number of indexed methods belonging to this entity.
	MethodCount int `json:"method_count"`

	// URL is the canonical documentation URL for this entity.
	URL string `json:"url"`
}

EntityInfo represents summary information about an entity returned by ListEntities. It does not include full source code or method details.

type LanguageInfo added in v0.1.4

type LanguageInfo struct {
	// Language is the language identifier (e.g., "python", "go", "rust").
	Language string `json:"language"`

	// FrameworkCount is the number of libraries/frameworks indexed for this language.
	FrameworkCount int `json:"framework_count"`
}

LanguageInfo holds summary information about a supported language.

type Library

type Library struct {
	// ID is the unique library identifier used as the libraryID parameter in
	// QueryDocs and ListEntities (e.g., "wordpress-6.5").
	ID string `json:"id"`

	// Name is the human-readable display name (e.g., "WordPress 6.5").
	Name string `json:"name"`

	// Description is a short summary of the library.
	Description string `json:"description"`

	// SourceURL is the canonical URL from which the library was crawled.
	SourceURL string `json:"source_url"`

	// Version is the version string reported by the source (e.g., "6.5.0").
	Version string `json:"version"`

	// Language is the programming language of the library (e.g., "php", "python", "go").
	Language string `json:"language"`

	// TrustScore is a normalised relevance weight in the range [0, 1].
	TrustScore float64 `json:"trust_score"`

	// SnippetCount is the total number of indexed documentation snippets
	// (entities + methods). It may be 0 if not yet computed.
	SnippetCount int `json:"snippet_count"`

	// CrawledAt is the time the library was last fully crawled.
	CrawledAt time.Time `json:"crawled_at"`
}

Library represents an indexed documentation source (e.g., a WordPress version).

type Option

type Option func(*Client)

Option configures a Client at construction time.

func WithTokenBudget

func WithTokenBudget(budget int) Option

WithTokenBudget sets the maximum approximate token count used when formatting QueryDocs text responses. The default is 8000 tokens.

type Parameter

type Parameter = source.Parameter

Parameter is re-exported from internal/source for the public API. Callers using defsource.Parameter continue to work without change — the type alias means defsource.Parameter and source.Parameter are identical.

type QueryOption

type QueryOption func(*queryConfig)

QueryOption configures a single QueryDocs call.

func WithSearchMode

func WithSearchMode(mode string) QueryOption

WithSearchMode sets the FTS5 search mode: "all" (AND semantics, default) or "any" (OR semantics). Use "any" when partial matches are acceptable.

type Relation

type Relation = source.Relation

Relation is re-exported from internal/source for the public API. Callers using defsource.Relation continue to work without change — the type alias means defsource.Relation and source.Relation are identical.

Directories

Path Synopsis
internal
config
Package config loads defSource runtime configuration from environment variables.
Package config loads defSource runtime configuration from environment variables.
crawler
Package crawler implements a concurrent documentation crawler that fetches, parses, and indexes entities from a source adapter into a store.
Package crawler implements a concurrent documentation crawler that fetches, parses, and indexes entities from a source adapter into a store.
docparser
Package docparser provides a unified documentation comment parsing infrastructure with sub-packages for each documentation format across multiple programming languages.
Package docparser provides a unified documentation comment parsing infrastructure with sub-packages for each documentation format across multiple programming languages.
docparser/doxygen
Package doxygen parses C/C++ Doxygen documentation comments into structured DocComment values.
Package doxygen parses C/C++ Doxygen documentation comments into structured DocComment values.
docparser/godoc
Package godoc parses Go doc comments into structured DocComment values.
Package godoc parses Go doc comments into structured DocComment values.
docparser/javadoc
Package javadoc parses JavaDoc comment blocks (/** ...
Package javadoc parses JavaDoc comment blocks (/** ...
docparser/jsdoc
Package jsdoc parses JSDoc comment blocks (/** ...
Package jsdoc parses JSDoc comment blocks (/** ...
docparser/phpdoc
Package phpdoc parses PHPDoc comment blocks (/** ...
Package phpdoc parses PHPDoc comment blocks (/** ...
docparser/pydoc
Package pydoc parses Python docstrings into structured DocComment values.
Package pydoc parses Python docstrings into structured DocComment values.
docparser/rustdoc
Package rustdoc parses Rust documentation comments (/// and //!) into structured DocComment values.
Package rustdoc parses Rust documentation comments (/// and //!) into structured DocComment values.
docparser/xmldoc
Package xmldoc parses C# XML documentation comments (/// lines or /** ...
Package xmldoc parses C# XML documentation comments (/// lines or /** ...
docparser/yard
Package yard parses Ruby YARD documentation comments into structured DocComment values.
Package yard parses Ruby YARD documentation comments into structured DocComment values.
search
Package search provides ranking, formatting, and token-counting utilities for documentation query results returned by the defSource library.
Package search provides ranking, formatting, and token-counting utilities for documentation query results returned by the defSource library.
server
Package server provides the HTTP API server for defSource.
Package server provides the HTTP API server for defSource.
source
Package source defines the Source interface and the data-transfer types that flow between a source adapter and the crawler.
Package source defines the Source interface and the data-transfer types that flow between a source adapter and the crawler.
source/allsources
Package allsources is a convenience import that triggers init() registration of all language source adapters into the default registry.
Package allsources is a convenience import that triggers init() registration of all language source adapters into the default registry.
source/clang
Package clang provides a documentation source adapter that parses C library source code from a local checkout of any C project (glibc, SQLite, OpenSSL, libcurl, etc.).
Package clang provides a documentation source adapter that parses C library source code from a local checkout of any C project (glibc, SQLite, OpenSSL, libcurl, etc.).
source/cpp
Package cpp provides a documentation source adapter that parses C++ library source code from a local clone of any C++ GitHub repository (Boost, Qt, Abseil, etc.).
Package cpp provides a documentation source adapter that parses C++ library source code from a local clone of any C++ GitHub repository (Boost, Qt, Abseil, etc.).
source/csharp
Package csharp provides a documentation source adapter that reads C# source code from a local clone of a .NET/ASP.NET/EF Core GitHub repository.
Package csharp provides a documentation source adapter that reads C# source code from a local clone of a .NET/ASP.NET/EF Core GitHub repository.
source/golang
Package golang provides a Source interface implementation for parsing Go source code.
Package golang provides a Source interface implementation for parsing Go source code.
source/java
Package java provides a documentation source adapter that reads Java source code from a local clone of a GitHub repository.
Package java provides a documentation source adapter that reads Java source code from a local clone of a GitHub repository.
source/javascript
Package javascript provides a documentation source adapter that reads JavaScript source code from a local directory (downloaded from GitHub).
Package javascript provides a documentation source adapter that reads JavaScript source code from a local directory (downloaded from GitHub).
source/php
Package php — ast.go: tree-sitter PHP AST walker and wrapper detector.
Package php — ast.go: tree-sitter PHP AST walker and wrapper detector.
source/python
Package python provides a documentation source adapter that reads Python source code from a local checkout of a Python framework repository (Django, Flask, FastAPI, etc.).
Package python provides a documentation source adapter that reads Python source code from a local checkout of a Python framework repository (Django, Flask, FastAPI, etc.).
source/ruby
Package ruby provides a documentation source adapter that reads Ruby source code from a local checkout of a Ruby framework repository (Rails, RSpec, Sidekiq, etc.).
Package ruby provides a documentation source adapter that reads Ruby source code from a local checkout of a Ruby framework repository (Rails, RSpec, Sidekiq, etc.).
source/rust
Package rust provides a documentation source adapter that reads Rust source code from a local checkout of any Rust crate repository.
Package rust provides a documentation source adapter that reads Rust source code from a local checkout of any Rust crate repository.
source/typescript
Package typescript provides a Source interface implementation for parsing TypeScript source code from any TypeScript-based library (Angular, NestJS, RxJS, Zod, etc.).
Package typescript provides a Source interface implementation for parsing TypeScript source code from any TypeScript-based library (Angular, NestJS, RxJS, Zod, etc.).
store
Package store defines the persistence interface and data-transfer types used by all storage backends.
Package store defines the persistence interface and data-transfer types used by all storage backends.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL