Documentation
¶
Overview ¶
Package core contains configuration and utility internals.
Index ¶
- Constants
- Variables
- func AllStringsInSlice(strings []string, slice []string) bool
- func BlockMetrics(doc *summarize.Document, counts map[string]int) map[string]interface{}
- func CapFirst(s string) string
- func CheckName(styleRoot, rulePath string) (string, error)
- func CondSprintf(format string, v ...interface{}) string
- func DefaultConfig() (string, error)
- func DefaultStylesPath() (string, error)
- func FindAsset(cfg *Config, path string) string
- func FindConfigAsset(cfg *Config, name, dir string) string
- func FormatAlert(a *Alert, limit int, level, name string)
- func FormatFromExt(path string, mapping map[string]string) (string, string)
- func FormatMessage(msg string, subs ...string) string
- func FromFile(cfg *Config, dry bool) (*ini.File, error)
- func FromString(src string, cfg *Config, dry bool) (*ini.File, error)
- func GetNormedExt(ext string) string
- func GetPackages(src string) ([]string, error)
- func HasAnySuffix(s string, suffixes []string) bool
- func IgnoreFiles(stylesPath string) ([]string, error)
- func InRange(n int, r []int) bool
- func Indent(text, indent string) string
- func IntInSlice(a int, slice []int) bool
- func IsCode(s string) bool
- func IsLetter(s string) bool
- func IsPhrase(s string) bool
- func IsTestFile(name string) bool
- func MockLoad(project, local string, cfg *Config) error
- func NewE100(context string, err error) error
- func NewE201(msg, value, path string, finder errorCondition) error
- func NewE201FromKey(cfg *Config, key string, match func(value string) bool, msg string) error
- func NewE201FromPosition(msg, file string, goal int) error
- func NewE201FromTarget(msg, value, file string) error
- func NormalizePath(path string, mapping map[string]string) string
- func RelToWD(path string) string
- func ReplaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string
- func Sanitize(txt string) string
- func ShouldIgnoreDirectory(directoryPath string) bool
- func SplitLines(data []byte, atEOF bool) (adv int, token []byte, err error)
- func SplitSection(label string) (string, string)
- func StringInSlice(a string, slice []string) bool
- func StringsToInterface(strings []string) []interface{}
- func StripANSI(s string) string
- func StyleName(rule string) string
- func Substitute(src, sub string, char rune) (string, bool)
- func TextToContext(text string, meta *nlp.Info) []nlp.TaggedWord
- func ToSentence(words []string, andOrOr string) string
- func UniqueStrings(slice []string) []string
- func Warn(msg string)
- func WhitespaceToSpace(msg string) string
- type Action
- type Alert
- type ByName
- type ByPosition
- type CLIFlags
- type Cell
- type Condition
- type Config
- func (c *Config) AddConfigFile(name string)
- func (c *Config) AddStylesPath(path string)
- func (c *Config) AddWordListFile(name string, accept bool) error
- func (c *Config) Cached(key string, build func() any) any
- func (c *Config) ConfigFile() string
- func (c *Config) LoadScopes() error
- func (c *Config) Root() (string, error)
- func (c *Config) SearchPaths() []string
- func (c *Config) SectionApplies(sec string, held map[string]bool, names ...string) bool
- func (c *Config) SectionVocabs() []string
- func (c *Config) SphinxNames(key string) []string
- func (c *Config) String() string
- func (c *Config) StylesPath() string
- type ConfigSrc
- type DaselValue
- type Error
- type ExcerptLine
- type ExpandFunc
- type File
- func (f *File) AddAlert(a Alert, blk nlp.Block, lines, pad int, lookup bool)
- func (f *File) ComputeMetrics() (map[string]interface{}, error)
- func (f *File) DropDisabled()
- func (f *File) FindLoc(ctx, s string, pad, count int, a Alert, at int) (int, []int, int)
- func (f *File) Level(name, compiled string) string
- func (f *File) MapAlertsToSource()
- func (f *File) QueryComments(check string) bool
- func (f *File) RegionDisabled(check, match string, line, col int) bool
- func (f *File) ResetComments()
- func (f *File) RestoreText(s string)
- func (f *File) SetMetaScope(scope string)
- func (f *File) SetNormedExt(ext string)
- func (f *File) SetText(s string)
- func (f *File) SortedAlerts() []Alert
- func (f *File) StartBlock()
- func (f *File) Tokens(text string) []tag.Token
- func (f *File) TokensWith(model, text string) ([]tag.Token, error)
- func (f *File) UpdateComments(comment string)
- func (f *File) UpdateCommentsAt(comment string, off int)
- type FileFields
- type Part
- type Scope
- type ScopedValue
- type ScopedValues
- type View
- type Vocabulary
Constants ¶
const BuiltinAffix = "en_US-web"
BuiltinAffix names the affix file of Vale's built-in dictionary.
Variables ¶
var ( // ConfigDir is the default location for Vale's configuration files. // // This was introduced in v3.0.0 as a means of standardizing the location // of Vale's configuration files. // // This directory is relative to the user's specified `StylesPath`, which // can be set via the `--config` flag, the `VALE_CONFIG_PATH` environment // variable, or the default search process. // // NOTE: The config pipeline is stored in the top-level `.vale-config` // directory. See `cmd/vale/sync.go`. ConfigDir = "config" // PipeDir is the default location for Vale's configuration pipeline. PipeDir = ".vale-config" VocabDir = filepath.Join(ConfigDir, "vocabularies") DictDir = filepath.Join(ConfigDir, "dictionaries") TmplDir = filepath.Join(ConfigDir, "templates") IgnoreDir = filepath.Join(ConfigDir, "ignore") ActionDir = filepath.Join(ConfigDir, "actions") FilterDir = filepath.Join(ConfigDir, "filters") ScriptDir = filepath.Join(ConfigDir, "scripts") ViewDir = filepath.Join(ConfigDir, "views") ScopeDir = filepath.Join(ConfigDir, "scopes") )
var AlertLevels = []string{"suggestion", "warning", "error"}
AlertLevels holds the possible values for "level" in an external rule.
var CommentsByNormedExt = map[string]map[string]string{
".clj": {
"inline": `(;+.+)`,
"blockStart": `$^`,
"blockEnd": `$^`,
},
".ps1": {
"inline": `(#.+)`,
"blockStart": `(<#.*)`,
"blockEnd": `(.*#>)`,
},
}
CommentsByNormedExt determines what parts of a file we should lint -- e.g., we only want to lint ; comments in a Clojure file.
Deprecated: When possible, we now use tree-sitter grammars to determine the comment delimiters for a given file. See the `lint/code` package for more information.
Only Clojure (no bundled grammar uses `;` comments) and PowerShell (a stand-in grammar would lose `<# #>` block interiors) remain here.
var ConfigDirs = []string{ VocabDir, DictDir, TmplDir, IgnoreDir, ActionDir, ScriptDir, FilterDir, ViewDir, ScopeDir, }
ConfigDirs is a list of all directories that contain user-defined, non-style configuration files.
var ConfigVars = map[string]string{
"VALE_CONFIG_PATH": "Override the default search process by specifying a .vale.ini file.",
"VALE_STYLES_PATH": "Specify the location of the default StylesPath.",
}
ConfigVars is a list of all supported environment variables.
var FormatByExtension = map[string][]string{
`\.(?:[rc]?py[3w]?|[Ss][Cc]onstruct)$`: {".py", "code"},
`\.(?:adoc|asciidoc|asc)$`: {".adoc", "markup"},
`\.(?:clj|cljs|cljc|cljd)$`: {".clj", "code"},
`\.(?:cpp|cc|c|cp|cxx|c\+\+|h|hpp|h\+\+)$`: {".cpp", "code"},
`\.(?:css)$`: {".css", "code"},
`\.(?:cs|csx)$`: {".cs", "code"},
`\.(?:dita)$`: {".dita", "markup"},
`\.(?:ex|exs)$`: {".ex", "code"},
`\.(?:go)$`: {".go", "code"},
`\.(?:hs)$`: {".hs", "code"},
`\.(?:html|htm|shtml|xhtml)$`: {".html", "markup"},
`\.(?:ipynb)$`: {".ipynb", "markup"},
`\.(?:java|bsh)$`: {".java", "code"},
`\.(?:jl)$`: {".jl", "code"},
`\.(?:kt|kts)$`: {".kt", "code"},
`\.(?:js|jsx|mjs|cjs)$`: {".js", "code"},
`\.(?:lua)$`: {".lua", "code"},
`\.(?:md|mdown|markdown|markdn|[Rr]md)$`: {".md", "markup"},
`\.(?:mdx)$`: {".mdx", "markup"},
`\.(?:myst)$`: {".myst", "markup"},
`\.(?:qdoc|qdocinc)$`: {".qdoc", "markup"},
`\.(?:qmd)$`: {".qmd", "markup"},
`\.(?:qml)$`: {".qml", "code"},
`\.(?:org)$`: {".org", "markup"},
`\.(?:php)$`: {".php", "code"},
`\.(?:pl|pm|pod)$`: {".r", "code"},
`\.(?:proto)$`: {".proto", "code"},
`\.(?:ps1|psm1|psd1)$`: {".ps1", "code"},
`\.(?:rb|Gemfile|Rakefile|Brewfile|gemspec)$`: {".rb", "code"},
`\.(?:rs)$`: {".rs", "code"},
`\.(?:rst|rest)$`: {".rst", "markup"},
`\.(?:r|R)$`: {".r", "code"},
`\.(?:sass|scss|less)$`: {".c", "code"},
`\.(?:scala|sbt)$`: {".c", "code"},
`\.(?:swift)$`: {".c", "code"},
`\.(?:ts|tsx|mts|cts)$`: {".ts", "code"},
`\.(?:typ)$`: {".typ", "markup"},
`\.(?:txt)$`: {".txt", "text"},
`\.(?:xml|xsd)$`: {".xml", "markup"},
`\.(?:yaml|yml)$`: {".yml", "data"},
`\.(?:json)$`: {".json", "data"},
`\.(?:toml)$`: {".toml", "data"},
}
FormatByExtension associates a file extension with its "normed" extension and its format (markup, code or text).
var LevelToInt = map[string]int{
"suggestion": 0,
"warning": 1,
"error": 2,
}
LevelToInt allows us to easily compare levels in lint.go.
var TestFileSuffixes = []string{".test.yml", ".test.yaml"}
TestFileSuffixes name the YAML that holds a rule's test cases rather than a rule. `.yml` is the spelling Vale uses elsewhere and the one to document; `.yaml` is accepted so that a configuration written the other way still works.
A rule's cases live beside it, which puts them inside the StylesPath: the loader that has to skip them and the runner that has to find them must agree on which is which. See #1122.
Functions ¶
func AllStringsInSlice ¶
AllStringsInSlice determines if `slice` contains the `strings`.
func BlockMetrics ¶ added in v3.21.0
BlockMetrics computes the metrics of one block: doc's counts plus the elements it holds. Empty when the text has no words.
func CheckName ¶
StyleName returns the style a rule belongs to -- `proselint` for `proselint.Typography`.
A config may name either, so that a setting can be given once for a style and then overridden for a rule within it. CheckName derives a rule's name from where it sits under its style root: the directory's base, then each subdirectory, then the file's base, joined with dots. `Std/dates/TimeFormat.yml` is `Std.dates.TimeFormat` -- the tree is part of the name, so organizing a style never silently renames or drops a rule, and disabling one names the path you see on disk.
The file's base keeps its historical reading: everything before the first dot. `Terms.custom.yml` has always loaded as `Terms`.
func CondSprintf ¶
CondSprintf is sprintf, ignores extra arguments.
func DefaultConfig ¶
DefaultConfig returns the path to the default configuration file.
We don't create this file automatically because there's no actual notion of a "default" configuration -- it's just a file loation.
NOTE: if this file does not exist *and* the user has not specified a project-specific configuration file, Vale raises an error.
func DefaultStylesPath ¶
DefaultStylesPath returns the path to the default styles directory.
NOTE: the default styles directory is only used if neither the project-specific nor the global configuration file specify a `StylesPath`.
func FindAsset ¶
FindAsset tries to locate a Vale-related resource by looking in the user-defined StylesPath.
func FindConfigAsset ¶
FindConfigAsset tries to locate a Vale-related resource by looking in the user-defined StylesPath(s).
func FormatAlert ¶
FormatAlert ensures that all required fields have data.
func FormatFromExt ¶
FormatFromExt takes a file extension and returns its [normExt, format] list, if supported.
func FormatMessage ¶
FormatMessage inserts `subs` into `msg`.
func FromString ¶
FromString loads an INI configuration from a string.
func GetNormedExt ¶
func GetPackages ¶
Get the user-defined packages from a `.vale.ini` file.
func HasAnySuffix ¶
func IgnoreFiles ¶
IgnoreFiles returns a list of all user-defined ignore files.
func IntInSlice ¶
IntInSlice determines if `slice` contains the int `a`.
func IsPhrase ¶
IsPhrase returns `true` is s is a phrase-like token.
This is used to differentiate regex tokens from non-regex.
func IsTestFile ¶
IsTestFile reports whether a file name holds test cases rather than a rule.
func MockLoad ¶
MockLoad returns the would-be configuration after loading two files, one from the project and one from the user's local directory.
func NewE100 ¶
NewE100 creates an "unexpected" error, with a context that says where it came from. An error that is already Vale's own passes through unchanged, so it isn't shown as a banner inside another.
func NewE201 ¶
NewE201 creates an error about an invalid value in the file at path, placed at the first line finder accepts.
func NewE201FromKey ¶ added in v3.24.0
NewE201FromKey creates an E201 at the line of a configuration file that sets key to a value match accepts, searched across the files the run loaded. It falls back to an E100 when none of them does.
func NewE201FromPosition ¶
NewE201FromPosition creates an E201 at a given line.
func NewE201FromTarget ¶
NewE201FromTarget creates an E201 at the first line containing value.
func NormalizePath ¶ added in v3.22.0
NormalizePath returns path with the extension `[formats]` maps it to, so that a section matches the format a file is read as.
func RelToWD ¶ added in v3.25.0
RelToWD returns path relative to the working directory when it's inside it, so an error names a file as the user would.
func ShouldIgnoreDirectory ¶
ShouldIgnoreDirectory will check if directory should be ignored
func SplitLines ¶
SplitLines splits on CRLF, CR not followed by LF, and LF.
func SplitSection ¶ added in v3.24.0
SplitSection returns a section header's glob and condition, which is "" for a plain section.
func StringInSlice ¶
StringInSlice determines if `slice` contains the string `a`.
func StringsToInterface ¶
func StringsToInterface(strings []string) []interface{}
StringsToInterface converts a slice of strings to an interface.
func Substitute ¶
Substitute replaces the substring `sub` with a string of asterisks.
func TextToContext ¶
func TextToContext(text string, meta *nlp.Info) []nlp.TaggedWord
func ToSentence ¶
ToSentence converts a slice of terms into sentence.
func UniqueStrings ¶
UniqueStrings returns a new slice with all duplicate strings removed.
func Warn ¶
func Warn(msg string)
Warn reports something the user should know about but that doesn't stop the run -- a key we don't recognize, say.
It goes to stderr to stay clear of `--output=JSON` and the other formats a caller parses, which are written to stdout.
func WhitespaceToSpace ¶
WhitespaceToSpace converts newlines into a single space.
Types ¶
type Action ¶
type Action struct {
Name string // the name of the action -- e.g, 'replace'
Params []string // a slice of parameters for the given action
}
An Action represents a possible solution to an Alert.
type Alert ¶
type Alert struct {
Action Action // a possible solution
Suggestions []string // what Action resolves to, when known at lint time
Groups []string `json:",omitempty"` // the matched token's capture groups
Span []int // the [begin, end] location within a line
Offset []string `json:"-"` // tokens to ignore before this match
Check string // the name of the check
Description string // why `Message` is meaningful
Link string // reference material
Message string // the output message
Severity string // 'suggestion', 'warning', or 'error'
Match string // the actual matched text
Line int // the source line
Limit int `json:"-"` // the max times to report
Hide bool `json:"-"` // should we hide this alert?
HasByteOffsets bool `json:"-"` // Span holds byte offsets into the raw document
// contains filtered or unexported fields
}
An Alert represents a potential error in prose.
type ByPosition ¶
type ByPosition []Alert
ByPosition sorts Alerts by line and column.
func (ByPosition) Len ¶
func (a ByPosition) Len() int
func (ByPosition) Less ¶
func (a ByPosition) Less(i, j int) bool
func (ByPosition) Swap ¶
func (a ByPosition) Swap(i, j int)
type CLIFlags ¶
type CLIFlags struct {
AlertLevel string
Built string
Glob string
InExt string
InPath string
Output string
Path string
Sources string
Filter string
Apply bool
Counts bool
Coverage bool
Local bool
NoExit bool
NoColor bool
PlainProgress bool
Normalize bool
Relative bool
Remote bool
Simple bool
Sorted bool
Wrap bool
Version bool
Help bool
IgnoreGlobal bool
}
CLIFlags holds the values that are defined at runtime by the user.
For example, `vale --minAlertLevel=error`.
type Cell ¶ added in v3.21.0
type Cell struct {
// Type is `markdown`, `code`, or `raw`.
Type string
// Lang is the extension of the code's language, such as `.py`, and
// empty for a language Vale has no grammar for.
Lang string
Value ScopedValue
}
A Cell is one cell of a Jupyter notebook: what kind it is, the language of its code, and its source placed in the file.
func ParseNotebook ¶ added in v3.21.0
ParseNotebook reads a `.ipynb` into its cells, in order.
The current layout (nbformat 4) and the one before it (nbformat 3, with its worksheets and heading cells) are both read. A cell's source may be one string or a list of lines; either way the cell is one value, placed by each of its scalars.
type Condition ¶ added in v3.24.0
type Condition struct {
Source string
// contains filtered or unexported fields
}
A Condition is a section header's compiled `if` expression.
func NewCondition ¶ added in v3.24.0
NewCondition compiles a section's condition.
type Config ¶
type Config struct {
// General configuration
BlockIgnores map[string][]string // A list of blocks to ignore
Checks []string // All checks to load
Formats map[string]string // A map of unknown -> known formats
Asciidoctor map[string]string // A map of asciidoctor attributes
Sphinx map[string]string // The `[sphinx]` section: a project's directives and roles
FormatToLang map[string]string // A map of format to lang ID
GBaseStyles []string // Global base style
GChecks map[string]bool // Global checks
IgnoredClasses []string // A list of HTML classes to ignore
IgnoredScopes []string // A list of HTML tags to ignore
MinAlertLevel int // Lowest alert level to display
Vocab []string // The active project
RuleToLevel map[string]string // Single-rule level changes
RuleToParams map[string]map[string]string // Single-rule scalar overrides
SBaseStyles map[string][]string // Syntax-specific base styles
SChecks map[string]map[string]bool // Syntax-specific checks
SLevels map[string]map[string]string // Syntax-specific level changes
SUnsets map[string][]string // Keys a section marked UNSET
SVocab map[string][]string // Vocabularies a section names
StyleSources map[string]string // The file each section's BasedOnStyles comes from
Vocabularies map[string]*Vocabulary // Every vocabulary loaded, by name
SkippedScopes []string // A list of HTML blocks to ignore
Stylesheets map[string]string // XSLT stylesheet
TokenIgnores map[string][]string // A list of tokens to ignore
CommentDelimiters map[string][2]string // Strings to treat as comment delimiters. Indicates the start and end delimiters.
WordTemplate string // The template used in YAML -> regexp list conversions
RootINI string // the path to the project's .vale.ini file
RootDir string // the directory the search found RootINI at
Paths []string // A list of paths to search for styles
ConfigFiles []string // A list of configuration files to load
AcceptedTokens []string `json:"-"` // Project-specific vocabulary (okay)
RejectedTokens []string `json:"-"` // Project-specific vocabulary (avoid)
FallbackPath string `json:"-"`
SecToPat map[string]glob.Glob `json:"-"`
// SecToCond holds the condition of a section written `[glob if expr]`.
SecToCond map[string]*Condition `json:"-"`
Styles []string `json:"-"`
Views map[string]*View `json:"-"`
// Scopes are the named scopes found under `config/scopes`, by name.
Scopes map[string]string `json:"-"`
NLPEndpoint string // An external API to call for NLP-related work.
// Command-line configuration
Flags *CLIFlags `json:"-"`
StyleKeys []string `json:"-"`
RuleKeys []string `json:"-"`
// contains filtered or unexported fields
}
Config holds the configuration values from both the CLI and `.vale.ini`.
func ReadPipeline ¶
ReadPipeline loads Vale's configuration according to the local search process.
A `dry` run means that we can't expect the `StylesPath` to fully formed yet. For example, some assets may not have been downloaded yet via the `sync` command.
func (*Config) AddConfigFile ¶
AddConfigFile adds a new configuration file to the current list.
func (*Config) AddStylesPath ¶
AddStylesPath adds a new path to the current list.
func (*Config) AddWordListFile ¶
AddWordListFile adds vocab terms from a provided file.
func (*Config) Cached ¶ added in v3.22.0
Cached returns what build makes for key, building it once per config.
func (*Config) ConfigFile ¶
ConfigFile returns the last configuration file in the list.
The user's project-agnostic file is added first, so this is the project's own file when a run has one.
func (*Config) LoadScopes ¶ added in v3.23.0
LoadScopes reads every named scope on the search paths into c.Scopes.
A named scope is an entry in a YAML mapping under `config/scopes/`, from a name to a scope expression, and a rule uses the name where it would write the expression. Every file found is loaded: a package ships its names beside the rules that use them, and nothing in a configuration has to mention them.
func (*Config) Root ¶
Root returns the first configuration file in the list.
NOTE: loading records every config file we read -- including the default one -- so an empty list means that we found nothing to read.
func (*Config) SearchPaths ¶
func (*Config) SectionApplies ¶ added in v3.24.0
SectionApplies reports whether section sec applies to a file: its glob matches one of names, and its condition, if it has one, held for the file.
func (*Config) SectionVocabs ¶ added in v3.22.0
SectionVocabs names every vocabulary some section uses.
func (*Config) SphinxNames ¶ added in v3.23.0
SphinxNames returns one list from the `[sphinx]` section, lowercased.
func (*Config) StylesPath ¶
GetStylesPath returns the last path in the list.
This represents the user's project-specific styles directory -- i.e., the last one that was added.
type ConfigSrc ¶
type ConfigSrc int
ConfigSrc is a source of configuration values.
This could be a local file, a string, or a remote URL.
type DaselValue ¶
type DaselValue = any
DaselValue is the decoded document root passed to dasel. It may be a map (object root), a slice (array root, see #1017), or any other JSON/YAML/TOML value -- dasel navigates all of them.
type Error ¶ added in v3.24.0
type Error struct {
Code string // E100 or E201
// Context says where an E100 came from: a command, or the file being
// linted. An E201 has a position instead.
Context string
Path string // the file holding the invalid value
Line int // 1-based; 0 when the value couldn't be placed
Span int // 1-based column of the value
// Excerpt is the lines around Line, shown above the message.
Excerpt []ExcerptLine
Msg string
}
An Error is a failure of Vale itself rather than a finding in a document: E100 when something went wrong at runtime, E201 when a configuration file or rule holds an invalid value.
It keeps its parts apart and is formatted only when shown, so the JSON and line outputs read the fields instead of parsing a rendered message back.
type ExcerptLine ¶ added in v3.24.0
An ExcerptLine is one line of an Error's excerpt.
type ExpandFunc ¶ added in v3.25.0
ExpandFunc returns the forms a word's affix flags name.
func AffixExpander ¶ added in v3.25.0
func AffixExpander(cfg *Config, name string) (ExpandFunc, error)
AffixExpander returns the ExpandFunc for the affix file name, found as a spelling rule's dictionaries are: in each search path's dictionaries folder, then in $DICPATH. An empty name, or BuiltinAffix without a file of that name, is the built-in dictionary's.
type File ¶
type File struct {
NLP nlp.Info // -
Summary bytes.Buffer // holds content to be included in summarization checks
// SummaryRuns place the summary's text in Content: each piece of prose
// written to Summary records where it came from, so that a match found in
// the summary can be reported at the text that was counted. Without them
// the match is located by searching Content for its text, and a copy in
// front matter, a code block or a heading -- none of which the summary
// holds -- takes the alert. See #1191.
SummaryRuns []nlp.Run
Alerts []Alert // all alerts associated with this file
BaseStyles []string // base style assigned in .vale
Lines []string // the File's Content split into lines
Sequences []string // tracks various info (e.g., defined abbreviations)
Content string // the raw file contents
Format string // 'code', 'markup' or 'prose'
NormedExt string // the normalized extension (see util/format.go)
Path string // the full path
NormedPath string // the normalized path
Transform string // XLST transform
Held map[string]bool // the conditional sections whose `if` held
RealExt string // actual file extension
Checks map[string]bool // syntax-specific checks assigned in .vale
Unset map[string]bool // keys a section marked UNSET; no global setting applies
Vocab []string // vocabularies the file's sections name
ChkToCtx map[string]string // maps a temporary context to a particular check
// Levels holds the level each rule was given by the sections matching this
// file, which is not the same as the level it was compiled with: the same
// rule can be an error in one format and a warning in another. See #965.
Levels map[string]string
Comments map[string]bool // comment control statements
Metrics map[string]int // count-based metrics
Lookup bool // -
MetaScope string // extra scope context, e.g. a YAML key or comment
// Scoped holds the text of every value a View found, by scope name, so
// a rule can ask about a scope other than the one it runs in.
Scoped map[string][]string
// contains filtered or unexported fields
}
A File represents a linted text file.
func (*File) ComputeMetrics ¶
ComputeMetrics returns all of f's metrics.
func (*File) DropDisabled ¶ added in v3.22.0
func (f *File) DropDisabled()
DropDisabled removes the alerts that fall inside a comment region, for the regions recorded after those alerts were added.
func (*File) FindLoc ¶
FindLoc calculates the line and span of an Alert.
`at` is where `s` begins in `ctx`, or -1 when that is not known; it lets the match be placed without searching for it.
func (*File) Level ¶
Level returns the level `name` should report at in this file, falling back to the level it was compiled with.
A rule's own level covers it; a level set for its style covers the rest of that style, mirroring how the two are resolved at compile time.
func (*File) MapAlertsToSource ¶
func (f *File) MapAlertsToSource()
MapAlertsToSource shifts and widens alert spans to account for the sanitizer's `’` rewrite, so every span indexes the file's actual text rather than the sanitized copy that was linted. See #687.
func (*File) QueryComments ¶
QueryComments checks if there has been an in-text comment for this check.
func (*File) RegionDisabled ¶
RegionDisabled reports whether a comment directive covers check at the given location -- a 1-based line and column, as alerts carry them.
func (*File) ResetComments ¶
func (f *File) ResetComments()
ResetComments resets the state of all checks back to active.
func (*File) RestoreText ¶ added in v3.22.0
RestoreText puts the file's text back after values were linted in its place, keeping the alerts already reported from being reported again.
func (*File) SetMetaScope ¶
SetMetaScope sets an optional scope appended to each check's scope, giving it extra context. It lives on the file because files are linted concurrently.
func (*File) SetNormedExt ¶
SetNormedExt sets the normalized extension of a File.
func (*File) SortedAlerts ¶
SortedAlerts returns all of f's alerts sorted by line and column.
func (*File) StartBlock ¶
func (f *File) StartBlock()
StartBlock resets the per-block alert state: the masked contexts, and the counts of what was masked into them.
func (*File) Tokens ¶
Tokens returns the tagged tokens of text, tagging it only once per document however many rules ask for it.
func (*File) TokensWith ¶
TokensWith is Tokens, read with the named tagger.
Two models disagree about the same sentence -- that is why a rule names one -- so each is cached separately.
func (*File) UpdateComments ¶
UpdateComments sets a new status based on comment.
func (*File) UpdateCommentsAt ¶
UpdateCommentsAt sets a new status based on comment, which begins at byte offset `off` of the file's content, or -1 when its position isn't known.
The position is what lets a directive work inside a block. The toggles are read once per block, so a NO/YES pair inside one paragraph -- which is what a deep continuation indent makes of them, since an indent of four or more past the list's content column fails CommonMark's HTML-block test and leaves the comments inline -- has cancelled out by the time the paragraph is linted. The recorded region suppresses the located alerts instead.
type FileFields ¶ added in v3.24.0
type FileFields struct {
Path string // relative to the root .vale.ini, with forward slashes
Dir string
Name string
Ext string
Meta map[string]any // the front matter, keyed as written
}
FileFields are what a section's condition reads about a file, in the shape `--filter` reads a rule: capitalized, with a leading dot.
func NewFileFields ¶ added in v3.24.0
func NewFileFields(path, content string, meta bool, cfg *Config) FileFields
NewFileFields describes the file at path, holding content. Front matter is parsed only when meta is set, since most conditions never read it.
type Part ¶ added in v3.21.0
type Part struct {
Offset int // rune offset in the value
Line int
Column int
// Quote is the scalar's quote character, or 0 for a plain or block
// scalar. A quoted scalar decodes escapes, so a column in its text is
// not a column in the source.
Quote byte
// Raw is the source line from Column on; the walk through its escapes
// stops there, so a quoted scalar folded over several lines is placed
// by its first.
Raw string
}
A Part is the run of a value that came from one scalar: where it starts in the value and in the source, and the source text it was decoded from.
type Scope ¶
type Scope struct {
Name string `yaml:"name"`
Expr string `yaml:"expr"`
Type string `yaml:"type"`
// Join, when set, is the separator a selected list of strings is
// joined with, so the list reads as one value rather than one value
// per element. A notebook cell's source is such a list.
Join *string `yaml:"join"`
}
A Scope is a single query that we want to run against a document.
type ScopedValue ¶
type ScopedValue struct {
Text string
Line int
Column int
// Joined marks a value made from a list, so its own line breaks are
// real ones and not an escape in a scalar.
Joined bool
// Parts maps the value back to the scalars it was decoded from. It is
// empty when the parser gave no positions.
Parts []Part
}
A ScopedValue is a single value extracted from a scope, along with the source position it was parsed from. Line/Column are 1-based; both are 0 when the source format does not provide position information (e.g., TOML) or when the value could not be located in the parse tree.
type ScopedValues ¶
type ScopedValues struct {
Scope string
Format string
Values []ScopedValue
}
A ScopedValues is a value that has been assigned a scope.
func FrontMatterValues ¶ added in v3.22.0
func FrontMatterValues(fm string, srcLines []string) ([]ScopedValues, error)
FrontMatterValues returns each top-level string field of YAML or JSON front matter, in document order, as a value placed by its scalar and scoped `frontmatter.<key>`. fm is the front matter as the file holds it, from the file's first line, so its positions are the file's.
type View ¶
type View struct {
Engine string `yaml:"engine"`
Scopes []Scope `yaml:"scopes"`
// Template is the TextFSM template a `textfsm` view reads with. Each
// scope's `expr` names one of its values.
Template string `yaml:"template"`
// contains filtered or unexported fields
}
A View is a named, virtual representation of a subset of a file's structured content. It is defined by a set of queries that can be used to extract specific information from the file.
The supported engines are:
- `dasel`, which queries the parsed value of a data file;
- `tree-sitter`, which queries the syntax tree of a source file; and
- `textfsm`, which reads a plain-text file through a template -- a state machine of regular expressions -- and names what it captures.
type Vocabulary ¶ added in v3.22.0
A Vocabulary is what one `config/vocabularies` directory holds.