Movatterモバイル変換


[0]ホーム

URL:


internal

package
v1.23.2Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License:Apache-2.0Imports:13Imported by:0

Details

Repository

github.com/prometheus/client_golang

Links

Documentation

Overview

Copyright (c) 2015 Björn Rabenstein

Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.

The code in this package is copy/paste to avoid a dependency. Hence this filecarries the copyright of the original repo.https://github.com/beorn7/floats

Copyright 2022 The Prometheus AuthorsLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.

It provides tools to compare sequences of strings and generate textual diffs.

Maintaining `GetUnifiedDiffString` here because original repository(https://github.com/pmezard/go-difflib) is no longer maintained.

Index

Examples

Constants

This section is empty.

Variables

View Source
var GoCollectorDefaultRuntimeMetrics =regexp.MustCompile(`/gc/gogc:percent|/gc/gomemlimit:bytes|/sched/gomaxprocs:threads`)

Functions

funcAlmostEqualFloat64added inv1.14.0

func AlmostEqualFloat64(a, b, epsilonfloat64)bool

AlmostEqualFloat64 returns true if a and b are equal within a relative errorof epsilon. Seehttp://floating-point-gui.de/errors/comparison/ for thedetails of the applied method.

funcAlmostEqualFloat64sadded inv1.14.0

func AlmostEqualFloat64s(a, b []float64, epsilonfloat64)bool

AlmostEqualFloat64s is the slice form of AlmostEqualFloat64.

funcGetUnifiedDiffStringadded inv1.13.0

func GetUnifiedDiffString(diffUnifiedDiff) (string,error)

Like WriteUnifiedDiff but returns the diff a string.

Example
a := `onetwothreefourfmt.Printf("%s,%T",a,b)`b := `zeroonethreefour`diff := UnifiedDiff{A:        SplitLines(a),B:        SplitLines(b),FromFile: "Original",FromDate: "2005-01-26 23:30:50",ToFile:   "Current",ToDate:   "2010-04-02 10:20:52",Context:  3,}result, _ := GetUnifiedDiffString(diff)fmt.Println(strings.ReplaceAll(result, "\t", " "))
Output:--- Original 2005-01-26 23:30:50+++ Current 2010-04-02 10:20:52@@ -1,5 +1,4 @@+zero one-two three four-fmt.Printf("%s,%T",a,b)

funcNormalizeMetricFamilies

func NormalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily

NormalizeMetricFamilies returns a MetricFamily slice with emptyMetricFamilies pruned and the remaining MetricFamilies sorted by name withinthe slice, with the contained Metrics sorted within each MetricFamily.

funcRuntimeMetricsBucketsForUnitadded inv0.12.1

func RuntimeMetricsBucketsForUnit(buckets []float64, unitstring) []float64

RuntimeMetricsBucketsForUnit takes a set of buckets obtained for a runtime/metrics histogramtype (so, lower-bound inclusive) and a unit from a runtime/metrics name, and producesa reduced set of buckets. This function always removes any -Inf bucket as it's representedas the bottom-most upper-bound inclusive bucket in Prometheus.

funcRuntimeMetricsToPromadded inv0.12.1

func RuntimeMetricsToProm(d *metrics.Description) (string,string,string,bool)

RuntimeMetricsToProm produces a Prometheus metric name from a runtime/metricsmetric description and validates whether the metric is suitable for integrationwith Prometheus.

Returns false if a name could not be produced, or if Prometheus does not understandthe runtime/metrics Kind.

Note that the main reason a name couldn't be produced is if the runtime/metricspackage exports a name with characters outside the valid Prometheus metric namecharacter set. This is theoretically possible, but should never happen in practice.Still, don't rely on it.

funcSplitLinesadded inv1.13.0

func SplitLines(sstring) []string

Split a string on "\n" while preserving them. The output can be usedas input for UnifiedDiff and ContextDiff structures.

funcWriteUnifiedDiffadded inv1.13.0

func WriteUnifiedDiff(writerio.Writer, diffUnifiedDiff)error

Compare two sequences of lines; generate the delta as a unified diff.

Unified diffs are a compact way of showing line changes and a fewlines of context. The number of context lines is set by 'n' whichdefaults to three.

By default, the diff control lines (those with ---, +++, or @@) arecreated with a trailing newline. This is helpful so that inputscreated from file.readlines() result in diffs that are suitable forfile.writelines() since both the inputs and outputs have trailingnewlines.

For inputs that do not have trailing newlines, set the linetermargument to "" so that the output will be uniformly newline free.

The unidiff format normally has a header for filenames and modificationtimes. Any or all of these may be specified using strings for'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.The modification times are normally expressed in the ISO 8601 format.

Types

typeGoCollectorOptionsadded inv1.13.0

type GoCollectorOptions struct {DisableMemStatsLikeMetricsboolRuntimeMetricSumForHist    map[string]stringRuntimeMetricRules         []GoCollectorRule}

GoCollectorOptions should not be used be directly by anything, except `collectors` package.Use it via collectors package instead. See issuehttps://github.com/prometheus/client_golang/issues/1030.

This is internal, so external users only can use it via `collector.WithGoCollector*` methods

typeGoCollectorRuleadded inv1.13.0

type GoCollectorRule struct {Matcher *regexp.RegexpDenybool}

typeLabelPairSorteradded inv1.13.0

type LabelPairSorter []*dto.LabelPair

LabelPairSorter implements sort.Interface. It is used to sort a slice ofdto.LabelPair pointers.

func (LabelPairSorter)Lenadded inv1.13.0

func (sLabelPairSorter) Len()int

func (LabelPairSorter)Lessadded inv1.13.0

func (sLabelPairSorter) Less(i, jint)bool

func (LabelPairSorter)Swapadded inv1.13.0

func (sLabelPairSorter) Swap(i, jint)

typeMatchadded inv1.13.0

type Match struct {AintBintSizeint}

typeMetricSorteradded inv1.13.0

type MetricSorter []*dto.Metric

MetricSorter is a sortable slice of *dto.Metric.

func (MetricSorter)Lenadded inv1.13.0

func (sMetricSorter) Len()int

func (MetricSorter)Lessadded inv1.13.0

func (sMetricSorter) Less(i, jint)bool

func (MetricSorter)Swapadded inv1.13.0

func (sMetricSorter) Swap(i, jint)

typeOpCodeadded inv1.13.0

type OpCode struct {TagbyteI1intI2intJ1intJ2int}

typeSequenceMatcheradded inv1.13.0

type SequenceMatcher struct {IsJunk func(string)bool// contains filtered or unexported fields}

SequenceMatcher compares sequence of strings. The basicalgorithm predates, and is a little fancier than, an algorithmpublished in the late 1980's by Ratcliff and Obershelp under thehyperbolic name "gestalt pattern matching". The basic idea is to findthe longest contiguous matching subsequence that contains no "junk"elements (R-O doesn't address junk). The same idea is then appliedrecursively to the pieces of the sequences to the left and to the rightof the matching subsequence. This does not yield minimal editsequences, but does tend to yield matches that "look right" to people.

SequenceMatcher tries to compute a "human-friendly diff" between twosequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is thelongest *contiguous* & junk-free matching subsequence. That's whatcatches peoples' eyes. The Windows(tm) windiff has another interestingnotion, pairing up elements that appear uniquely in each sequence.That, and the method here, appear to yield more intuitive differencereports than does diff. This method appears to be the least vulnerableto synching up on blocks of "junk lines", though (like blank lines inordinary text files, or maybe "<P>" lines in HTML files). That may bebecause this is the only method of the 3 that has a *concept* of"junk" <wink>.

Timing: Basic R-O is cubic time worst case and quadratic time expectedcase. SequenceMatcher is quadratic time for the worst case and hasexpected-case behavior dependent in a complicated way on how manyelements the sequences have in common; best case time is linear.

funcNewMatcheradded inv1.13.0

func NewMatcher(a, b []string) *SequenceMatcher

funcNewMatcherWithJunkadded inv1.13.0

func NewMatcherWithJunk(a, b []string, autoJunkbool,isJunk func(string)bool,) *SequenceMatcher

func (*SequenceMatcher)GetGroupedOpCodesadded inv1.13.0

func (m *SequenceMatcher) GetGroupedOpCodes(nint) [][]OpCode

Isolate change clusters by eliminating ranges with no changes.

Return a generator of groups with up to n lines of context.Each group is in the same format as returned by GetOpCodes().

func (*SequenceMatcher)GetMatchingBlocksadded inv1.13.0

func (m *SequenceMatcher) GetMatchingBlocks() []Match

Return list of triples describing matching subsequences.

Each triple is of the form (i, j, n), and means thata[i:i+n] == b[j:j+n]. The triples are monotonically increasing ini and in j. It's also guaranteed that if (i, j, n) and (i', j', n') areadjacent triples in the list, and the second is not the last triple in thelist, then i+n != i' or j+n != j'. IOW, adjacent triples never describeadjacent equal blocks.

The last triple is a dummy, (len(a), len(b), 0), and is the onlytriple with n==0.

func (*SequenceMatcher)GetOpCodesadded inv1.13.0

func (m *SequenceMatcher) GetOpCodes() []OpCode

Return list of 5-tuples describing how to turn a into b.

Each tuple is of the form (tag, i1, i2, j1, j2). The first tuplehas i1 == j1 == 0, and remaining tuples have i1 == the i2 from thetuple preceding it, and likewise for j1 == the previous j2.

The tags are characters, with these meanings:

'r' (replace): a[i1:i2] should be replaced by b[j1:j2]

'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.

'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.

'e' (equal): a[i1:i2] == b[j1:j2]

func (*SequenceMatcher)QuickRatioadded inv1.13.0

func (m *SequenceMatcher) QuickRatio()float64

Return an upper bound on ratio() relatively quickly.

This isn't defined beyond that it is an upper bound on .Ratio(), andis faster to compute.

func (*SequenceMatcher)Ratioadded inv1.13.0

func (m *SequenceMatcher) Ratio()float64

Return a measure of the sequences' similarity (float in [0,1]).

Where T is the total number of elements in both sequences, andM is the number of matches, this is 2.0*M / T.Note that this is 1 if the sequences are identical, and 0 ifthey have nothing in common.

.Ratio() is expensive to compute if you haven't already computed.GetMatchingBlocks() or .GetOpCodes(), in which case you maywant to try .QuickRatio() or .RealQuickRation() first to get anupper bound.

func (*SequenceMatcher)RealQuickRatioadded inv1.13.0

func (m *SequenceMatcher) RealQuickRatio()float64

Return an upper bound on ratio() very quickly.

This isn't defined beyond that it is an upper bound on .Ratio(), andis faster to compute than either .Ratio() or .QuickRatio().

func (*SequenceMatcher)SetSeq1added inv1.13.0

func (m *SequenceMatcher) SetSeq1(a []string)

Set the first sequence to be compared. The second sequence to be compared isnot changed.

SequenceMatcher computes and caches detailed information about the secondsequence, so if you want to compare one sequence S against many sequences,use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the othersequences.

See also SetSeqs() and SetSeq2().

func (*SequenceMatcher)SetSeq2added inv1.13.0

func (m *SequenceMatcher) SetSeq2(b []string)

Set the second sequence to be compared. The first sequence to be compared isnot changed.

func (*SequenceMatcher)SetSeqsadded inv1.13.0

func (m *SequenceMatcher) SetSeqs(a, b []string)

Set two sequences to be compared.

typeUnifiedDiffadded inv1.13.0

type UnifiedDiff struct {A        []string// First sequence linesFromFilestring// First file nameFromDatestring// First file timeB        []string// Second sequence linesToFilestring// Second file nameToDatestring// Second file timeEolstring// Headers end of line, defaults to LFContextint// Number of context lines}

Unified diff parameters

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp