Documentation
¶
Overview ¶
Code generated by tools/registrygen; DO NOT EDIT. Linguist heuristics: 5fbdfcb8133be2bed88bf3ce62b2335f50474525. Copyright (c) 2017 GitHub, Inc. MIT license: LICENSE.linguist.
Package languages identifies source languages from content and paths. Content analysis does not require or retain a filename or the input buffer.
Code generated by tools/registrygen; DO NOT EDIT. Linguist metadata: 5fbdfcb8133be2bed88bf3ce62b2335f50474525. Copyright (c) 2017 GitHub, Inc. MIT license: LICENSE.linguist.
Index ¶
- Constants
- func Analyze(data []byte, complete bool, dst *Analysis)
- func AnalyzeReader(ctx context.Context, reader io.Reader, options ReadOptions, dst *Analysis) error
- type Analysis
- type Confidence
- type Context
- type Directory
- type Evidence
- type FileTotals
- type Language
- type LanguageTotals
- type Match
- type ReadOptions
- type Result
- type ScanOptions
- type Set
- type Summary
- type Tree
Examples ¶
Constants ¶
const DefaultBytes = 0
DefaultBytes reads the entire file. Positive read budgets select a prefix.
const MaxSignals = 128
Variables ¶
This section is empty.
Functions ¶
func Analyze ¶
Analyze inspects all supplied bytes. complete must be false for a prefix whose suffix is unavailable. dst must be non-nil and owned by the calling goroutine.
Example ¶
package main
import (
"fmt"
"github.com/git-pkgs/languages"
)
func main() {
var content languages.Analysis
languages.Analyze([]byte("use strict;\nuse warnings;\n"), false, &content)
r := content.Result()
fmt.Println(r.Language, r.Confidence)
fmt.Println(languages.AnalyzePath("source.pl").Candidates.Has(languages.Prolog))
fmt.Println(languages.Combine(&content, languages.AnalyzePath("source.pl")).Language)
}
Output: Perl high true Perl
func AnalyzeReader ¶
AnalyzeReader reads content with bounded memory. Reaching a byte budget without EOF leaves Prefix true. Errors clear dst. Cancellation is checked between reads; it cannot interrupt an io.Reader blocked inside Read.
Types ¶
type Analysis ¶
type Analysis struct {
Signals [MaxSignals]Match
Count int
Bytes int64
Prefix bool
Binary bool
// contains filtered or unexported fields
}
Analysis is a reusable, value-copyable content result with no input references. Only Signals[:Count] is populated. It can be stored with a content object's ID. Prefix is true unless the caller supplied the complete object. JSON encoding omits classifier state.
type Confidence ¶
type Confidence string
const ( None Confidence = "none" Low Confidence = "low" Medium Confidence = "medium" High Confidence = "high" )
func (Confidence) Rank ¶
func (c Confidence) Rank() int
Rank orders confidence from none (0) to high (3). Unknown values rank as none.
type Context ¶
Context is occurrence-specific evidence. No path string is retained.
func AnalyzePath ¶
AnalyzePath examines only the final path component, with either path separator. Filenames are case-sensitive; extensions are case-insensitive.
type Directory ¶
type Directory struct {
Path string `json:"path"`
Summary Summary `json:"summary"`
Children []Directory `json:"children,omitempty"`
}
Directory includes totals for all descendants. Path is relative to the tree root.
type FileTotals ¶
type Language ¶
type Language uint16
Language identifies a language within a detector build. Store names, not indices.
const ( Language1CEnterprise Language = Prolog + 1 + iota Language2DimensionalArray Language4D ABAP ABAPCDS ABNF AGSScript AIDL AL ALGOL AMPL ANTLR APIBlueprint APL ASL ASN1 ASPNET ATS ActionScript Ada AdblockFilterList AdobeFontMetrics Agda Aiken Aleo Alloy AlpineAbuild AltiumDesigner AngelScript AnswerSetProgramming AntBuildSystem Antlers ApacheConf Apex ApolloGuidanceComputer AppleScript Arc ArkTS AsciiDoc AspectJ Assembly Astro Asymptote Augeas AutoHotkey AutoIt AvroIDL Awk B BFormalMethod B4X BAML BASIC BBCode BIRD2 BQN Ballerina Batchfile Beef Befunge Bend Berry BibTeX BibTeXStyle Bicep Bikeshed Bison BitBake Blade BlitzBasic BlitzMax Blueprint Bluespec BluespecBH Boo Boogie Brainfuck BrighterScript Brightscript Browserslist Bru BuildStream CObjDump C2hsHaskell C3 CAPCDS CIL CLIPS CMake COBOL CODEOWNERS COLLADA CQL CSON CSS CSV CUE CWeb CabalConfig Caddyfile Cadence Cairo CairoZero CameLIGO Cangjie CapNProto Carbon CartoCSS Ceylon Chapel Charity Checksums ChucK Circom Cirru Clarion Clarity ClassicASP Clean Click ClosureTemplates CloudFirestoreSecurityRules Clue CoNLLU CodeQL CoffeeScript ColdFusion ColdFusionCFC CommonWorkflowLanguage ComponentPascal Cooklang Cool CppObjDump Creole Crystal Csound CsoundDocument CsoundScore Cuda CueSheet Curry Cycript Cylc Cypher Cython D DObjDump D2 DIGITALCommandLanguage DM DNSZone DTrace Dafny DarcsPatch Dart Daslang DataWeave DebianPackageControlFile DenizenScript Dhall Diff DirectX3DFile Dockerfile Dogescript Dotenv Dune Dylan E EMail EBNF ECL ECLiPSe EJS EQ Eagle Earthly Easybuild EcereProjects Ecmarkup Edge EdgeQL EditorConfig EdjeDataCollection Eiffel Elixir Elm Elvish ElvishTranscript EmacsLisp EmberScript Erlang Euphoria FSharp F FIGletFont FIRRTL FLUX FPP Factor Fancy Fantom Faust Fennel FilebenchWML Filterscript FlatBuffers Flix Fluent Formatted Forth Fortran FortranFreeForm FreeBASIC FreeMarker Frege Futhark GCode GAML GAMS GAP GCCMachineDescription GDB GDScript GDShader GEDCOM GLSL GN GSC GameMakerLanguage GemfileLock Gemini Genero4gl GeneroPer Genie Genshi GentooEbuild GentooEclass GerberImage GettextCatalog Gherkin GitAttributes GitCommit GitConfig GitRevisionList Gleam GlimmerJS GlimmerTS Glyph GlyphBitmapDistributionFormat Gno Gnuplot GoChecksums GoModule GoTemplate GoWorkspace GodotResource Golo Gosu Grace Gradle GradleKotlinDSL GrammaticalFramework GraphModelingLanguage GraphQL GraphvizDOT Groovy GroovyServerPages GtkRC HAProxy HCL HIP HLSL HOCON HTMLPlusECR HTMLPlusEEX HTMLPlusRazor HTTP HXML Hack Haml Handlebars Harbour Hare Haskell Haxe HiveQL HolyC HostsFile Hurl Hy HyPhy IDL IGORPro ILAssembly INI IRCLog ISPC Idris IgnoreList ImHexPatternLanguage ImageJMacro Imba Inform7 Ink InnoSetup Io Ioke Isabelle IsabelleROOT J JARManifest JASS JCL JFlex JSON JSONWithComments JSON5 JSONLD JSONiq Jac Jai Janet Jasmin JavaProperties JavaServerPages JavaTemplateEngine JavaScriptPlusERB JestSnapshot JetBrainsMPS Jison JisonLex Jolie Jsonnet Julia JuliaREPL JupyterNotebook Just KCL KDL KFramework KRL KaitaiStruct KakouneScript KerboScript KiCadLayout KiCadLegacyLayout KiCadSchematic Kickstart Kit KoLmafiaASH Koka Kotlin Kusto LFE LLVM LLVMTableGen LOLCODE LSL LTspiceSymbol LabVIEW Lambdapi Langium Lark Lasso Latte Lean Lean4 Leo Less Lex LigoLANG LilyPond Limbo LinearProgramming LinkerScript LinuxKernelModule Liquid Liquidsoap LiterateAgda LiterateCoffeeScript LiterateHaskell LiveCodeScript LiveScript Lobster Logos Logtalk LookML LoomScript Luau M M3U M4 M4Sugar MAXScript MDX MLIR MQL4 MQL5 MTML MUF Macaulay2 Makefile Mako Markdown Marko Mask MathematicalProgrammingSystem MavenPOM Max MeTTa Mercury Mermaid Meson Metal MicrosoftDeveloperStudioProject MicrosoftVisualStudioSolution MiniD MiniScript MiniYAML MiniZinc MiniZincData Mint Mirah Modelica Modula2 Modula3 ModuleManagementSystem Mojo Monkey MonkeyC Moocode MoonBit MoonScript Motoko Motorola68KAssembly Move Muse Mustache Myghty NASL NCL NEON NL NMODL NPMConfig NSIS NWScript Nasal Nearley Nemerle NetLinx NetLinxPlusERB NetLogo NewLisp Nextflow Nginx Nickel Nim Ninja Nit Nix Noir Nu NumPy Nunjucks Nushell OASv2Json OASv2Yaml OASv3Json OASv3Yaml OCaml OMNeTPlusPlusMSG OMNeTPlusPlusNED Oberon ObjDump ObjectDataInstanceNotation ObjectScript ObjectiveCPlusPlus ObjectiveJ Odin Omgrofl Opa Opal OpenPolicyAgent OpenAPISpecificationV2 OpenAPISpecificationV3 OpenCL OpenEdgeABL OpenQASM OpenRCRunscript OpenSCAD OpenStepPropertyList OpenTypeFeatureFile OptionList Org OverPy OverpassQL Ox Oxygene Oz P4 PDDL PEGJs PLSQL PLpgSQL POVRaySDL Pact Pan Papyrus Parrot ParrotAssembly ParrotInternalRepresentation Pascal Pawn Pep8 Pic Pickle PicoLisp PigLatin Pike PipRequirements Pkl PlantUML Pod Pod6 PogoScript Polar Pony Portugol PostCSS PostScript PowerQuery PowerBuilder PowerShell Praat Prisma ProC Processing Procfile Proguard Promela PropellerSpin ProtocolBuffer ProtocolBufferTextFormat PublicKey Pug Puppet PureData PureBasic PureScript Pyret PythonConsole PythonTraceback QSharp QML QMake QtScript Quake QuakeC QuartusSimulationIP QuickBASIC Quint R RAML RAScript RBS RDoc REALbasic REXX RMarkdown RON ROSInterface RPC RPGLE RPMSpec RUNOFF Ragel Rascal RawTokenData ReScript ReadlineConfig Reason ReasonLIGO Rebol RecordJar Red Redcode RedirectRules Redscript RegularExpression RenPy RenderScript Rez Rhai RichTextFormat Ring Riot RobotFramework RobotsExclusionRules Roc RocqProver Roff RoffManpage Rouge RouterOSScript SAS SCSS SELinuxPolicy SIP SMT SPARQL SQF SQLPL SRecodeTemplate SSHConfig STAR STL STON SVG SWIG Sage Sail Salt Sass Scala Scaml Scenic Scilab Self ShaderLab ShellCheckConfig ShellSession Shen Sieve SimpleFileVerification Singularity Slang Slash Slice Slim Slint SmPL Smali Smalltalk Smarty Smithy Snakemake Solidity Soong SourcePawn SpiceDBSchema SplineFontDatabase Squirrel Stan StandardML Starlark Stata StringTemplate Stylus SubRipText SugarSS SuperCollider SurrealQL SurvexData Svelte Sway Sweave Swift SystemVerilog TIProgram TLVerilog TLA TMDL TOML TSPLIBData TSQL TSV TXL Tact Talon Tape Tcl Tcsh TeX Tea Teal Terra TerraformTemplate Texinfo Text TextGrid TextMateProperties Textile Thrift Toit Tolk TorConfig TreeSitterQuery Turing Turtle TypeLanguage TypeSpec Typst UnifiedParallelC Unity3DAsset UnixAssembly Uno UnrealScript UntypedPlutusCore UrWeb V VBA VBScript VCL VHDL Vala ValveDataFormat VelocityTemplateLanguage Vento Verilog Verse VespaSchemaDefinition VimHelpFile VimSnippet VimScript VisualBasicNET VisualBasic60 Volt Vue Vyper WDL WGSL WavefrontMaterial WavefrontObject WebOntologyLanguage WebAssembly WebAssemblyInterfaceType WebIDL WebVTT WgetConfig Whiley Wikitext Win32MessageFile WindowsRegistryEntries WitcherScript WolframLanguage Wollok WorldOfWarcraftAddonData Wren XBitMap XFontDirectoryIndex XPixMap X10 XC XCompose XMLPropertyList XPages XProc XQuery XS XSLT Xmake Xojo Xonsh Xtend YAML YANG YARA YASnippet Yacc Yul ZAP ZIL Zeek ZenScript Zephir Zig Zimpl Zmodel CURLConfig Crontab Desktop Dircolors EC Edn Hoon ICalendar Jq Kvlang MIRCScript Mcfunction Mdsvex Mupad Nanorc NesC Ooc PkgConfig Q ReStructuredText Sed Templ Ucode VCard Wisp XBase LanguageCount )
type LanguageTotals ¶
type LanguageTotals struct {
Language string `json:"language"`
FileTotals
}
type Match ¶
Match records the first occurrence of a rule. Offsets refer to the original bytes. Rule indices are build-specific; use Evidence().ID for stored results.
type ReadOptions ¶
type Result ¶
type Result struct {
Language Language
Confidence Confidence
Candidates Set
Conflict bool
Statistical bool
}
Result leaves Language empty when the evidence supports multiple candidates. Confidence describes rule support, not an empirical probability.
func Detect ¶
Detect identifies source from a filename and the supplied content. Either input may be empty. Content is treated as a prefix; use Analyze with complete=true and Analysis.Detect when the supplied content is complete.
Example ¶
package main
import (
"fmt"
"github.com/git-pkgs/languages"
)
func main() {
result := languages.Detect("app.ts", []byte("const count = 1;\n"))
fmt.Println(result.Language)
}
Output: TypeScript
type ScanOptions ¶
type Set ¶
type Set struct {
// contains filtered or unexported fields
}
Set stores language candidates without allocation. Its zero value is empty.
func (Set) MarshalJSON ¶
MarshalJSON writes candidate names, independent of numeric language indices.
func (*Set) UnmarshalJSON ¶
type Summary ¶
type Summary struct {
FileTotals
Languages []LanguageTotals `json:"languages"`
Unknown FileTotals `json:"unknown"`
Ambiguous FileTotals `json:"ambiguous"`
Conflicts FileTotals `json:"conflicts"`
Binary FileTotals `json:"binary"`
Incomplete int64 `json:"incomplete"`
}
Summary counts each file once, including files with no selected language.
type Tree ¶
type Tree struct {
// contains filtered or unexported fields
}
Tree accumulates file analyses without retaining their content or analysis buffers. Its zero value is ready to use. Add must not run concurrently with other operations.
func Scan ¶
Scan summarizes regular files in fsys. Git metadata and symlinks are skipped. Use fs.Sub to select a subtree. On an error no partial tree is returned.
Confinement depends on fsys: a file replaced after enumeration is opened as-is, and os.DirFS and fs.Sub follow the replacement. For a mutable or untrusted directory, pass os.Root.FS, subject to its documented platform guarantees.
func (*Tree) Add ¶
Add records one file using its full size and filename-contextual detection. Names must be unique, slash-separated relative file paths without dot components.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
evaluate
command
|
|
|
languages
command
|
|
|
localscan
command
|
|
|
internal
|
|
|
benchbatch
command
benchbatch measures retained heap while scanning without retaining results.
|
benchbatch measures retained heap while scanning without retaining results. |
|
classifier
Package classifier scores content with a generated lexical model.
|
Package classifier scores content with a generated lexical model. |
|
localscan
Package localscan measures local repository scans and builds weakly labelled samples.
|
Package localscan measures local repository scans and builds weakly labelled samples. |
|
modelgen
command
modelgen builds a bounded content classifier from Linguist samples.
|
modelgen builds a bounded content classifier from Linguist samples. |
|
tokenize
Package tokenize extracts lexical features for training and classification.
|
Package tokenize extracts lexical features for training and classification. |
|
wasmcheck
command
wasmcheck exercises the module API under native Go and WebAssembly.
|
wasmcheck exercises the module API under native Go and WebAssembly. |