android

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 8, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package android provides parsers for Android project files.

Index

Constants

View Source
const DefaultResourceCacheCapBytes int64 = 128 * 1024 * 1024

DefaultResourceCacheCapBytes caps the on-disk footprint of the ResourceIndex cache. Sized generously so large multi-module repos fit in 128 MB.

Variables

View Source
var KnownDensities = []Density{
	{"ldpi", 0.75},
	{"mdpi", 1.0},
	{"hdpi", 1.5},
	{"xhdpi", 2.0},
	{"xxhdpi", 3.0},
	{"xxxhdpi", 4.0},
}

KnownDensities lists standard Android density buckets in order.

Functions

func ClearResourceGraphCache

func ClearResourceGraphCache(dir string) error

func ClearResourceIndexCache

func ClearResourceIndexCache(repoDir string) error

ClearResourceIndexCache removes the resource-cache directory under repoDir. Used by --clear-cache; a no-op when the cache dir does not exist.

func ClearXMLParseCache

func ClearXMLParseCache(repoDir string) error

ClearXMLParseCache removes the xml parse cache subtree. Used by --clear-cache at the CLI boundary; a no-op when the directory does not exist. The Kotlin/Java parse-cache.ClearParseCache also removes its parent dir (.krit/parse-cache) on invocation, so either entry point is sufficient — both are registered so order doesn't matter.

func DensityMultiplier

func DensityMultiplier(density string) float64

DensityMultiplier returns the multiplier for a given density name, or 0 if unknown.

func HasPermission

func HasPermission(c Component) bool

HasPermission returns true if a component declares android:permission.

func IsAnimatedGIF

func IsAnimatedGIF(path string) (bool, error)

IsAnimatedGIF returns true if the GIF file at path contains multiple frames (i.e., is an animated GIF). Returns false for single-frame GIFs.

func IsAnimatedPNG

func IsAnimatedPNG(path string) (bool, error)

IsAnimatedPNG returns true if the PNG file at path is an APNG (Animated PNG). APNG files contain an acTL (animation control) chunk before the first IDAT chunk. Regular PNG files do not have this chunk.

func IsExported

func IsExported(c Component, hasIntentFilters bool) bool

IsExported returns true if a component is exported. A component is considered exported if android:exported="true", or if exported is unset and the component has at least one intent-filter (the pre-API-31 default behavior).

func IsLayoutView

func IsLayoutView(viewType string) bool

IsLayoutView returns true if the view type is a layout container.

func IsScrollableView

func IsScrollableView(viewType string) bool

IsScrollableView returns true if the view type is a scrolling container.

func ResourceGraphCacheDir

func ResourceGraphCacheDir(repoDir string) string

func ResourceGraphKey

func ResourceGraphKey(resDirs []string, hashes map[string]string) (string, bool)

func ScanLayoutResourcesWithStatsWorkers

func ScanLayoutResourcesWithStatsWorkers(resDir string, maxWorkers int) (*ResourceIndex, ResourceScanStats, error)

ScanLayoutResourcesWithStatsWorkers scans only layout and drawable-like resource directories from an Android res/ directory.

func ScanResourceDirWithStats

func ScanResourceDirWithStats(resDir string) (*ResourceIndex, ResourceScanStats, error)

ScanResourceDirWithStats scans an Android res/ directory and returns the resource index plus coarse timing for the scan internals.

func ScanResourceDirWithStatsWorkers

func ScanResourceDirWithStatsWorkers(resDir string, maxWorkers int) (*ResourceIndex, ResourceScanStats, error)

ScanResourceDirWithStatsWorkers scans an Android res/ directory with an explicit worker cap and returns the resource index plus coarse timing.

func ScanValuesResourcesWithStatsKindsWorkers

func ScanValuesResourcesWithStatsKindsWorkers(resDir string, maxWorkers int, kinds ValuesScanKind) (*ResourceIndex, ResourceScanStats, error)

func ScanValuesResourcesWithStatsWorkers

func ScanValuesResourcesWithStatsWorkers(resDir string, maxWorkers int) (*ResourceIndex, ResourceScanStats, error)

ScanValuesResourcesWithStatsWorkers scans only values resource directories from an Android res/ directory.

func SetActiveResourceIndexCache

func SetActiveResourceIndexCache(c *ResourceIndexCache)

SetActiveResourceIndexCache installs c as the process-global cache consulted by scanValuesDirIndexKinds. Passing nil disables cache use for the remainder of the process.

func SetActiveXMLParseCache

func SetActiveXMLParseCache(pc *XMLParseCache)

SetActiveXMLParseCache installs pc as the process-wide cache used by ParseXMLAST. Passing nil clears the active cache (equivalent to disabling the cache). NewXMLParseCache installs itself automatically; this helper is for tests and for callers that construct a cache lazily.

func XMLGrammarVersion

func XMLGrammarVersion() string

XMLGrammarVersion returns a stable identifier for the in-tree tree-sitter-xml binding. The SymbolCount is appended so regenerating the grammar (even without bumping the go-tree-sitter dep) still invalidates cached entries.

Types

type Activity

type Activity struct {
	Name          string         `xml:"http://schemas.android.com/apk/res/android name,attr"`
	Exported      string         `xml:"http://schemas.android.com/apk/res/android exported,attr"`
	Permission    string         `xml:"http://schemas.android.com/apk/res/android permission,attr"`
	IntentFilters []IntentFilter `xml:"intent-filter"`
}

Activity is an <activity> element.

type Application

type Application struct {
	Name                  string     `xml:"http://schemas.android.com/apk/res/android name,attr"`
	Debuggable            string     `xml:"http://schemas.android.com/apk/res/android debuggable,attr"`
	AllowBackup           string     `xml:"http://schemas.android.com/apk/res/android allowBackup,attr"`
	LocaleConfig          string     `xml:"http://schemas.android.com/apk/res/android localeConfig,attr"`
	SupportsRtl           string     `xml:"http://schemas.android.com/apk/res/android supportsRtl,attr"`
	ExtractNativeLibs     string     `xml:"http://schemas.android.com/apk/res/android extractNativeLibs,attr"`
	UsesCleartextTraffic  string     `xml:"http://schemas.android.com/apk/res/android usesCleartextTraffic,attr"`
	NetworkSecurityConfig string     `xml:"http://schemas.android.com/apk/res/android networkSecurityConfig,attr"`
	FullBackupContent     string     `xml:"http://schemas.android.com/apk/res/android fullBackupContent,attr"`
	DataExtractionRules   string     `xml:"http://schemas.android.com/apk/res/android dataExtractionRules,attr"`
	Theme                 string     `xml:"http://schemas.android.com/apk/res/android theme,attr"`
	Label                 string     `xml:"http://schemas.android.com/apk/res/android label,attr"`
	Icon                  string     `xml:"http://schemas.android.com/apk/res/android icon,attr"`
	Activities            []Activity `xml:"activity"`
	Services              []Service  `xml:"service"`
	Receivers             []Receiver `xml:"receiver"`
	Providers             []Provider `xml:"provider"`
	MetaData              []MetaData `xml:"meta-data"`
}

Application holds application-level attributes and components.

type BuildConfig

type BuildConfig struct {
	MinSdkVersion     int
	TargetSdkVersion  int
	CompileSdkVersion int
	Dependencies      []Dependency
	Plugins           []string
	IsAndroid         bool
	BuildFeatures     BuildFeatures
}

BuildConfig holds parsed configuration from a Gradle build file.

func ParseBuildGradle

func ParseBuildGradle(path string) (*BuildConfig, error)

ParseBuildGradle reads and parses a Gradle build file at the given path.

func ParseBuildGradleContent

func ParseBuildGradleContent(content string) (*BuildConfig, error)

ParseBuildGradleContent parses Gradle build file content and returns a BuildConfig.

type BuildFeatures

type BuildFeatures struct {
	Compose     bool
	ViewBinding bool
	DataBinding bool
	BuildConfig bool
	AidL        bool
}

BuildFeatures tracks Android build feature flags.

type CachedResourceGraphBuilder

type CachedResourceGraphBuilder struct {
	Builder ResourceGraphBuilder
	Cache   ResourceGraphCache
}

func (CachedResourceGraphBuilder) Build

func (b CachedResourceGraphBuilder) Build(root string, resDirs []string, hashes map[string]string) (*ResourceGraph, error)

type Component

type Component struct {
	Name       string
	Exported   string // "true", "false", or "" (unset)
	Permission string
}

Component is the shared interface for all Android manifest components.

type ComponentResult

type ComponentResult struct {
	Component
	Type          string // "activity", "service", "receiver", "provider"
	IntentFilters []IntentFilter
	Authorities   string // only for providers
}

ComponentResult wraps a found component with its type information.

type ConvertedComponent

type ConvertedComponent struct {
	Tag                     string
	Name                    string
	Line                    int
	Exported                *bool
	Permission              string
	HasIntentFilter         bool
	ParentTag               string
	IntentFilterActions     []string
	IntentFilterCategories  []string
	IntentFilterDataSchemes []string
	MetaDataEntries         []ConvertedMetaData
}

ConvertedComponent holds component data for rules.

type ConvertedElement

type ConvertedElement struct {
	Tag       string
	Line      int
	ParentTag string
}

ConvertedElement holds element data for rules.

type ConvertedManifest

type ConvertedManifest struct {
	Path        string
	Package     string
	MinSDK      int
	TargetSDK   int
	HasUsesSdk  bool
	UsesSdkLine int

	UsesPermissions []string
	Permissions     []string
	UsesFeatures    []ConvertedUsesFeature

	// Application fields
	HasApplication        bool
	AppLine               int
	AllowBackup           *bool
	Debuggable            *bool
	LocaleConfig          string
	SupportsRtl           *bool
	ExtractNativeLibs     *bool
	Icon                  string
	UsesCleartextTraffic  *bool
	FullBackupContent     string
	DataExtractionRules   string
	NetworkSecurityConfig string

	// Components
	Activities []ConvertedComponent
	Services   []ConvertedComponent
	Receivers  []ConvertedComponent
	Providers  []ConvertedComponent

	// All elements for WrongManifestParent checks
	Elements []ConvertedElement
}

ConvertedManifest holds the intermediate data extracted from parsing that main.go can use to populate rules.Manifest without circular imports.

func ConvertManifest

func ConvertManifest(m *Manifest, path string) *ConvertedManifest

ConvertManifest converts a parsed android.Manifest into the intermediate format that main.go uses to build rules.Manifest.

type ConvertedMetaData

type ConvertedMetaData struct {
	Name     string
	Value    string
	Resource string
}

ConvertedMetaData holds a single meta-data entry for rules.

type ConvertedUsesFeature

type ConvertedUsesFeature struct {
	Name     string
	Required string
	Line     int
}

ConvertedUsesFeature holds a <uses-feature> entry for rules.

type Density

type Density struct {
	Name       string  // e.g., "mdpi", "hdpi"
	Multiplier float64 // relative to mdpi (1.0)
}

Density represents an Android screen density bucket.

type Dependency

type Dependency struct {
	Group         string
	Name          string
	Version       string
	Configuration string
}

Dependency represents a single external dependency declaration.

type DiskResourceGraphCache

type DiskResourceGraphCache struct{}

func (DiskResourceGraphCache) Load

func (DiskResourceGraphCache) Load(root, key string) (*ResourceGraph, bool)

func (DiskResourceGraphCache) Save

func (DiskResourceGraphCache) Save(root, key string, graph *ResourceGraph) error

type ElementInfo

type ElementInfo struct {
	Tag       string
	ParentTag string
	Line      int
}

ElementInfo captures raw XML element names and parents for manifest-oriented lint rules.

type ExtraTextEntry

type ExtraTextEntry struct {
	FilePath string
	Line     int
	Text     string
}

ExtraTextEntry records stray text found between elements in a values XML file.

type FileReference

type FileReference struct {
	Path string // file containing the reference
	Line int    // 1-based line number
	Text string // the line text containing the reference
}

FileReference records a location where a resource file is referenced by its full name (including extension). Such references would break if the file is renamed or converted to a different format (e.g. PNG -> WebP).

func ScanFileReferences

func ScanFileReferences(searchDirs []string, fileName string) []FileReference

ScanFileReferences searches Kotlin, Java, and XML files under searchDirs for literal occurrences of fileName (e.g. "icon.png"). It returns every location where fileName appears as a substring of a source line.

Android resolves drawable references by resource name (without extension), so "@drawable/icon" is safe for both icon.png and icon.webp. This function specifically targets direct file-name references that would break after a format conversion.

type GradleLint

type GradleLint struct {
	Rule    string
	Message string
	Line    int
}

GradleLint represents a single lint finding from Gradle file analysis.

func LintBuildGradle

func LintBuildGradle(content string, cfg *BuildConfig, minSdkThreshold int) []GradleLint

LintBuildGradle runs all Gradle lint rules against the given content and config. minSdkThreshold is the minimum acceptable minSdk value for MinSdkTooLow.

type GraphResolver

type GraphResolver struct {
	Graph *ResourceGraph
}

func (GraphResolver) AffectedFiles

func (r GraphResolver) AffectedFiles(changed []string) []string

type IconFile

type IconFile struct {
	Path    string // absolute file path
	Name    string // resource name without extension
	Width   int    // 0 if unknown (xml, etc.)
	Height  int    // 0 if unknown
	Density string // density bucket from directory name
	Format  string // png, jpg, gif, webp, xml
	Size    int64  // file size in bytes
	Hash    string // SHA-256 hex digest for duplicate detection
}

IconFile represents a single icon resource file.

func (*IconFile) ExtensionFormat

func (ic *IconFile) ExtensionFormat() string

ExtensionFormat returns the format implied by the file extension of the icon's path.

func (*IconFile) IsNinePatch

func (ic *IconFile) IsNinePatch() bool

IsNinePatch returns true if the file has a .9.png extension.

type IconIndex

type IconIndex struct {
	Densities   map[string][]*IconFile // density -> list of icon files
	Icons       []*IconFile            // all icon files
	ConfigIcons []*IconFile            // icons in non-density config folders (e.g., drawable-en, drawable-fr)
}

IconIndex holds all icon resources organized by density.

func ScanIconDirs

func ScanIconDirs(resDir string) (*IconIndex, error)

ScanIconDirs scans res/drawable-* and res/mipmap-* directories for icon resources.

func ScanIconDirsWithWorkers

func ScanIconDirsWithWorkers(resDir string, maxWorkers int) (*IconIndex, error)

func (*IconIndex) ConfigIconsByName

func (idx *IconIndex) ConfigIconsByName() map[string][]*IconFile

ConfigIconsByName groups config icons by their resource name.

func (*IconIndex) IconsByName

func (idx *IconIndex) IconsByName() map[string][]*IconFile

IconsByName groups icons by their resource name across densities.

type IconScanFuture

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

IconScanFuture memoizes a background icon scan for a single res/ dir.

func NewIconScanFuture

func NewIconScanFuture(resDir string, startLimiter chan struct{}, maxWorkers ...int) *IconScanFuture

func (*IconScanFuture) Await

func (f *IconScanFuture) Await() (*IconIndex, error)

func (*IconScanFuture) Duration

func (f *IconScanFuture) Duration() time.Duration

func (*IconScanFuture) Start

func (f *IconScanFuture) Start()

type Intent

type Intent struct {
	Actions []IntentAction `xml:"action"`
}

Intent is a <intent> element (used inside <queries>).

type IntentAction

type IntentAction struct {
	Name string `xml:"http://schemas.android.com/apk/res/android name,attr"`
}

IntentAction is an <action> within an intent-filter.

type IntentCategory

type IntentCategory struct {
	Name string `xml:"http://schemas.android.com/apk/res/android name,attr"`
}

IntentCategory is a <category> within an intent-filter.

type IntentData

type IntentData struct {
	Scheme string `xml:"http://schemas.android.com/apk/res/android scheme,attr"`
	Host   string `xml:"http://schemas.android.com/apk/res/android host,attr"`
}

IntentData is a <data> element within an intent-filter.

type IntentFilter

type IntentFilter struct {
	Actions    []IntentAction   `xml:"action"`
	Categories []IntentCategory `xml:"category"`
	Data       []IntentData     `xml:"data"`
}

IntentFilter is an <intent-filter> element.

type Layout

type Layout struct {
	Name     string
	FilePath string // absolute path to the layout XML file
	RootView *View
}

Layout represents a parsed Android layout XML file.

func (*Layout) FindViewsByType

func (l *Layout) FindViewsByType(viewType string) []*View

FindViewsByType returns all views of the given type in the layout tree.

func (*Layout) MaxDepth

func (l *Layout) MaxDepth() int

MaxDepth returns the maximum nesting depth of the layout.

func (*Layout) ViewCount

func (l *Layout) ViewCount() int

ViewCount returns the total number of views in a layout.

type LazyValuesScan

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

LazyValuesScan starts values parsing on demand and caches the merged result so callers can overlap work and apply the parsed values later.

func NewLazyValuesScan

func NewLazyValuesScan(dir string, maxWorkers int, kinds ...ValuesScanKind) *LazyValuesScan

NewLazyValuesScan returns a reusable provider for a single values/ directory.

func (*LazyValuesScan) LoadInto

func (p *LazyValuesScan) LoadInto(idx *ResourceIndex) (ResourceScanStats, error)

LoadInto waits for the values scan if needed and merges the results into idx.

func (*LazyValuesScan) Start

func (p *LazyValuesScan) Start()

Start begins the background values scan. Calling Start multiple times is safe.

type Manifest

type Manifest struct {
	Package         string           `xml:"package,attr"`
	VersionCode     string           `xml:"http://schemas.android.com/apk/res/android versionCode,attr"`
	VersionName     string           `xml:"http://schemas.android.com/apk/res/android versionName,attr"`
	UsesSdk         UsesSdk          `xml:"uses-sdk"`
	UsesPermissions []UsesPermission `xml:"uses-permission"`
	Permissions     []Permission     `xml:"permission"`
	Application     Application      `xml:"application"`
	Queries         []Intent         `xml:"queries>intent"`
	UsesFeatures    []UsesFeature    `xml:"uses-feature"`
	Elements        []ElementInfo    `xml:"-"`
	Root            *XMLNode         `xml:"-"`
}

Manifest represents a parsed AndroidManifest.xml.

func ParseManifest

func ParseManifest(path string) (*Manifest, error)

ParseManifest reads and parses an AndroidManifest.xml file.

func ParseManifestBytes

func ParseManifestBytes(data []byte) (*Manifest, error)

ParseManifestBytes parses AndroidManifest.xml content from bytes.

func (*Manifest) AllComponents

func (m *Manifest) AllComponents() []ComponentResult

AllComponents returns every component in the manifest as ComponentResults.

func (*Manifest) ExportedWithoutPermission

func (m *Manifest) ExportedWithoutPermission() []ComponentResult

ExportedWithoutPermission returns components that are exported but have no android:permission set. Useful for security lint checks.

func (*Manifest) FindComponent

func (m *Manifest) FindComponent(name string) *ComponentResult

FindComponent searches all component types by class name. The name can be a simple class name (e.g. "MainActivity"), a relative name (e.g. ".MainActivity"), or a fully qualified name (e.g. "com.example.MainActivity").

type MetaData

type MetaData struct {
	Name     string `xml:"http://schemas.android.com/apk/res/android name,attr"`
	Value    string `xml:"http://schemas.android.com/apk/res/android value,attr"`
	Resource string `xml:"http://schemas.android.com/apk/res/android resource,attr"`
}

MetaData is a <meta-data> element.

type Permission

type Permission struct {
	Name            string `xml:"http://schemas.android.com/apk/res/android name,attr"`
	ProtectionLevel string `xml:"http://schemas.android.com/apk/res/android protectionLevel,attr"`
}

Permission is a <permission> element.

type Project

type Project struct {
	ManifestPaths []string // paths to AndroidManifest.xml files
	ResDirs       []string // paths to res/ directories
	GradlePaths   []string // paths to build.gradle or build.gradle.kts files
}

Project holds the paths to Android project files discovered during scanning.

func DetectProject

func DetectProject(scanPaths []string) *Project

DetectProject walks the given scan paths looking for Android project files: AndroidManifest.xml, src/main/res/, build.gradle, build.gradle.kts. It returns an Project with all discovered paths.

func DetectProjectWithIndex

func DetectProjectWithIndex(scanPaths []string, index trackedfiles.Index) *Project

DetectProjectWithIndex is DetectProject with injectable tracked-file discovery for tests and callers that already have a shared listing.

func (*Project) IsEmpty

func (p *Project) IsEmpty() bool

IsEmpty returns true if no Android project files were found.

type Provider

type Provider struct {
	Name        string `xml:"http://schemas.android.com/apk/res/android name,attr"`
	Exported    string `xml:"http://schemas.android.com/apk/res/android exported,attr"`
	Permission  string `xml:"http://schemas.android.com/apk/res/android permission,attr"`
	Authorities string `xml:"http://schemas.android.com/apk/res/android authorities,attr"`
}

Provider is a <provider> element.

type Receiver

type Receiver struct {
	Name          string         `xml:"http://schemas.android.com/apk/res/android name,attr"`
	Exported      string         `xml:"http://schemas.android.com/apk/res/android exported,attr"`
	Permission    string         `xml:"http://schemas.android.com/apk/res/android permission,attr"`
	IntentFilters []IntentFilter `xml:"intent-filter"`
	MetaData      []MetaData     `xml:"meta-data"`
}

Receiver is a <receiver> element.

type ResourceDependencyResolver

type ResourceDependencyResolver interface {
	AffectedFiles(changed []string) []string
}

type ResourceFileNode

type ResourceFileNode struct {
	Path    string       `json:"path"`
	Defines []ResourceID `json:"defines"`
	Refs    []ResourceID `json:"refs"`
}

type ResourceGraph

type ResourceGraph struct {
	Files       map[string]ResourceFileNode `json:"files"`
	DefinedIn   map[ResourceID][]string     `json:"definedIn"`
	ReverseDeps map[string][]string         `json:"reverseDeps"`
}

type ResourceGraphBuilder

type ResourceGraphBuilder interface {
	Build(root string, resDirs []string, hashes map[string]string) (*ResourceGraph, error)
}

type ResourceGraphCache

type ResourceGraphCache interface {
	Load(root, key string) (*ResourceGraph, bool)
	Save(root, key string, graph *ResourceGraph) error
}

type ResourceID

type ResourceID struct {
	Type string `json:"type"`
	Name string `json:"name"`
}

type ResourceIndex

type ResourceIndex struct {
	Layouts             map[string]*Layout            // layout name -> parsed layout (last wins for compat)
	LayoutConfigs       map[string]map[string]*Layout // layout name -> config qualifier -> layout
	Strings             map[string]string             // string name -> value
	StringsNonTranslate map[string]bool               // strings marked translatable="false"
	// StringsNonFormatted marks strings with formatted="false". These are
	// NOT format strings — their `%{var}` / `%foo` sequences are literal,
	// typically for gettext/phrase-style translation interpolation, and
	// format-specifier-validation rules should skip them.
	StringsNonFormatted map[string]bool
	// StringsTrailingWS marks strings whose raw XML text content ended with
	// whitespace before TrimSpace. Significant in some locales and in
	// concatenated strings.
	StringsTrailingWS map[string]bool
	StringsLocation   map[string]StringLocation    // string name -> file path and line
	Colors            map[string]string            // color name -> value
	Dimensions        map[string]string            // dimen name -> value
	Styles            map[string]*Style            // style name -> style definition
	Drawables         []string                     // drawable resource names
	DrawableSelectors map[string][]SelectorItem    // selector drawable name -> child items
	StringArrays      map[string][]string          // string-array name -> items
	Plurals           map[string]map[string]string // plural name -> quantity -> value
	Integers          map[string]string            // integer name -> value
	Booleans          map[string]string            // bool name -> value
	IDs               map[string]bool              // declared @+id names
	ExtraTexts        []ExtraTextEntry             // stray text nodes in values files
}

ResourceIndex holds all parsed Android resource data from a res/ directory.

func MergeResourceIndexes

func MergeResourceIndexes(indexes ...*ResourceIndex) *ResourceIndex

MergeResourceIndexes combines multiple partial resource indexes into one.

func ScanResourceDir

func ScanResourceDir(resDir string) (*ResourceIndex, error)

ScanResourceDir scans an Android res/ directory and returns a ResourceIndex.

type ResourceIndexCache

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

ResourceIndexCache persists parsed ResourceIndex results keyed by per-directory content fingerprint. A nil *ResourceIndexCache is a valid disabled cache — every method is a safe no-op.

func ActiveResourceIndexCache

func ActiveResourceIndexCache() *ResourceIndexCache

ActiveResourceIndexCache returns the most-recently-opened cache, or nil when none has been constructed.

func NewResourceIndexCache

func NewResourceIndexCache(repoDir string) (*ResourceIndexCache, error)

NewResourceIndexCache opens (creating if needed) the resource-cache directory under repoDir/.krit. A schema-version or hash-algo change in the sidecar metadata wipes the entries subtree before returning.

func NewResourceIndexCacheWithCap

func NewResourceIndexCacheWithCap(repoDir string, capBytes int64) (*ResourceIndexCache, error)

NewResourceIndexCacheWithCap is NewResourceIndexCache with an explicit byte cap. capBytes <= 0 disables the cap (no eviction).

func (*ResourceIndexCache) Clear

func (c *ResourceIndexCache) Clear() error

Clear removes every cache entry. The sidecar schema tokens are left in place so a subsequent Open does not see a mismatch.

func (*ResourceIndexCache) Close

func (c *ResourceIndexCache) Close() error

Close flushes async writes and the LRU sidecar. Safe on a nil receiver.

func (*ResourceIndexCache) CloseIdle

func (c *ResourceIndexCache) CloseIdle() error

CloseIdle shuts down background workers without persisting read-hit LRU touches. It is intended for invocations that only loaded cache entries.

func (*ResourceIndexCache) HasWrites

func (c *ResourceIndexCache) HasWrites() bool

HasWrites reports whether this process queued or completed resource-index cache writes. Read-hit LRU touches do not count.

func (*ResourceIndexCache) LRUStats

func (c *ResourceIndexCache) LRUStats() cacheutil.LRUStats

LRUStats returns the raw LRU snapshot for --perf / tests.

func (*ResourceIndexCache) Load

func (c *ResourceIndexCache) Load(fingerprint string, _ ValuesScanKind, _ string) (*ResourceIndex, bool)

Load tries to load a cached ResourceIndex for the given fingerprint. Returns (index, true) on hit; (nil, false) on miss, corrupt entry, or any read/decode error. A nil cache is always a miss.

func (*ResourceIndexCache) Root

func (c *ResourceIndexCache) Root() string

Root returns the on-disk root directory for the resource cache. Exposed for diagnostics and tests.

func (*ResourceIndexCache) Save

func (c *ResourceIndexCache) Save(fingerprint string, _ ValuesScanKind, _ string, idx *ResourceIndex) error

Save persists idx under fingerprint. A write failure is returned but callers typically discard it — the next run will just miss.

func (*ResourceIndexCache) SaveAsync

func (c *ResourceIndexCache) SaveAsync(fingerprint string, kinds ValuesScanKind, resDir string, idx *ResourceIndex) error

SaveAsync persists idx outside the caller's critical path when the background writer has capacity. The ResourceIndex is cloned before queueing so later merges or rule execution cannot race with gob encoding.

func (*ResourceIndexCache) Stats

Stats returns a unified stats snapshot.

type ResourceScanFuture

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

ResourceScanFuture memoizes a background resource scan for a single res/ dir.

func NewLayoutScanFuture

func NewLayoutScanFuture(resDir string, startLimiter chan struct{}, maxWorkers ...int) *ResourceScanFuture

func NewResourceScanFuture

func NewResourceScanFuture(resDir string, startLimiter chan struct{}, maxWorkers ...int) *ResourceScanFuture

func NewValuesScanFuture

func NewValuesScanFuture(resDir string, startLimiter chan struct{}, kinds ValuesScanKind, maxWorkers ...int) *ResourceScanFuture

func (*ResourceScanFuture) Await

func (*ResourceScanFuture) Duration

func (f *ResourceScanFuture) Duration() time.Duration

func (*ResourceScanFuture) Start

func (f *ResourceScanFuture) Start()

type ResourceScanStats

type ResourceScanStats struct {
	LayoutScanMs      int64
	ValuesScanMs      int64
	DrawableScanMs    int64
	ValuesReadMs      int64
	ValuesParseMs     int64
	ValuesIndexMs     int64
	MergeMs           int64
	MaxLayoutScanMs   int64
	MaxValuesScanMs   int64
	MaxDrawableScanMs int64
	LayoutDirCount    int64
	ValuesDirCount    int64
	DrawableDirCount  int64
}

ResourceScanStats captures where time is spent while indexing a res/ directory.

type ResourceValueProvider

type ResourceValueProvider interface {
	LoadInto(idx *ResourceIndex) (ResourceScanStats, error)
}

ResourceValueProvider materializes values XML resources into a ResourceIndex. Providers may load eagerly or lazily, but must preserve the current merged output semantics when applied.

type SelectorItem

type SelectorItem struct {
	FilePath   string
	Line       int
	StateAttrs map[string]string
}

SelectorItem records a child <item> in a drawable selector XML file.

type Service

type Service struct {
	Name          string         `xml:"http://schemas.android.com/apk/res/android name,attr"`
	Exported      string         `xml:"http://schemas.android.com/apk/res/android exported,attr"`
	Permission    string         `xml:"http://schemas.android.com/apk/res/android permission,attr"`
	IntentFilters []IntentFilter `xml:"intent-filter"`
}

Service is a <service> element.

type StringLocation

type StringLocation struct {
	FilePath string
	Line     int
}

StringLocation records where a <string> element was defined.

type Style

type Style struct {
	Name   string
	Parent string
	Items  map[string]string // item name -> value
}

Style represents an Android style definition.

type UsesFeature

type UsesFeature struct {
	Name     string `xml:"http://schemas.android.com/apk/res/android name,attr"`
	Required string `xml:"http://schemas.android.com/apk/res/android required,attr"`
}

UsesFeature is a <uses-feature> element.

type UsesPermission

type UsesPermission struct {
	Name string `xml:"http://schemas.android.com/apk/res/android name,attr"`
}

UsesPermission is a <uses-permission> element.

type UsesSdk

type UsesSdk struct {
	MinSdkVersion    string `xml:"http://schemas.android.com/apk/res/android minSdkVersion,attr"`
	TargetSdkVersion string `xml:"http://schemas.android.com/apk/res/android targetSdkVersion,attr"`
}

UsesSdk holds minSdkVersion and targetSdkVersion.

type ValuesScanKind

type ValuesScanKind uint32
const (
	ValuesScanNone    ValuesScanKind = 0
	ValuesScanStrings ValuesScanKind = 1 << iota
	ValuesScanDimensions
	ValuesScanPlurals
	ValuesScanArrays
	ValuesScanExtraText
)

type View

type View struct {
	Type               string            // e.g., "TextView", "LinearLayout"
	ID                 string            // android:id value (e.g., "@+id/title")
	ContentDescription string            // android:contentDescription
	Text               string            // android:text
	LayoutWidth        string            // android:layout_width
	LayoutHeight       string            // android:layout_height
	Background         string            // android:background
	Attributes         map[string]string // all attributes
	Children           []*View
	Line               int // 1-based line number in the XML file
}

View represents a single view element in a layout hierarchy.

func (*View) HasContentDescription

func (v *View) HasContentDescription() bool

HasContentDescription checks if a view has a contentDescription attribute set.

func (*View) HasHardcodedText

func (v *View) HasHardcodedText() bool

HasHardcodedText checks if a view has hardcoded text (not a resource reference).

type XMLAttribute

type XMLAttribute struct {
	Name      string
	Value     string
	Line      int
	Col       int
	StartByte uint
	EndByte   uint
}

XMLAttribute is a position-aware XML attribute.

type XMLNode

type XMLNode struct {
	Tag       string
	Line      int
	Col       int
	StartByte uint
	EndByte   uint
	Attrs     []XMLAttribute
	Children  []*XMLNode
	Text      string
}

XMLNode is a position-aware XML element tree node.

func ParseXMLAST

func ParseXMLAST(data []byte) (*XMLNode, error)

func (*XMLNode) Attr

func (n *XMLNode) Attr(name string) string

func (*XMLNode) ChildByTag

func (n *XMLNode) ChildByTag(tag string) *XMLNode

func (*XMLNode) ChildrenByTag

func (n *XMLNode) ChildrenByTag(tag string) []*XMLNode

type XMLParseCache

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

XMLParseCache persists ParseXMLAST results keyed by content hash. A nil *XMLParseCache is a valid disabled cache — every method is a safe no-op so callers can unconditionally invoke Load/Save/Close.

func ActiveXMLParseCache

func ActiveXMLParseCache() *XMLParseCache

ActiveXMLParseCache returns the currently installed cache, or nil when caching is disabled. Exposed for diagnostics and tests.

func NewXMLParseCache

func NewXMLParseCache(repoDir string) (*XMLParseCache, error)

NewXMLParseCache returns a cache rooted at repoDir/.krit/parse-cache/xml. Shares the parent parse-cache dir with the Kotlin/Java caches so --clear-cache wipes all three at once, but its own grammar-version sidecar guarantees a tree-sitter-xml bump does not invalidate Kotlin/Java entries and vice versa.

func NewXMLParseCacheWithCap

func NewXMLParseCacheWithCap(repoDir string, capBytes int64) (*XMLParseCache, error)

NewXMLParseCacheWithCap is NewXMLParseCache with an explicit byte cap. capBytes <= 0 disables eviction.

func (*XMLParseCache) Clear

func (pc *XMLParseCache) Clear() error

Clear removes every cache entry. The version / grammar-version metadata files are left in place so a subsequent NewXMLParseCache call does not see a schema mismatch.

func (*XMLParseCache) Close

func (pc *XMLParseCache) Close() error

Close flushes async writes and the LRU sidecar. Safe to call on a nil cache.

func (*XMLParseCache) CloseIdle

func (pc *XMLParseCache) CloseIdle() error

CloseIdle shuts down background workers without persisting read-hit LRU touches. It is intended for invocations that only loaded cache entries.

func (*XMLParseCache) Dir

func (pc *XMLParseCache) Dir() string

Dir returns the cache root under .krit/parse-cache/xml. Empty when pc is nil.

func (*XMLParseCache) HasWrites

func (pc *XMLParseCache) HasWrites() bool

HasWrites reports whether this process queued or completed XML parse-cache writes. Read-hit LRU touches do not count.

func (*XMLParseCache) LRUStats

func (pc *XMLParseCache) LRUStats() cacheutil.LRUStats

LRUStats returns the current LRU snapshot.

func (*XMLParseCache) Load

func (pc *XMLParseCache) Load(content []byte) (*XMLNode, bool)

Load tries to load a cached XMLNode tree for content. Returns (root, true) on hit, (nil, false) on miss, small file, or any read/decode error. A nil XMLParseCache is always a miss.

func (*XMLParseCache) Save

func (pc *XMLParseCache) Save(content []byte, root *XMLNode) error

Save persists the parse result for content. Small files are skipped. A nil pc or nil root is a no-op.

func (*XMLParseCache) SaveAsync

func (pc *XMLParseCache) SaveAsync(content []byte, root *XMLNode) error

SaveAsync persists the parse result outside the caller's critical path when the background writer has capacity. Hashing stays synchronous so cache keys are stable before returning; the XML tree is cloned before queueing because callers may keep using the returned node tree immediately.

func (*XMLParseCache) Stats

func (pc *XMLParseCache) Stats() cacheutil.CacheStats

Stats returns a unified snapshot. Counter fields are running totals for the current process; Entries and Bytes come from the LRU sidecar.

type XMLResourceGraphBuilder

type XMLResourceGraphBuilder struct{}

func (XMLResourceGraphBuilder) Build

func (XMLResourceGraphBuilder) Build(_ string, resDirs []string, _ map[string]string) (*ResourceGraph, error)

Jump to

Keyboard shortcuts

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