github.com/ianlewis/go-gitignore@v0.1.1-0.20231110021210-4a0f15cbd56f/token.go (about)

     1  // Copyright 2016 Denormal Limited
     2  // Copyright 2023 Google LLC
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //      http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  // Unless required by applicable law or agreed to in writing, software
    11  // distributed under the License is distributed on an "AS IS" BASIS,
    12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  
    16  package gitignore
    17  
    18  import (
    19  	"fmt"
    20  )
    21  
    22  // Token represents a parsed token from a .gitignore stream, encapsulating the
    23  // token type, the runes comprising the token, and the position within the
    24  // stream of the first rune of the token.
    25  type Token struct {
    26  	Type TokenType
    27  	Word []rune
    28  	Position
    29  }
    30  
    31  // NewToken returns a Token instance of the given t, represented by the
    32  // word runes, at the stream position pos. If the token type is not know, the
    33  // returned instance will have type BAD.
    34  func NewToken(t TokenType, word []rune, pos Position) *Token {
    35  	// ensure the type is valid
    36  	if t < ILLEGAL || t > BAD {
    37  		t = BAD
    38  	}
    39  
    40  	// return the token
    41  	return &Token{Type: t, Word: word, Position: pos}
    42  } // NewToken()
    43  
    44  // Name returns a string representation of the Token type.
    45  func (t *Token) Name() string {
    46  	return t.Type.String()
    47  } // Name()
    48  
    49  // Token returns the string representation of the Token word.
    50  func (t *Token) Token() string {
    51  	return string(t.Word)
    52  } // Token()
    53  
    54  // String returns a string representation of the Token, encapsulating its
    55  // position in the input stream, its name (i.e. type), and its runes.
    56  func (t *Token) String() string {
    57  	return fmt.Sprintf("%s: %s %q", t.Position.String(), t.Name(), t.Token())
    58  } // String()