defsource

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: May 27, 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) 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) 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) 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 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"`

	// 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.
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/wpgithub
Package wpgithub — ast.go: tree-sitter PHP AST walker and wrapper detector.
Package wpgithub — ast.go: tree-sitter PHP AST walker and wrapper detector.
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