id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
16,800 | beego/mux | tree.go | BuildURL | func (n *Node) BuildURL(pairs ...string) (*url.URL, error) {
if len(pairs)%2 != 0 {
return nil, fmt.Errorf("pairs expect even number key/val, but get %d", len(pairs))
}
params := make(map[string]string)
var key string
for k, v := range pairs {
if k%2 == 0 {
key = v
} else {
params[key] = v
}
}
path, err := buildPath(strings.Split(n.pattern, "/"), params)
if err != nil {
return nil, err
}
return &url.URL{
Path: path,
}, nil
} | go | func (n *Node) BuildURL(pairs ...string) (*url.URL, error) {
if len(pairs)%2 != 0 {
return nil, fmt.Errorf("pairs expect even number key/val, but get %d", len(pairs))
}
params := make(map[string]string)
var key string
for k, v := range pairs {
if k%2 == 0 {
key = v
} else {
params[key] = v
}
}
path, err := buildPath(strings.Split(n.pattern, "/"), params)
if err != nil {
return nil, err
}
return &url.URL{
Path: path,
}, nil
} | [
"func",
"(",
"n",
"*",
"Node",
")",
"BuildURL",
"(",
"pairs",
"...",
"string",
")",
"(",
"*",
"url",
".",
"URL",
",",
"error",
")",
"{",
"if",
"len",
"(",
"pairs",
")",
"%",
"2",
"!=",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"("... | // BuildURL will builds a URL for the pattern. | [
"BuildURL",
"will",
"builds",
"a",
"URL",
"for",
"the",
"pattern",
"."
] | 6660b4b5accbb383fac89498e57d3250d5e907ac | https://github.com/beego/mux/blob/6660b4b5accbb383fac89498e57d3250d5e907ac/tree.go#L334-L354 |
16,801 | beego/mux | tree.go | parsePattern | func parsePattern(parent *Node, segments []string) *Node {
segment := segments[0]
segments = segments[1:]
child := parseSegment(parent, segment)
if len(segments) == 0 {
child.endpoint = true
return child
}
return parsePattern(child, segments)
} | go | func parsePattern(parent *Node, segments []string) *Node {
segment := segments[0]
segments = segments[1:]
child := parseSegment(parent, segment)
if len(segments) == 0 {
child.endpoint = true
return child
}
return parsePattern(child, segments)
} | [
"func",
"parsePattern",
"(",
"parent",
"*",
"Node",
",",
"segments",
"[",
"]",
"string",
")",
"*",
"Node",
"{",
"segment",
":=",
"segments",
"[",
"0",
"]",
"\n",
"segments",
"=",
"segments",
"[",
"1",
":",
"]",
"\n",
"child",
":=",
"parseSegment",
"(... | // parsePattern support multi pattern | [
"parsePattern",
"support",
"multi",
"pattern"
] | 6660b4b5accbb383fac89498e57d3250d5e907ac | https://github.com/beego/mux/blob/6660b4b5accbb383fac89498e57d3250d5e907ac/tree.go#L460-L469 |
16,802 | notnil/chess | game.go | PGN | func PGN(r io.Reader) (func(*Game), error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
game, err := decodePGN(string(b))
if err != nil {
return nil, err
}
return func(g *Game) {
g.copy(game)
}, nil
} | go | func PGN(r io.Reader) (func(*Game), error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
game, err := decodePGN(string(b))
if err != nil {
return nil, err
}
return func(g *Game) {
g.copy(game)
}, nil
} | [
"func",
"PGN",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"func",
"(",
"*",
"Game",
")",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
... | // PGN takes a reader and returns a function that updates
// the game to reflect the PGN data. The PGN can use any
// move notation supported by this package. The returned
// function is designed to be used in the NewGame constructor.
// An error is returned if there is a problem parsing the PGN data. | [
"PGN",
"takes",
"a",
"reader",
"and",
"returns",
"a",
"function",
"that",
"updates",
"the",
"game",
"to",
"reflect",
"the",
"PGN",
"data",
".",
"The",
"PGN",
"can",
"use",
"any",
"move",
"notation",
"supported",
"by",
"this",
"package",
".",
"The",
"retu... | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L87-L99 |
16,803 | notnil/chess | game.go | FEN | func FEN(fen string) (func(*Game), error) {
pos, err := decodeFEN(fen)
if err != nil {
return nil, err
}
return func(g *Game) {
g.pos = pos
g.positions = []*Position{pos}
g.updatePosition()
}, nil
} | go | func FEN(fen string) (func(*Game), error) {
pos, err := decodeFEN(fen)
if err != nil {
return nil, err
}
return func(g *Game) {
g.pos = pos
g.positions = []*Position{pos}
g.updatePosition()
}, nil
} | [
"func",
"FEN",
"(",
"fen",
"string",
")",
"(",
"func",
"(",
"*",
"Game",
")",
",",
"error",
")",
"{",
"pos",
",",
"err",
":=",
"decodeFEN",
"(",
"fen",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"r... | // FEN takes a string and returns a function that updates
// the game to reflect the FEN data. Since FEN doesn't encode
// prior moves, the move list will be empty. The returned
// function is designed to be used in the NewGame constructor.
// An error is returned if there is a problem parsing the FEN data. | [
"FEN",
"takes",
"a",
"string",
"and",
"returns",
"a",
"function",
"that",
"updates",
"the",
"game",
"to",
"reflect",
"the",
"FEN",
"data",
".",
"Since",
"FEN",
"doesn",
"t",
"encode",
"prior",
"moves",
"the",
"move",
"list",
"will",
"be",
"empty",
".",
... | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L106-L116 |
16,804 | notnil/chess | game.go | TagPairs | func TagPairs(tagPairs []*TagPair) func(*Game) {
return func(g *Game) {
g.tagPairs = append([]*TagPair(nil), tagPairs...)
}
} | go | func TagPairs(tagPairs []*TagPair) func(*Game) {
return func(g *Game) {
g.tagPairs = append([]*TagPair(nil), tagPairs...)
}
} | [
"func",
"TagPairs",
"(",
"tagPairs",
"[",
"]",
"*",
"TagPair",
")",
"func",
"(",
"*",
"Game",
")",
"{",
"return",
"func",
"(",
"g",
"*",
"Game",
")",
"{",
"g",
".",
"tagPairs",
"=",
"append",
"(",
"[",
"]",
"*",
"TagPair",
"(",
"nil",
")",
",",... | // TagPairs returns a function that sets the tag pairs
// to the given value. The returned function is designed
// to be used in the NewGame constructor. | [
"TagPairs",
"returns",
"a",
"function",
"that",
"sets",
"the",
"tag",
"pairs",
"to",
"the",
"given",
"value",
".",
"The",
"returned",
"function",
"is",
"designed",
"to",
"be",
"used",
"in",
"the",
"NewGame",
"constructor",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L121-L125 |
16,805 | notnil/chess | game.go | NewGame | func NewGame(options ...func(*Game)) *Game {
pos, _ := decodeFEN(startFEN)
game := &Game{
notation: AlgebraicNotation{},
moves: []*Move{},
pos: pos,
positions: []*Position{pos},
outcome: NoOutcome,
method: NoMethod,
}
for _, f := range options {
if f != nil {
f(game)
}
}
return game
} | go | func NewGame(options ...func(*Game)) *Game {
pos, _ := decodeFEN(startFEN)
game := &Game{
notation: AlgebraicNotation{},
moves: []*Move{},
pos: pos,
positions: []*Position{pos},
outcome: NoOutcome,
method: NoMethod,
}
for _, f := range options {
if f != nil {
f(game)
}
}
return game
} | [
"func",
"NewGame",
"(",
"options",
"...",
"func",
"(",
"*",
"Game",
")",
")",
"*",
"Game",
"{",
"pos",
",",
"_",
":=",
"decodeFEN",
"(",
"startFEN",
")",
"\n",
"game",
":=",
"&",
"Game",
"{",
"notation",
":",
"AlgebraicNotation",
"{",
"}",
",",
"mo... | // NewGame defaults to returning a game in the standard
// opening position. Options can be given to configure
// the game's initial state. | [
"NewGame",
"defaults",
"to",
"returning",
"a",
"game",
"in",
"the",
"standard",
"opening",
"position",
".",
"Options",
"can",
"be",
"given",
"to",
"configure",
"the",
"game",
"s",
"initial",
"state",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L141-L157 |
16,806 | notnil/chess | game.go | Move | func (g *Game) Move(m *Move) error {
valid := moveSlice(g.ValidMoves()).find(m)
if valid == nil {
return fmt.Errorf("chess: invalid move %s", m)
}
g.moves = append(g.moves, valid)
g.pos = g.pos.Update(valid)
g.positions = append(g.positions, g.pos)
g.updatePosition()
return nil
} | go | func (g *Game) Move(m *Move) error {
valid := moveSlice(g.ValidMoves()).find(m)
if valid == nil {
return fmt.Errorf("chess: invalid move %s", m)
}
g.moves = append(g.moves, valid)
g.pos = g.pos.Update(valid)
g.positions = append(g.positions, g.pos)
g.updatePosition()
return nil
} | [
"func",
"(",
"g",
"*",
"Game",
")",
"Move",
"(",
"m",
"*",
"Move",
")",
"error",
"{",
"valid",
":=",
"moveSlice",
"(",
"g",
".",
"ValidMoves",
"(",
")",
")",
".",
"find",
"(",
"m",
")",
"\n",
"if",
"valid",
"==",
"nil",
"{",
"return",
"fmt",
... | // Move updates the game with the given move. An error is returned
// if the move is invalid or the game has already been completed. | [
"Move",
"updates",
"the",
"game",
"with",
"the",
"given",
"move",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"move",
"is",
"invalid",
"or",
"the",
"game",
"has",
"already",
"been",
"completed",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L161-L171 |
16,807 | notnil/chess | game.go | MoveStr | func (g *Game) MoveStr(s string) error {
m, err := g.notation.Decode(g.pos, s)
if err != nil {
return err
}
return g.Move(m)
} | go | func (g *Game) MoveStr(s string) error {
m, err := g.notation.Decode(g.pos, s)
if err != nil {
return err
}
return g.Move(m)
} | [
"func",
"(",
"g",
"*",
"Game",
")",
"MoveStr",
"(",
"s",
"string",
")",
"error",
"{",
"m",
",",
"err",
":=",
"g",
".",
"notation",
".",
"Decode",
"(",
"g",
".",
"pos",
",",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",... | // MoveStr decodes the given string in game's notation
// and calls the Move function. An error is returned if
// the move can't be decoded or the move is invalid. | [
"MoveStr",
"decodes",
"the",
"given",
"string",
"in",
"game",
"s",
"notation",
"and",
"calls",
"the",
"Move",
"function",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"move",
"can",
"t",
"be",
"decoded",
"or",
"the",
"move",
"is",
"invalid",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L176-L182 |
16,808 | notnil/chess | game.go | MarshalText | func (g *Game) MarshalText() (text []byte, err error) {
return []byte(encodePGN(g)), nil
} | go | func (g *Game) MarshalText() (text []byte, err error) {
return []byte(encodePGN(g)), nil
} | [
"func",
"(",
"g",
"*",
"Game",
")",
"MarshalText",
"(",
")",
"(",
"text",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"return",
"[",
"]",
"byte",
"(",
"encodePGN",
"(",
"g",
")",
")",
",",
"nil",
"\n",
"}"
] | // MarshalText implements the encoding.TextMarshaler interface and
// encodes the game's PGN. | [
"MarshalText",
"implements",
"the",
"encoding",
".",
"TextMarshaler",
"interface",
"and",
"encodes",
"the",
"game",
"s",
"PGN",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L233-L235 |
16,809 | notnil/chess | game.go | UnmarshalText | func (g *Game) UnmarshalText(text []byte) error {
game, err := decodePGN(string(text))
if err != nil {
return err
}
g.copy(game)
return nil
} | go | func (g *Game) UnmarshalText(text []byte) error {
game, err := decodePGN(string(text))
if err != nil {
return err
}
g.copy(game)
return nil
} | [
"func",
"(",
"g",
"*",
"Game",
")",
"UnmarshalText",
"(",
"text",
"[",
"]",
"byte",
")",
"error",
"{",
"game",
",",
"err",
":=",
"decodePGN",
"(",
"string",
"(",
"text",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
... | // UnmarshalText implements the encoding.TextUnarshaler interface and
// assumes the data is in the PGN format. | [
"UnmarshalText",
"implements",
"the",
"encoding",
".",
"TextUnarshaler",
"interface",
"and",
"assumes",
"the",
"data",
"is",
"in",
"the",
"PGN",
"format",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L239-L246 |
16,810 | notnil/chess | game.go | Draw | func (g *Game) Draw(method Method) error {
switch method {
case ThreefoldRepetition:
if g.numOfRepitions() < 3 {
return errors.New("chess: draw by ThreefoldRepetition requires at least three repetitions of the current board state")
}
case FiftyMoveRule:
if g.pos.halfMoveClock < 100 {
return fmt.Errorf("chess: draw by FiftyMoveRule requires the half move clock to be at 100 or greater but is %d", g.pos.halfMoveClock)
}
case DrawOffer:
default:
return fmt.Errorf("chess: unsupported draw method %s", method.String())
}
g.outcome = Draw
g.method = method
return nil
} | go | func (g *Game) Draw(method Method) error {
switch method {
case ThreefoldRepetition:
if g.numOfRepitions() < 3 {
return errors.New("chess: draw by ThreefoldRepetition requires at least three repetitions of the current board state")
}
case FiftyMoveRule:
if g.pos.halfMoveClock < 100 {
return fmt.Errorf("chess: draw by FiftyMoveRule requires the half move clock to be at 100 or greater but is %d", g.pos.halfMoveClock)
}
case DrawOffer:
default:
return fmt.Errorf("chess: unsupported draw method %s", method.String())
}
g.outcome = Draw
g.method = method
return nil
} | [
"func",
"(",
"g",
"*",
"Game",
")",
"Draw",
"(",
"method",
"Method",
")",
"error",
"{",
"switch",
"method",
"{",
"case",
"ThreefoldRepetition",
":",
"if",
"g",
".",
"numOfRepitions",
"(",
")",
"<",
"3",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",... | // Draw attempts to draw the game by the given method. If the
// method is valid, then the game is updated to a draw by that
// method. If the method isn't valid then an error is returned. | [
"Draw",
"attempts",
"to",
"draw",
"the",
"game",
"by",
"the",
"given",
"method",
".",
"If",
"the",
"method",
"is",
"valid",
"then",
"the",
"game",
"is",
"updated",
"to",
"a",
"draw",
"by",
"that",
"method",
".",
"If",
"the",
"method",
"isn",
"t",
"va... | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L251-L268 |
16,811 | notnil/chess | game.go | Resign | func (g *Game) Resign(color Color) {
if g.outcome != NoOutcome || color == NoColor {
return
}
if color == White {
g.outcome = BlackWon
} else {
g.outcome = WhiteWon
}
g.method = Resignation
} | go | func (g *Game) Resign(color Color) {
if g.outcome != NoOutcome || color == NoColor {
return
}
if color == White {
g.outcome = BlackWon
} else {
g.outcome = WhiteWon
}
g.method = Resignation
} | [
"func",
"(",
"g",
"*",
"Game",
")",
"Resign",
"(",
"color",
"Color",
")",
"{",
"if",
"g",
".",
"outcome",
"!=",
"NoOutcome",
"||",
"color",
"==",
"NoColor",
"{",
"return",
"\n",
"}",
"\n",
"if",
"color",
"==",
"White",
"{",
"g",
".",
"outcome",
"... | // Resign resigns the game for the given color. If the game has
// already been completed then the game is not updated. | [
"Resign",
"resigns",
"the",
"game",
"for",
"the",
"given",
"color",
".",
"If",
"the",
"game",
"has",
"already",
"been",
"completed",
"then",
"the",
"game",
"is",
"not",
"updated",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L272-L282 |
16,812 | notnil/chess | game.go | AddTagPair | func (g *Game) AddTagPair(k, v string) bool {
for i, tag := range g.tagPairs {
if tag.Key == k {
g.tagPairs[i].Value = v
return true
}
}
g.tagPairs = append(g.tagPairs, &TagPair{Key: k, Value: v})
return false
} | go | func (g *Game) AddTagPair(k, v string) bool {
for i, tag := range g.tagPairs {
if tag.Key == k {
g.tagPairs[i].Value = v
return true
}
}
g.tagPairs = append(g.tagPairs, &TagPair{Key: k, Value: v})
return false
} | [
"func",
"(",
"g",
"*",
"Game",
")",
"AddTagPair",
"(",
"k",
",",
"v",
"string",
")",
"bool",
"{",
"for",
"i",
",",
"tag",
":=",
"range",
"g",
".",
"tagPairs",
"{",
"if",
"tag",
".",
"Key",
"==",
"k",
"{",
"g",
".",
"tagPairs",
"[",
"i",
"]",
... | // AddTagPair adds or updates a tag pair with the given key and
// value and returns true if the value is overwritten. | [
"AddTagPair",
"adds",
"or",
"updates",
"a",
"tag",
"pair",
"with",
"the",
"given",
"key",
"and",
"value",
"and",
"returns",
"true",
"if",
"the",
"value",
"is",
"overwritten",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L298-L307 |
16,813 | notnil/chess | game.go | GetTagPair | func (g *Game) GetTagPair(k string) *TagPair {
for _, tag := range g.tagPairs {
if tag.Key == k {
return tag
}
}
return nil
} | go | func (g *Game) GetTagPair(k string) *TagPair {
for _, tag := range g.tagPairs {
if tag.Key == k {
return tag
}
}
return nil
} | [
"func",
"(",
"g",
"*",
"Game",
")",
"GetTagPair",
"(",
"k",
"string",
")",
"*",
"TagPair",
"{",
"for",
"_",
",",
"tag",
":=",
"range",
"g",
".",
"tagPairs",
"{",
"if",
"tag",
".",
"Key",
"==",
"k",
"{",
"return",
"tag",
"\n",
"}",
"\n",
"}",
... | // GetTagPair returns the tag pair for the given key or nil
// if it is not present. | [
"GetTagPair",
"returns",
"the",
"tag",
"pair",
"for",
"the",
"given",
"key",
"or",
"nil",
"if",
"it",
"is",
"not",
"present",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L311-L318 |
16,814 | notnil/chess | game.go | RemoveTagPair | func (g *Game) RemoveTagPair(k string) bool {
cp := []*TagPair{}
found := false
for _, tag := range g.tagPairs {
if tag.Key == k {
found = true
} else {
cp = append(cp, tag)
}
}
g.tagPairs = cp
return found
} | go | func (g *Game) RemoveTagPair(k string) bool {
cp := []*TagPair{}
found := false
for _, tag := range g.tagPairs {
if tag.Key == k {
found = true
} else {
cp = append(cp, tag)
}
}
g.tagPairs = cp
return found
} | [
"func",
"(",
"g",
"*",
"Game",
")",
"RemoveTagPair",
"(",
"k",
"string",
")",
"bool",
"{",
"cp",
":=",
"[",
"]",
"*",
"TagPair",
"{",
"}",
"\n",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"tag",
":=",
"range",
"g",
".",
"tagPairs",
"{",
"if... | // RemoveTagPair removes the tag pair for the given key and
// returns true if a tag pair was removed. | [
"RemoveTagPair",
"removes",
"the",
"tag",
"pair",
"for",
"the",
"given",
"key",
"and",
"returns",
"true",
"if",
"a",
"tag",
"pair",
"was",
"removed",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/game.go#L322-L334 |
16,815 | notnil/chess | move.go | String | func (m *Move) String() string {
return m.s1.String() + m.s2.String() + m.promo.String()
} | go | func (m *Move) String() string {
return m.s1.String() + m.s2.String() + m.promo.String()
} | [
"func",
"(",
"m",
"*",
"Move",
")",
"String",
"(",
")",
"string",
"{",
"return",
"m",
".",
"s1",
".",
"String",
"(",
")",
"+",
"m",
".",
"s2",
".",
"String",
"(",
")",
"+",
"m",
".",
"promo",
".",
"String",
"(",
")",
"\n",
"}"
] | // String returns a string useful for debugging. String doesn't return
// algebraic notation. | [
"String",
"returns",
"a",
"string",
"useful",
"for",
"debugging",
".",
"String",
"doesn",
"t",
"return",
"algebraic",
"notation",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/move.go#L32-L34 |
16,816 | notnil/chess | board.go | SquareMap | func (b *Board) SquareMap() map[Square]Piece {
m := map[Square]Piece{}
for sq := 0; sq < numOfSquaresInBoard; sq++ {
p := b.Piece(Square(sq))
if p != NoPiece {
m[Square(sq)] = p
}
}
return m
} | go | func (b *Board) SquareMap() map[Square]Piece {
m := map[Square]Piece{}
for sq := 0; sq < numOfSquaresInBoard; sq++ {
p := b.Piece(Square(sq))
if p != NoPiece {
m[Square(sq)] = p
}
}
return m
} | [
"func",
"(",
"b",
"*",
"Board",
")",
"SquareMap",
"(",
")",
"map",
"[",
"Square",
"]",
"Piece",
"{",
"m",
":=",
"map",
"[",
"Square",
"]",
"Piece",
"{",
"}",
"\n",
"for",
"sq",
":=",
"0",
";",
"sq",
"<",
"numOfSquaresInBoard",
";",
"sq",
"++",
... | // SquareMap returns a mapping of squares to pieces. A square is only added to the map if it is occupied. | [
"SquareMap",
"returns",
"a",
"mapping",
"of",
"squares",
"to",
"pieces",
".",
"A",
"square",
"is",
"only",
"added",
"to",
"the",
"map",
"if",
"it",
"is",
"occupied",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/board.go#L33-L42 |
16,817 | notnil/chess | board.go | Draw | func (b *Board) Draw() string {
s := "\n A B C D E F G H\n"
for r := 7; r >= 0; r-- {
s += Rank(r).String()
for f := 0; f < numOfSquaresInRow; f++ {
p := b.Piece(getSquare(File(f), Rank(r)))
if p == NoPiece {
s += "-"
} else {
s += p.String()
}
s += " "
}
s += "\n"
}
return s
} | go | func (b *Board) Draw() string {
s := "\n A B C D E F G H\n"
for r := 7; r >= 0; r-- {
s += Rank(r).String()
for f := 0; f < numOfSquaresInRow; f++ {
p := b.Piece(getSquare(File(f), Rank(r)))
if p == NoPiece {
s += "-"
} else {
s += p.String()
}
s += " "
}
s += "\n"
}
return s
} | [
"func",
"(",
"b",
"*",
"Board",
")",
"Draw",
"(",
")",
"string",
"{",
"s",
":=",
"\"",
"\\n",
"\\n",
"\"",
"\n",
"for",
"r",
":=",
"7",
";",
"r",
">=",
"0",
";",
"r",
"--",
"{",
"s",
"+=",
"Rank",
"(",
"r",
")",
".",
"String",
"(",
")",
... | // Draw returns visual representation of the board useful for debugging. | [
"Draw",
"returns",
"visual",
"representation",
"of",
"the",
"board",
"useful",
"for",
"debugging",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/board.go#L45-L61 |
16,818 | notnil/chess | board.go | Piece | func (b *Board) Piece(sq Square) Piece {
for _, p := range allPieces {
bb := b.bbForPiece(p)
if bb.Occupied(sq) {
return p
}
}
return NoPiece
} | go | func (b *Board) Piece(sq Square) Piece {
for _, p := range allPieces {
bb := b.bbForPiece(p)
if bb.Occupied(sq) {
return p
}
}
return NoPiece
} | [
"func",
"(",
"b",
"*",
"Board",
")",
"Piece",
"(",
"sq",
"Square",
")",
"Piece",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"allPieces",
"{",
"bb",
":=",
"b",
".",
"bbForPiece",
"(",
"p",
")",
"\n",
"if",
"bb",
".",
"Occupied",
"(",
"sq",
")",
... | // Piece returns the piece for the given square. | [
"Piece",
"returns",
"the",
"piece",
"for",
"the",
"given",
"square",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/board.go#L90-L98 |
16,819 | notnil/chess | pgn.go | GamesFromPGN | func GamesFromPGN(r io.Reader) ([]*Game, error) {
games := []*Game{}
current := ""
count := 0
totalCount := 0
br := bufio.NewReader(r)
for {
line, err := br.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
if strings.TrimSpace(line) == "" {
count++
} else {
current += line
}
if count == 2 {
game, err := decodePGN(current)
if err != nil {
return nil, err
}
games = append(games, game)
count = 0
current = ""
totalCount++
log.Println("Processed game", totalCount)
}
}
return games, nil
} | go | func GamesFromPGN(r io.Reader) ([]*Game, error) {
games := []*Game{}
current := ""
count := 0
totalCount := 0
br := bufio.NewReader(r)
for {
line, err := br.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
if strings.TrimSpace(line) == "" {
count++
} else {
current += line
}
if count == 2 {
game, err := decodePGN(current)
if err != nil {
return nil, err
}
games = append(games, game)
count = 0
current = ""
totalCount++
log.Println("Processed game", totalCount)
}
}
return games, nil
} | [
"func",
"GamesFromPGN",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"[",
"]",
"*",
"Game",
",",
"error",
")",
"{",
"games",
":=",
"[",
"]",
"*",
"Game",
"{",
"}",
"\n",
"current",
":=",
"\"",
"\"",
"\n",
"count",
":=",
"0",
"\n",
"totalCount",
":=... | // GamesFromPGN returns all PGN decoding games from the
// reader. It is designed to be used decoding multiple PGNs
// in the same file. An error is returned if there is an
// issue parsing the PGNs. | [
"GamesFromPGN",
"returns",
"all",
"PGN",
"decoding",
"games",
"from",
"the",
"reader",
".",
"It",
"is",
"designed",
"to",
"be",
"used",
"decoding",
"multiple",
"PGNs",
"in",
"the",
"same",
"file",
".",
"An",
"error",
"is",
"returned",
"if",
"there",
"is",
... | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/pgn.go#L16-L47 |
16,820 | notnil/chess | piece.go | Other | func (c Color) Other() Color {
switch c {
case White:
return Black
case Black:
return White
}
return NoColor
} | go | func (c Color) Other() Color {
switch c {
case White:
return Black
case Black:
return White
}
return NoColor
} | [
"func",
"(",
"c",
"Color",
")",
"Other",
"(",
")",
"Color",
"{",
"switch",
"c",
"{",
"case",
"White",
":",
"return",
"Black",
"\n",
"case",
"Black",
":",
"return",
"White",
"\n",
"}",
"\n",
"return",
"NoColor",
"\n",
"}"
] | // Other returns the opposie color of the receiver. | [
"Other",
"returns",
"the",
"opposie",
"color",
"of",
"the",
"receiver",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/piece.go#L16-L24 |
16,821 | notnil/chess | piece.go | Type | func (p Piece) Type() PieceType {
switch p {
case WhiteKing, BlackKing:
return King
case WhiteQueen, BlackQueen:
return Queen
case WhiteRook, BlackRook:
return Rook
case WhiteBishop, BlackBishop:
return Bishop
case WhiteKnight, BlackKnight:
return Knight
case WhitePawn, BlackPawn:
return Pawn
}
return NoPieceType
} | go | func (p Piece) Type() PieceType {
switch p {
case WhiteKing, BlackKing:
return King
case WhiteQueen, BlackQueen:
return Queen
case WhiteRook, BlackRook:
return Rook
case WhiteBishop, BlackBishop:
return Bishop
case WhiteKnight, BlackKnight:
return Knight
case WhitePawn, BlackPawn:
return Pawn
}
return NoPieceType
} | [
"func",
"(",
"p",
"Piece",
")",
"Type",
"(",
")",
"PieceType",
"{",
"switch",
"p",
"{",
"case",
"WhiteKing",
",",
"BlackKing",
":",
"return",
"King",
"\n",
"case",
"WhiteQueen",
",",
"BlackQueen",
":",
"return",
"Queen",
"\n",
"case",
"WhiteRook",
",",
... | // Type returns the type of the piece. | [
"Type",
"returns",
"the",
"type",
"of",
"the",
"piece",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/piece.go#L147-L163 |
16,822 | notnil/chess | piece.go | Color | func (p Piece) Color() Color {
switch p {
case WhiteKing, WhiteQueen, WhiteRook, WhiteBishop, WhiteKnight, WhitePawn:
return White
case BlackKing, BlackQueen, BlackRook, BlackBishop, BlackKnight, BlackPawn:
return Black
}
return NoColor
} | go | func (p Piece) Color() Color {
switch p {
case WhiteKing, WhiteQueen, WhiteRook, WhiteBishop, WhiteKnight, WhitePawn:
return White
case BlackKing, BlackQueen, BlackRook, BlackBishop, BlackKnight, BlackPawn:
return Black
}
return NoColor
} | [
"func",
"(",
"p",
"Piece",
")",
"Color",
"(",
")",
"Color",
"{",
"switch",
"p",
"{",
"case",
"WhiteKing",
",",
"WhiteQueen",
",",
"WhiteRook",
",",
"WhiteBishop",
",",
"WhiteKnight",
",",
"WhitePawn",
":",
"return",
"White",
"\n",
"case",
"BlackKing",
",... | // Color returns the color of the piece. | [
"Color",
"returns",
"the",
"color",
"of",
"the",
"piece",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/piece.go#L166-L174 |
16,823 | notnil/chess | bitboard.go | Occupied | func (b bitboard) Occupied(sq Square) bool {
return (uint64(b) >> uint64(63-sq) & 1) == 1
} | go | func (b bitboard) Occupied(sq Square) bool {
return (uint64(b) >> uint64(63-sq) & 1) == 1
} | [
"func",
"(",
"b",
"bitboard",
")",
"Occupied",
"(",
"sq",
"Square",
")",
"bool",
"{",
"return",
"(",
"uint64",
"(",
"b",
")",
">>",
"uint64",
"(",
"63",
"-",
"sq",
")",
"&",
"1",
")",
"==",
"1",
"\n",
"}"
] | // Occupied returns true if the square's bitboard position is 1. | [
"Occupied",
"returns",
"true",
"if",
"the",
"square",
"s",
"bitboard",
"position",
"is",
"1",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/bitboard.go#L39-L41 |
16,824 | notnil/chess | bitboard.go | String | func (b bitboard) String() string {
s := strconv.FormatUint(uint64(b), 2)
return strings.Repeat("0", numOfSquaresInBoard-len(s)) + s
} | go | func (b bitboard) String() string {
s := strconv.FormatUint(uint64(b), 2)
return strings.Repeat("0", numOfSquaresInBoard-len(s)) + s
} | [
"func",
"(",
"b",
"bitboard",
")",
"String",
"(",
")",
"string",
"{",
"s",
":=",
"strconv",
".",
"FormatUint",
"(",
"uint64",
"(",
"b",
")",
",",
"2",
")",
"\n",
"return",
"strings",
".",
"Repeat",
"(",
"\"",
"\"",
",",
"numOfSquaresInBoard",
"-",
... | // String returns a 64 character string of 1s and 0s starting with the most significant bit. | [
"String",
"returns",
"a",
"64",
"character",
"string",
"of",
"1s",
"and",
"0s",
"starting",
"with",
"the",
"most",
"significant",
"bit",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/bitboard.go#L44-L47 |
16,825 | notnil/chess | bitboard.go | Draw | func (b bitboard) Draw() string {
s := "\n A B C D E F G H\n"
for r := 7; r >= 0; r-- {
s += Rank(r).String()
for f := 0; f < numOfSquaresInRow; f++ {
sq := getSquare(File(f), Rank(r))
if b.Occupied(sq) {
s += "1"
} else {
s += "0"
}
s += " "
}
s += "\n"
}
return s
} | go | func (b bitboard) Draw() string {
s := "\n A B C D E F G H\n"
for r := 7; r >= 0; r-- {
s += Rank(r).String()
for f := 0; f < numOfSquaresInRow; f++ {
sq := getSquare(File(f), Rank(r))
if b.Occupied(sq) {
s += "1"
} else {
s += "0"
}
s += " "
}
s += "\n"
}
return s
} | [
"func",
"(",
"b",
"bitboard",
")",
"Draw",
"(",
")",
"string",
"{",
"s",
":=",
"\"",
"\\n",
"\\n",
"\"",
"\n",
"for",
"r",
":=",
"7",
";",
"r",
">=",
"0",
";",
"r",
"--",
"{",
"s",
"+=",
"Rank",
"(",
"r",
")",
".",
"String",
"(",
")",
"\n... | // Draw returns visual representation of the bitboard useful for debugging. | [
"Draw",
"returns",
"visual",
"representation",
"of",
"the",
"bitboard",
"useful",
"for",
"debugging",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/bitboard.go#L82-L98 |
16,826 | notnil/chess | position.go | CanCastle | func (cr CastleRights) CanCastle(c Color, side Side) bool {
char := "k"
if side == QueenSide {
char = "q"
}
if c == White {
char = strings.ToUpper(char)
}
return strings.Contains(string(cr), char)
} | go | func (cr CastleRights) CanCastle(c Color, side Side) bool {
char := "k"
if side == QueenSide {
char = "q"
}
if c == White {
char = strings.ToUpper(char)
}
return strings.Contains(string(cr), char)
} | [
"func",
"(",
"cr",
"CastleRights",
")",
"CanCastle",
"(",
"c",
"Color",
",",
"side",
"Side",
")",
"bool",
"{",
"char",
":=",
"\"",
"\"",
"\n",
"if",
"side",
"==",
"QueenSide",
"{",
"char",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"c",
"==",
"White... | // CanCastle returns true if the given color and side combination
// can castle, otherwise returns false. | [
"CanCastle",
"returns",
"true",
"if",
"the",
"given",
"color",
"and",
"side",
"combination",
"can",
"castle",
"otherwise",
"returns",
"false",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/position.go#L25-L34 |
16,827 | notnil/chess | position.go | Update | func (pos *Position) Update(m *Move) *Position {
moveCount := pos.moveCount
if pos.turn == Black {
moveCount++
}
cr := pos.CastleRights()
ncr := pos.updateCastleRights(m)
p := pos.board.Piece(m.s1)
halfMove := pos.halfMoveClock
if p.Type() == Pawn || m.HasTag(Capture) || cr != ncr {
halfMove = 0
} else {
halfMove++
}
b := pos.board.copy()
b.update(m)
return &Position{
board: b,
turn: pos.turn.Other(),
castleRights: ncr,
enPassantSquare: pos.updateEnPassantSquare(m),
halfMoveClock: halfMove,
moveCount: moveCount,
inCheck: m.HasTag(Check),
}
} | go | func (pos *Position) Update(m *Move) *Position {
moveCount := pos.moveCount
if pos.turn == Black {
moveCount++
}
cr := pos.CastleRights()
ncr := pos.updateCastleRights(m)
p := pos.board.Piece(m.s1)
halfMove := pos.halfMoveClock
if p.Type() == Pawn || m.HasTag(Capture) || cr != ncr {
halfMove = 0
} else {
halfMove++
}
b := pos.board.copy()
b.update(m)
return &Position{
board: b,
turn: pos.turn.Other(),
castleRights: ncr,
enPassantSquare: pos.updateEnPassantSquare(m),
halfMoveClock: halfMove,
moveCount: moveCount,
inCheck: m.HasTag(Check),
}
} | [
"func",
"(",
"pos",
"*",
"Position",
")",
"Update",
"(",
"m",
"*",
"Move",
")",
"*",
"Position",
"{",
"moveCount",
":=",
"pos",
".",
"moveCount",
"\n",
"if",
"pos",
".",
"turn",
"==",
"Black",
"{",
"moveCount",
"++",
"\n",
"}",
"\n",
"cr",
":=",
... | // Update returns a new position resulting from the given move.
// The move itself isn't validated, if validation is needed use
// Game's Move method. This method is more performant for bots that
// rely on the ValidMoves because it skips redundant validation. | [
"Update",
"returns",
"a",
"new",
"position",
"resulting",
"from",
"the",
"given",
"move",
".",
"The",
"move",
"itself",
"isn",
"t",
"validated",
"if",
"validation",
"is",
"needed",
"use",
"Game",
"s",
"Move",
"method",
".",
"This",
"method",
"is",
"more",
... | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/position.go#L59-L84 |
16,828 | notnil/chess | position.go | ValidMoves | func (pos *Position) ValidMoves() []*Move {
if pos.validMoves != nil {
return append([]*Move(nil), pos.validMoves...)
}
pos.validMoves = engine{}.CalcMoves(pos, false)
return append([]*Move(nil), pos.validMoves...)
} | go | func (pos *Position) ValidMoves() []*Move {
if pos.validMoves != nil {
return append([]*Move(nil), pos.validMoves...)
}
pos.validMoves = engine{}.CalcMoves(pos, false)
return append([]*Move(nil), pos.validMoves...)
} | [
"func",
"(",
"pos",
"*",
"Position",
")",
"ValidMoves",
"(",
")",
"[",
"]",
"*",
"Move",
"{",
"if",
"pos",
".",
"validMoves",
"!=",
"nil",
"{",
"return",
"append",
"(",
"[",
"]",
"*",
"Move",
"(",
"nil",
")",
",",
"pos",
".",
"validMoves",
"...",... | // ValidMoves returns a list of valid moves for the position. | [
"ValidMoves",
"returns",
"a",
"list",
"of",
"valid",
"moves",
"for",
"the",
"position",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/position.go#L87-L93 |
16,829 | notnil/chess | position.go | Hash | func (pos *Position) Hash() [16]byte {
sq := "-"
if pos.enPassantSquare != NoSquare {
sq = pos.enPassantSquare.String()
}
s := pos.turn.String() + ":" + pos.castleRights.String() + ":" + sq
for _, p := range allPieces {
bb := pos.board.bbForPiece(p)
s += ":" + strconv.FormatUint(uint64(bb), 16)
}
return md5.Sum([]byte(s))
} | go | func (pos *Position) Hash() [16]byte {
sq := "-"
if pos.enPassantSquare != NoSquare {
sq = pos.enPassantSquare.String()
}
s := pos.turn.String() + ":" + pos.castleRights.String() + ":" + sq
for _, p := range allPieces {
bb := pos.board.bbForPiece(p)
s += ":" + strconv.FormatUint(uint64(bb), 16)
}
return md5.Sum([]byte(s))
} | [
"func",
"(",
"pos",
"*",
"Position",
")",
"Hash",
"(",
")",
"[",
"16",
"]",
"byte",
"{",
"sq",
":=",
"\"",
"\"",
"\n",
"if",
"pos",
".",
"enPassantSquare",
"!=",
"NoSquare",
"{",
"sq",
"=",
"pos",
".",
"enPassantSquare",
".",
"String",
"(",
")",
... | // Hash returns a unique hash of the position | [
"Hash",
"returns",
"a",
"unique",
"hash",
"of",
"the",
"position"
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/position.go#L130-L141 |
16,830 | notnil/chess | position.go | MarshalText | func (pos *Position) MarshalText() (text []byte, err error) {
return []byte(pos.String()), nil
} | go | func (pos *Position) MarshalText() (text []byte, err error) {
return []byte(pos.String()), nil
} | [
"func",
"(",
"pos",
"*",
"Position",
")",
"MarshalText",
"(",
")",
"(",
"text",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"return",
"[",
"]",
"byte",
"(",
"pos",
".",
"String",
"(",
")",
")",
",",
"nil",
"\n",
"}"
] | // MarshalText implements the encoding.TextMarshaler interface and
// encodes the position's FEN. | [
"MarshalText",
"implements",
"the",
"encoding",
".",
"TextMarshaler",
"interface",
"and",
"encodes",
"the",
"position",
"s",
"FEN",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/position.go#L145-L147 |
16,831 | notnil/chess | position.go | UnmarshalText | func (pos *Position) UnmarshalText(text []byte) error {
cp, err := decodeFEN(string(text))
if err != nil {
return err
}
pos.board = cp.board
pos.turn = cp.turn
pos.castleRights = cp.castleRights
pos.enPassantSquare = cp.enPassantSquare
pos.halfMoveClock = cp.halfMoveClock
pos.moveCount = cp.moveCount
pos.inCheck = isInCheck(cp)
return nil
} | go | func (pos *Position) UnmarshalText(text []byte) error {
cp, err := decodeFEN(string(text))
if err != nil {
return err
}
pos.board = cp.board
pos.turn = cp.turn
pos.castleRights = cp.castleRights
pos.enPassantSquare = cp.enPassantSquare
pos.halfMoveClock = cp.halfMoveClock
pos.moveCount = cp.moveCount
pos.inCheck = isInCheck(cp)
return nil
} | [
"func",
"(",
"pos",
"*",
"Position",
")",
"UnmarshalText",
"(",
"text",
"[",
"]",
"byte",
")",
"error",
"{",
"cp",
",",
"err",
":=",
"decodeFEN",
"(",
"string",
"(",
"text",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}... | // UnmarshalText implements the encoding.TextUnarshaler interface and
// assumes the data is in the FEN format. | [
"UnmarshalText",
"implements",
"the",
"encoding",
".",
"TextUnarshaler",
"interface",
"and",
"assumes",
"the",
"data",
"is",
"in",
"the",
"FEN",
"format",
"."
] | 2ad5c7f990b6eb99cfd6a5d3187c899c75053b89 | https://github.com/notnil/chess/blob/2ad5c7f990b6eb99cfd6a5d3187c899c75053b89/position.go#L151-L164 |
16,832 | vulcand/predicate | lib.go | GetFieldByTag | func GetFieldByTag(ival interface{}, tagName string, fieldNames []string) (interface{}, error) {
if len(fieldNames) == 0 {
return nil, trace.BadParameter("missing field names")
}
val := reflect.ValueOf(ival)
if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr {
val = val.Elem()
}
if val.Kind() != reflect.Struct {
return nil, trace.NotFound("field name %v is not found", strings.Join(fieldNames, "."))
}
fieldName := fieldNames[0]
rest := fieldNames[1:]
valType := val.Type()
for i := 0; i < valType.NumField(); i++ {
tagValue := valType.Field(i).Tag.Get(tagName)
parts := strings.Split(tagValue, ",")
if parts[0] == fieldName {
value := val.Field(i).Interface()
if len(rest) == 0 {
return value, nil
}
return GetFieldByTag(value, tagName, rest)
}
}
return nil, trace.NotFound("field name %v is not found", strings.Join(fieldNames, "."))
} | go | func GetFieldByTag(ival interface{}, tagName string, fieldNames []string) (interface{}, error) {
if len(fieldNames) == 0 {
return nil, trace.BadParameter("missing field names")
}
val := reflect.ValueOf(ival)
if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr {
val = val.Elem()
}
if val.Kind() != reflect.Struct {
return nil, trace.NotFound("field name %v is not found", strings.Join(fieldNames, "."))
}
fieldName := fieldNames[0]
rest := fieldNames[1:]
valType := val.Type()
for i := 0; i < valType.NumField(); i++ {
tagValue := valType.Field(i).Tag.Get(tagName)
parts := strings.Split(tagValue, ",")
if parts[0] == fieldName {
value := val.Field(i).Interface()
if len(rest) == 0 {
return value, nil
}
return GetFieldByTag(value, tagName, rest)
}
}
return nil, trace.NotFound("field name %v is not found", strings.Join(fieldNames, "."))
} | [
"func",
"GetFieldByTag",
"(",
"ival",
"interface",
"{",
"}",
",",
"tagName",
"string",
",",
"fieldNames",
"[",
"]",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"len",
"(",
"fieldNames",
")",
"==",
"0",
"{",
"return",
"nil... | // GetFieldByTag returns a field from the object based on the tag | [
"GetFieldByTag",
"returns",
"a",
"field",
"from",
"the",
"object",
"based",
"on",
"the",
"tag"
] | 8fbfb3ab0e94276b6b58bec378600829adc7a203 | https://github.com/vulcand/predicate/blob/8fbfb3ab0e94276b6b58bec378600829adc7a203/lib.go#L131-L158 |
16,833 | vulcand/predicate | builder/builder.go | Equals | func Equals(left, right Expr) EqualsExpr {
return EqualsExpr{Left: left, Right: right}
} | go | func Equals(left, right Expr) EqualsExpr {
return EqualsExpr{Left: left, Right: right}
} | [
"func",
"Equals",
"(",
"left",
",",
"right",
"Expr",
")",
"EqualsExpr",
"{",
"return",
"EqualsExpr",
"{",
"Left",
":",
"left",
",",
"Right",
":",
"right",
"}",
"\n",
"}"
] | // Equals returns equals expression | [
"Equals",
"returns",
"equals",
"expression"
] | 8fbfb3ab0e94276b6b58bec378600829adc7a203 | https://github.com/vulcand/predicate/blob/8fbfb3ab0e94276b6b58bec378600829adc7a203/builder/builder.go#L72-L74 |
16,834 | vulcand/predicate | builder/builder.go | String | func (i EqualsExpr) String() string {
return fmt.Sprintf("equals(%v, %v)", i.Left, i.Right)
} | go | func (i EqualsExpr) String() string {
return fmt.Sprintf("equals(%v, %v)", i.Left, i.Right)
} | [
"func",
"(",
"i",
"EqualsExpr",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
".",
"Left",
",",
"i",
".",
"Right",
")",
"\n",
"}"
] | // String returns function call expression used in rules | [
"String",
"returns",
"function",
"call",
"expression",
"used",
"in",
"rules"
] | 8fbfb3ab0e94276b6b58bec378600829adc7a203 | https://github.com/vulcand/predicate/blob/8fbfb3ab0e94276b6b58bec378600829adc7a203/builder/builder.go#L87-L89 |
16,835 | vulcand/predicate | builder/builder.go | Contains | func Contains(a, b Expr) ContainsExpr {
return ContainsExpr{Left: a, Right: b}
} | go | func Contains(a, b Expr) ContainsExpr {
return ContainsExpr{Left: a, Right: b}
} | [
"func",
"Contains",
"(",
"a",
",",
"b",
"Expr",
")",
"ContainsExpr",
"{",
"return",
"ContainsExpr",
"{",
"Left",
":",
"a",
",",
"Right",
":",
"b",
"}",
"\n",
"}"
] | // Contains returns contains function call expression | [
"Contains",
"returns",
"contains",
"function",
"call",
"expression"
] | 8fbfb3ab0e94276b6b58bec378600829adc7a203 | https://github.com/vulcand/predicate/blob/8fbfb3ab0e94276b6b58bec378600829adc7a203/builder/builder.go#L110-L112 |
16,836 | vulcand/predicate | builder/builder.go | String | func (i ContainsExpr) String() string {
return fmt.Sprintf("contains(%v, %v)", i.Left, i.Right)
} | go | func (i ContainsExpr) String() string {
return fmt.Sprintf("contains(%v, %v)", i.Left, i.Right)
} | [
"func",
"(",
"i",
"ContainsExpr",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
".",
"Left",
",",
"i",
".",
"Right",
")",
"\n",
"}"
] | // String rturns function call expression used in rules | [
"String",
"rturns",
"function",
"call",
"expression",
"used",
"in",
"rules"
] | 8fbfb3ab0e94276b6b58bec378600829adc7a203 | https://github.com/vulcand/predicate/blob/8fbfb3ab0e94276b6b58bec378600829adc7a203/builder/builder.go#L125-L127 |
16,837 | vulcand/predicate | builder/builder.go | And | func And(left, right Expr) AndExpr {
return AndExpr{
Left: left,
Right: right,
}
} | go | func And(left, right Expr) AndExpr {
return AndExpr{
Left: left,
Right: right,
}
} | [
"func",
"And",
"(",
"left",
",",
"right",
"Expr",
")",
"AndExpr",
"{",
"return",
"AndExpr",
"{",
"Left",
":",
"left",
",",
"Right",
":",
"right",
",",
"}",
"\n",
"}"
] | // And returns && expression | [
"And",
"returns",
"&&",
"expression"
] | 8fbfb3ab0e94276b6b58bec378600829adc7a203 | https://github.com/vulcand/predicate/blob/8fbfb3ab0e94276b6b58bec378600829adc7a203/builder/builder.go#L130-L135 |
16,838 | vulcand/predicate | builder/builder.go | Or | func Or(left, right Expr) OrExpr {
return OrExpr{
Left: left,
Right: right,
}
} | go | func Or(left, right Expr) OrExpr {
return OrExpr{
Left: left,
Right: right,
}
} | [
"func",
"Or",
"(",
"left",
",",
"right",
"Expr",
")",
"OrExpr",
"{",
"return",
"OrExpr",
"{",
"Left",
":",
"left",
",",
"Right",
":",
"right",
",",
"}",
"\n",
"}"
] | // Or returns || expression | [
"Or",
"returns",
"||",
"expression"
] | 8fbfb3ab0e94276b6b58bec378600829adc7a203 | https://github.com/vulcand/predicate/blob/8fbfb3ab0e94276b6b58bec378600829adc7a203/builder/builder.go#L151-L156 |
16,839 | vulcand/predicate | parse.go | evaluateSelector | func evaluateSelector(sel *ast.SelectorExpr, fields []string) ([]string, error) {
fields = append([]string{sel.Sel.Name}, fields...)
switch l := sel.X.(type) {
case *ast.SelectorExpr:
return evaluateSelector(l, fields)
case *ast.Ident:
fields = append([]string{l.Name}, fields...)
return fields, nil
default:
return nil, trace.BadParameter("unsupported selector type: %T", l)
}
} | go | func evaluateSelector(sel *ast.SelectorExpr, fields []string) ([]string, error) {
fields = append([]string{sel.Sel.Name}, fields...)
switch l := sel.X.(type) {
case *ast.SelectorExpr:
return evaluateSelector(l, fields)
case *ast.Ident:
fields = append([]string{l.Name}, fields...)
return fields, nil
default:
return nil, trace.BadParameter("unsupported selector type: %T", l)
}
} | [
"func",
"evaluateSelector",
"(",
"sel",
"*",
"ast",
".",
"SelectorExpr",
",",
"fields",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"fields",
"=",
"append",
"(",
"[",
"]",
"string",
"{",
"sel",
".",
"Sel",
".",
"Name",... | // evaluateSelector recursively evaluates the selector field and returns a list
// of properties at the end | [
"evaluateSelector",
"recursively",
"evaluates",
"the",
"selector",
"field",
"and",
"returns",
"a",
"list",
"of",
"properties",
"at",
"the",
"end"
] | 8fbfb3ab0e94276b6b58bec378600829adc7a203 | https://github.com/vulcand/predicate/blob/8fbfb3ab0e94276b6b58bec378600829adc7a203/parse.go#L156-L167 |
16,840 | Unknwon/cae | zip/write.go | packFile | func packFile(srcFile string, recPath string, zw *zip.Writer, fi os.FileInfo) error {
if fi.IsDir() {
fh, err := zip.FileInfoHeader(fi)
if err != nil {
return err
}
fh.Name = recPath + "/"
if _, err = zw.CreateHeader(fh); err != nil {
return err
}
} else {
fh, err := zip.FileInfoHeader(fi)
if err != nil {
return err
}
fh.Name = recPath
fh.Method = zip.Deflate
fw, err := zw.CreateHeader(fh)
if err != nil {
return err
}
if fi.Mode()&os.ModeSymlink != 0 {
target, err := os.Readlink(srcFile)
if err != nil {
return err
}
if _, err = fw.Write([]byte(target)); err != nil {
return err
}
} else {
f, err := os.Open(srcFile)
if err != nil {
return err
}
defer f.Close()
if _, err = io.Copy(fw, f); err != nil {
return err
}
}
}
return nil
} | go | func packFile(srcFile string, recPath string, zw *zip.Writer, fi os.FileInfo) error {
if fi.IsDir() {
fh, err := zip.FileInfoHeader(fi)
if err != nil {
return err
}
fh.Name = recPath + "/"
if _, err = zw.CreateHeader(fh); err != nil {
return err
}
} else {
fh, err := zip.FileInfoHeader(fi)
if err != nil {
return err
}
fh.Name = recPath
fh.Method = zip.Deflate
fw, err := zw.CreateHeader(fh)
if err != nil {
return err
}
if fi.Mode()&os.ModeSymlink != 0 {
target, err := os.Readlink(srcFile)
if err != nil {
return err
}
if _, err = fw.Write([]byte(target)); err != nil {
return err
}
} else {
f, err := os.Open(srcFile)
if err != nil {
return err
}
defer f.Close()
if _, err = io.Copy(fw, f); err != nil {
return err
}
}
}
return nil
} | [
"func",
"packFile",
"(",
"srcFile",
"string",
",",
"recPath",
"string",
",",
"zw",
"*",
"zip",
".",
"Writer",
",",
"fi",
"os",
".",
"FileInfo",
")",
"error",
"{",
"if",
"fi",
".",
"IsDir",
"(",
")",
"{",
"fh",
",",
"err",
":=",
"zip",
".",
"FileI... | // packFile packs a file or directory to zip.Writer. | [
"packFile",
"packs",
"a",
"file",
"or",
"directory",
"to",
"zip",
".",
"Writer",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/zip/write.go#L197-L241 |
16,841 | Unknwon/cae | tz/stream.go | NewStreamArachive | func NewStreamArachive(w io.Writer) *StreamArchive {
s := &StreamArchive{}
s.gw = gzip.NewWriter(w)
s.Writer = tar.NewWriter(s.gw)
return s
} | go | func NewStreamArachive(w io.Writer) *StreamArchive {
s := &StreamArchive{}
s.gw = gzip.NewWriter(w)
s.Writer = tar.NewWriter(s.gw)
return s
} | [
"func",
"NewStreamArachive",
"(",
"w",
"io",
".",
"Writer",
")",
"*",
"StreamArchive",
"{",
"s",
":=",
"&",
"StreamArchive",
"{",
"}",
"\n",
"s",
".",
"gw",
"=",
"gzip",
".",
"NewWriter",
"(",
"w",
")",
"\n",
"s",
".",
"Writer",
"=",
"tar",
".",
... | // NewStreamArachive returns a new streamable archive with given io.Writer.
// It's caller's responsibility to close io.Writer and streamer after operation. | [
"NewStreamArachive",
"returns",
"a",
"new",
"streamable",
"archive",
"with",
"given",
"io",
".",
"Writer",
".",
"It",
"s",
"caller",
"s",
"responsibility",
"to",
"close",
"io",
".",
"Writer",
"and",
"streamer",
"after",
"operation",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/stream.go#L40-L45 |
16,842 | Unknwon/cae | tz/stream.go | StreamReader | func (s *StreamArchive) StreamReader(relPath string, fi os.FileInfo, r io.Reader) (err error) {
fh, err := tar.FileInfoHeader(fi, "")
if err != nil {
return err
}
fh.Name = filepath.Join(relPath, fi.Name())
if err = s.Writer.WriteHeader(fh); err != nil {
return err
}
_, err = io.Copy(s.Writer, r)
return err
} | go | func (s *StreamArchive) StreamReader(relPath string, fi os.FileInfo, r io.Reader) (err error) {
fh, err := tar.FileInfoHeader(fi, "")
if err != nil {
return err
}
fh.Name = filepath.Join(relPath, fi.Name())
if err = s.Writer.WriteHeader(fh); err != nil {
return err
}
_, err = io.Copy(s.Writer, r)
return err
} | [
"func",
"(",
"s",
"*",
"StreamArchive",
")",
"StreamReader",
"(",
"relPath",
"string",
",",
"fi",
"os",
".",
"FileInfo",
",",
"r",
"io",
".",
"Reader",
")",
"(",
"err",
"error",
")",
"{",
"fh",
",",
"err",
":=",
"tar",
".",
"FileInfoHeader",
"(",
"... | // StreamReader streams data from io.Reader to StreamArchive. | [
"StreamReader",
"streams",
"data",
"from",
"io",
".",
"Reader",
"to",
"StreamArchive",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/stream.go#L81-L92 |
16,843 | Unknwon/cae | tz/write.go | ExtractToFunc | func (tz *TzArchive) ExtractToFunc(destPath string, fn cae.HookFunc, entries ...string) (err error) {
destPath = strings.Replace(destPath, "\\", "/", -1)
isHasEntry := len(entries) > 0
if Verbose {
fmt.Println("Extracting " + tz.FileName + "...")
}
os.MkdirAll(destPath, os.ModePerm)
// Copy post-added files.
for _, f := range tz.files {
if !cae.IsExist(f.absPath) {
continue
}
relPath := path.Join(destPath, f.Name)
os.MkdirAll(path.Dir(relPath), os.ModePerm)
if err := cae.Copy(relPath, f.absPath); err != nil {
return err
}
}
tr, f, err := openFile(tz.FileName)
if err != nil {
return err
}
defer f.Close()
for {
h, err := tr.Next()
if err == io.EOF {
break
} else if err != nil {
return err
}
h.Name = strings.Replace(h.Name, "\\", "/", -1)
// Directory.
if h.Typeflag == tar.TypeDir {
if isHasEntry {
if cae.IsEntry(h.Name, entries) {
if err = fn(h.Name, h.FileInfo()); err != nil {
continue
}
os.MkdirAll(path.Join(destPath, h.Name), os.ModePerm)
}
continue
}
if err = fn(h.Name, h.FileInfo()); err != nil {
continue
}
os.MkdirAll(path.Join(destPath, h.Name), os.ModePerm)
continue
}
// File.
if isHasEntry {
if cae.IsEntry(h.Name, entries) {
if err = fn(h.Name, h.FileInfo()); err != nil {
continue
}
err = extractFile(h, tr, destPath)
}
} else {
if err = fn(h.Name, h.FileInfo()); err != nil {
continue
}
err = extractFile(h, tr, destPath)
}
if err != nil {
return err
}
}
return nil
} | go | func (tz *TzArchive) ExtractToFunc(destPath string, fn cae.HookFunc, entries ...string) (err error) {
destPath = strings.Replace(destPath, "\\", "/", -1)
isHasEntry := len(entries) > 0
if Verbose {
fmt.Println("Extracting " + tz.FileName + "...")
}
os.MkdirAll(destPath, os.ModePerm)
// Copy post-added files.
for _, f := range tz.files {
if !cae.IsExist(f.absPath) {
continue
}
relPath := path.Join(destPath, f.Name)
os.MkdirAll(path.Dir(relPath), os.ModePerm)
if err := cae.Copy(relPath, f.absPath); err != nil {
return err
}
}
tr, f, err := openFile(tz.FileName)
if err != nil {
return err
}
defer f.Close()
for {
h, err := tr.Next()
if err == io.EOF {
break
} else if err != nil {
return err
}
h.Name = strings.Replace(h.Name, "\\", "/", -1)
// Directory.
if h.Typeflag == tar.TypeDir {
if isHasEntry {
if cae.IsEntry(h.Name, entries) {
if err = fn(h.Name, h.FileInfo()); err != nil {
continue
}
os.MkdirAll(path.Join(destPath, h.Name), os.ModePerm)
}
continue
}
if err = fn(h.Name, h.FileInfo()); err != nil {
continue
}
os.MkdirAll(path.Join(destPath, h.Name), os.ModePerm)
continue
}
// File.
if isHasEntry {
if cae.IsEntry(h.Name, entries) {
if err = fn(h.Name, h.FileInfo()); err != nil {
continue
}
err = extractFile(h, tr, destPath)
}
} else {
if err = fn(h.Name, h.FileInfo()); err != nil {
continue
}
err = extractFile(h, tr, destPath)
}
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"tz",
"*",
"TzArchive",
")",
"ExtractToFunc",
"(",
"destPath",
"string",
",",
"fn",
"cae",
".",
"HookFunc",
",",
"entries",
"...",
"string",
")",
"(",
"err",
"error",
")",
"{",
"destPath",
"=",
"strings",
".",
"Replace",
"(",
"destPath",
"... | // ExtractTo extracts the whole archive or the given files to the
// specified destination.
// It accepts a function as a middleware for custom operations. | [
"ExtractTo",
"extracts",
"the",
"whole",
"archive",
"or",
"the",
"given",
"files",
"to",
"the",
"specified",
"destination",
".",
"It",
"accepts",
"a",
"function",
"as",
"a",
"middleware",
"for",
"custom",
"operations",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/write.go#L71-L145 |
16,844 | Unknwon/cae | tz/write.go | extractFile | func (tz *TzArchive) extractFile(f *File, tr *tar.Reader) error {
if !tz.isHasWriter {
for _, h := range tz.ReadCloser.File {
if f.Name == h.Name {
return extractFile(h, tr, f.absPath)
}
}
}
return cae.Copy(f.Name, f.absPath)
} | go | func (tz *TzArchive) extractFile(f *File, tr *tar.Reader) error {
if !tz.isHasWriter {
for _, h := range tz.ReadCloser.File {
if f.Name == h.Name {
return extractFile(h, tr, f.absPath)
}
}
}
return cae.Copy(f.Name, f.absPath)
} | [
"func",
"(",
"tz",
"*",
"TzArchive",
")",
"extractFile",
"(",
"f",
"*",
"File",
",",
"tr",
"*",
"tar",
".",
"Reader",
")",
"error",
"{",
"if",
"!",
"tz",
".",
"isHasWriter",
"{",
"for",
"_",
",",
"h",
":=",
"range",
"tz",
".",
"ReadCloser",
".",
... | // extractFile extracts file from TzArchive to file system. | [
"extractFile",
"extracts",
"file",
"from",
"TzArchive",
"to",
"file",
"system",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/write.go#L166-L176 |
16,845 | Unknwon/cae | tz/write.go | packFile | func packFile(srcFile string, recPath string, tw *tar.Writer, fi os.FileInfo) (err error) {
if fi.IsDir() {
h, err := tar.FileInfoHeader(fi, "")
if err != nil {
return err
}
h.Name = recPath + "/"
if err = tw.WriteHeader(h); err != nil {
return err
}
} else {
target := ""
if fi.Mode()&os.ModeSymlink != 0 {
target, err = os.Readlink(srcFile)
if err != nil {
return err
}
}
h, err := tar.FileInfoHeader(fi, target)
if err != nil {
return err
}
h.Name = recPath
if err = tw.WriteHeader(h); err != nil {
return err
}
if len(target) == 0 {
f, err := os.Open(srcFile)
if err != nil {
return err
}
if _, err = io.Copy(tw, f); err != nil {
return err
}
}
}
return nil
} | go | func packFile(srcFile string, recPath string, tw *tar.Writer, fi os.FileInfo) (err error) {
if fi.IsDir() {
h, err := tar.FileInfoHeader(fi, "")
if err != nil {
return err
}
h.Name = recPath + "/"
if err = tw.WriteHeader(h); err != nil {
return err
}
} else {
target := ""
if fi.Mode()&os.ModeSymlink != 0 {
target, err = os.Readlink(srcFile)
if err != nil {
return err
}
}
h, err := tar.FileInfoHeader(fi, target)
if err != nil {
return err
}
h.Name = recPath
if err = tw.WriteHeader(h); err != nil {
return err
}
if len(target) == 0 {
f, err := os.Open(srcFile)
if err != nil {
return err
}
if _, err = io.Copy(tw, f); err != nil {
return err
}
}
}
return nil
} | [
"func",
"packFile",
"(",
"srcFile",
"string",
",",
"recPath",
"string",
",",
"tw",
"*",
"tar",
".",
"Writer",
",",
"fi",
"os",
".",
"FileInfo",
")",
"(",
"err",
"error",
")",
"{",
"if",
"fi",
".",
"IsDir",
"(",
")",
"{",
"h",
",",
"err",
":=",
... | // packFile packs a file or directory to tar.Writer. | [
"packFile",
"packs",
"a",
"file",
"or",
"directory",
"to",
"tar",
".",
"Writer",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/write.go#L256-L297 |
16,846 | Unknwon/cae | tz/write.go | PackToFunc | func PackToFunc(srcPath, destPath string, fn func(fullName string, fi os.FileInfo) error, includeDir ...bool) error {
isIncludeDir := false
if len(includeDir) > 0 && includeDir[0] {
isIncludeDir = true
}
return packTo(srcPath, destPath, fn, isIncludeDir)
} | go | func PackToFunc(srcPath, destPath string, fn func(fullName string, fi os.FileInfo) error, includeDir ...bool) error {
isIncludeDir := false
if len(includeDir) > 0 && includeDir[0] {
isIncludeDir = true
}
return packTo(srcPath, destPath, fn, isIncludeDir)
} | [
"func",
"PackToFunc",
"(",
"srcPath",
",",
"destPath",
"string",
",",
"fn",
"func",
"(",
"fullName",
"string",
",",
"fi",
"os",
".",
"FileInfo",
")",
"error",
",",
"includeDir",
"...",
"bool",
")",
"error",
"{",
"isIncludeDir",
":=",
"false",
"\n",
"if",... | // PackToFunc packs the complete archive to the specified destination.
// It accepts a function as a middleware for custom operations. | [
"PackToFunc",
"packs",
"the",
"complete",
"archive",
"to",
"the",
"specified",
"destination",
".",
"It",
"accepts",
"a",
"function",
"as",
"a",
"middleware",
"for",
"custom",
"operations",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/write.go#L388-L395 |
16,847 | Unknwon/cae | tz/tz.go | List | func (tz *TzArchive) List(prefixes ...string) []string {
isHasPrefix := len(prefixes) > 0
names := make([]string, 0, tz.NumFiles)
for _, f := range tz.files {
if isHasPrefix && !cae.HasPrefix(f.Name, prefixes) {
continue
}
names = append(names, f.Name)
}
return names
} | go | func (tz *TzArchive) List(prefixes ...string) []string {
isHasPrefix := len(prefixes) > 0
names := make([]string, 0, tz.NumFiles)
for _, f := range tz.files {
if isHasPrefix && !cae.HasPrefix(f.Name, prefixes) {
continue
}
names = append(names, f.Name)
}
return names
} | [
"func",
"(",
"tz",
"*",
"TzArchive",
")",
"List",
"(",
"prefixes",
"...",
"string",
")",
"[",
"]",
"string",
"{",
"isHasPrefix",
":=",
"len",
"(",
"prefixes",
")",
">",
"0",
"\n",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"tz... | // List returns a string slice of files' name in TzArchive.
// Specify prefixes will be used as filters. | [
"List",
"returns",
"a",
"string",
"slice",
"of",
"files",
"name",
"in",
"TzArchive",
".",
"Specify",
"prefixes",
"will",
"be",
"used",
"as",
"filters",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/tz.go#L92-L102 |
16,848 | Unknwon/cae | tz/tz.go | AddEmptyDir | func (tz *TzArchive) AddEmptyDir(dirPath string) bool {
if !strings.HasSuffix(dirPath, "/") {
dirPath += "/"
}
for _, f := range tz.files {
if dirPath == f.Name {
return false
}
}
dirPath = strings.TrimSuffix(dirPath, "/")
if strings.Contains(dirPath, "/") {
// Auto add all upper level directories.
tz.AddEmptyDir(path.Dir(dirPath))
}
tz.files = append(tz.files, &File{
Header: &tar.Header{
Name: dirPath + "/",
},
})
tz.updateStat()
return true
} | go | func (tz *TzArchive) AddEmptyDir(dirPath string) bool {
if !strings.HasSuffix(dirPath, "/") {
dirPath += "/"
}
for _, f := range tz.files {
if dirPath == f.Name {
return false
}
}
dirPath = strings.TrimSuffix(dirPath, "/")
if strings.Contains(dirPath, "/") {
// Auto add all upper level directories.
tz.AddEmptyDir(path.Dir(dirPath))
}
tz.files = append(tz.files, &File{
Header: &tar.Header{
Name: dirPath + "/",
},
})
tz.updateStat()
return true
} | [
"func",
"(",
"tz",
"*",
"TzArchive",
")",
"AddEmptyDir",
"(",
"dirPath",
"string",
")",
"bool",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"dirPath",
",",
"\"",
"\"",
")",
"{",
"dirPath",
"+=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"for",
"_",
",",... | // AddEmptyDir adds a raw directory entry to TzArchive,
// it returns false if same directory enry already existed. | [
"AddEmptyDir",
"adds",
"a",
"raw",
"directory",
"entry",
"to",
"TzArchive",
"it",
"returns",
"false",
"if",
"same",
"directory",
"enry",
"already",
"existed",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/tz.go#L106-L129 |
16,849 | Unknwon/cae | tz/tz.go | AddDir | func (tz *TzArchive) AddDir(dirPath, absPath string) error {
dir, err := os.Open(absPath)
if err != nil {
return err
}
defer dir.Close()
tz.AddEmptyDir(dirPath)
fis, err := dir.Readdir(0)
if err != nil {
return err
}
for _, fi := range fis {
curPath := strings.Replace(absPath+"/"+fi.Name(), "\\", "/", -1)
tmpRecPath := strings.Replace(filepath.Join(dirPath, fi.Name()), "\\", "/", -1)
if fi.IsDir() {
if err = tz.AddDir(tmpRecPath, curPath); err != nil {
return err
}
} else {
if err = tz.AddFile(tmpRecPath, curPath); err != nil {
return err
}
}
}
return nil
} | go | func (tz *TzArchive) AddDir(dirPath, absPath string) error {
dir, err := os.Open(absPath)
if err != nil {
return err
}
defer dir.Close()
tz.AddEmptyDir(dirPath)
fis, err := dir.Readdir(0)
if err != nil {
return err
}
for _, fi := range fis {
curPath := strings.Replace(absPath+"/"+fi.Name(), "\\", "/", -1)
tmpRecPath := strings.Replace(filepath.Join(dirPath, fi.Name()), "\\", "/", -1)
if fi.IsDir() {
if err = tz.AddDir(tmpRecPath, curPath); err != nil {
return err
}
} else {
if err = tz.AddFile(tmpRecPath, curPath); err != nil {
return err
}
}
}
return nil
} | [
"func",
"(",
"tz",
"*",
"TzArchive",
")",
"AddDir",
"(",
"dirPath",
",",
"absPath",
"string",
")",
"error",
"{",
"dir",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"absPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n... | // AddDir adds a directory and subdirectories entries to TzArchive. | [
"AddDir",
"adds",
"a",
"directory",
"and",
"subdirectories",
"entries",
"to",
"TzArchive",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/tz.go#L132-L159 |
16,850 | Unknwon/cae | tz/tz.go | AddFile | func (tz *TzArchive) AddFile(fileName, absPath string) error {
if cae.IsFilter(absPath) {
return nil
}
si, err := os.Lstat(absPath)
if err != nil {
return err
}
target := ""
if si.Mode()&os.ModeSymlink != 0 {
target, err = os.Readlink(absPath)
if err != nil {
return err
}
}
file := new(File)
file.Header, err = tar.FileInfoHeader(si, target)
if err != nil {
return err
}
file.Name = fileName
file.absPath = absPath
tz.AddEmptyDir(path.Dir(fileName))
isExist := false
for _, f := range tz.files {
if fileName == f.Name {
f = file
isExist = true
break
}
}
if !isExist {
tz.files = append(tz.files, file)
}
tz.updateStat()
return nil
} | go | func (tz *TzArchive) AddFile(fileName, absPath string) error {
if cae.IsFilter(absPath) {
return nil
}
si, err := os.Lstat(absPath)
if err != nil {
return err
}
target := ""
if si.Mode()&os.ModeSymlink != 0 {
target, err = os.Readlink(absPath)
if err != nil {
return err
}
}
file := new(File)
file.Header, err = tar.FileInfoHeader(si, target)
if err != nil {
return err
}
file.Name = fileName
file.absPath = absPath
tz.AddEmptyDir(path.Dir(fileName))
isExist := false
for _, f := range tz.files {
if fileName == f.Name {
f = file
isExist = true
break
}
}
if !isExist {
tz.files = append(tz.files, file)
}
tz.updateStat()
return nil
} | [
"func",
"(",
"tz",
"*",
"TzArchive",
")",
"AddFile",
"(",
"fileName",
",",
"absPath",
"string",
")",
"error",
"{",
"if",
"cae",
".",
"IsFilter",
"(",
"absPath",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"si",
",",
"err",
":=",
"os",
".",
"Lstat... | // AddFile adds a file entry to TzArchive. | [
"AddFile",
"adds",
"a",
"file",
"entry",
"to",
"TzArchive",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/tz.go#L168-L210 |
16,851 | Unknwon/cae | tz/read.go | openFile | func openFile(name string) (*tar.Reader, *os.File, error) {
f, err := os.Open(name)
if err != nil {
return nil, nil, err
}
gr, err := gzip.NewReader(f)
if err != nil {
f.Close()
return nil, nil, err
}
return tar.NewReader(gr), f, nil
} | go | func openFile(name string) (*tar.Reader, *os.File, error) {
f, err := os.Open(name)
if err != nil {
return nil, nil, err
}
gr, err := gzip.NewReader(f)
if err != nil {
f.Close()
return nil, nil, err
}
return tar.NewReader(gr), f, nil
} | [
"func",
"openFile",
"(",
"name",
"string",
")",
"(",
"*",
"tar",
".",
"Reader",
",",
"*",
"os",
".",
"File",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"n... | // openFile opens a tar.gz file with gzip and tar decoders. | [
"openFile",
"opens",
"a",
"tar",
".",
"gz",
"file",
"with",
"gzip",
"and",
"tar",
"decoders",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/read.go#L37-L50 |
16,852 | Unknwon/cae | tz/read.go | openReader | func openReader(name string) (*ReadCloser, error) {
tr, f, err := openFile(name)
if err != nil {
return nil, err
}
r := new(ReadCloser)
if err := r.init(tr); err != nil {
return nil, err
}
r.f = f
return r, nil
} | go | func openReader(name string) (*ReadCloser, error) {
tr, f, err := openFile(name)
if err != nil {
return nil, err
}
r := new(ReadCloser)
if err := r.init(tr); err != nil {
return nil, err
}
r.f = f
return r, nil
} | [
"func",
"openReader",
"(",
"name",
"string",
")",
"(",
"*",
"ReadCloser",
",",
"error",
")",
"{",
"tr",
",",
"f",
",",
"err",
":=",
"openFile",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",... | // openReader opens the tar.gz file specified by name and return a tar.Reader. | [
"openReader",
"opens",
"the",
"tar",
".",
"gz",
"file",
"specified",
"by",
"name",
"and",
"return",
"a",
"tar",
".",
"Reader",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/read.go#L53-L65 |
16,853 | Unknwon/cae | tz/read.go | init | func (rc *ReadCloser) init(r *tar.Reader) error {
defer rc.Close()
rc.File = make([]*tar.Header, 0, 10)
for {
h, err := r.Next()
if err == io.EOF {
break
} else if err != nil {
return err
}
rc.File = append(rc.File, h)
}
return nil
} | go | func (rc *ReadCloser) init(r *tar.Reader) error {
defer rc.Close()
rc.File = make([]*tar.Header, 0, 10)
for {
h, err := r.Next()
if err == io.EOF {
break
} else if err != nil {
return err
}
rc.File = append(rc.File, h)
}
return nil
} | [
"func",
"(",
"rc",
"*",
"ReadCloser",
")",
"init",
"(",
"r",
"*",
"tar",
".",
"Reader",
")",
"error",
"{",
"defer",
"rc",
".",
"Close",
"(",
")",
"\n\n",
"rc",
".",
"File",
"=",
"make",
"(",
"[",
"]",
"*",
"tar",
".",
"Header",
",",
"0",
",",... | // init initializes a new ReadCloser. | [
"init",
"initializes",
"a",
"new",
"ReadCloser",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/read.go#L68-L83 |
16,854 | Unknwon/cae | tz/read.go | syncFiles | func (tz *TzArchive) syncFiles() {
tz.files = make([]*File, tz.NumFiles)
for i, f := range tz.File {
tz.files[i] = &File{}
tz.files[i].Header = f
tz.files[i].Name = strings.Replace(f.Name, "\\", "/", -1)
if f.FileInfo().IsDir() && !strings.HasSuffix(tz.files[i].Name, "/") {
tz.files[i].Name += "/"
}
}
} | go | func (tz *TzArchive) syncFiles() {
tz.files = make([]*File, tz.NumFiles)
for i, f := range tz.File {
tz.files[i] = &File{}
tz.files[i].Header = f
tz.files[i].Name = strings.Replace(f.Name, "\\", "/", -1)
if f.FileInfo().IsDir() && !strings.HasSuffix(tz.files[i].Name, "/") {
tz.files[i].Name += "/"
}
}
} | [
"func",
"(",
"tz",
"*",
"TzArchive",
")",
"syncFiles",
"(",
")",
"{",
"tz",
".",
"files",
"=",
"make",
"(",
"[",
"]",
"*",
"File",
",",
"tz",
".",
"NumFiles",
")",
"\n",
"for",
"i",
",",
"f",
":=",
"range",
"tz",
".",
"File",
"{",
"tz",
".",
... | // syncFiles syncs file information from file system to memroy object. | [
"syncFiles",
"syncs",
"file",
"information",
"from",
"file",
"system",
"to",
"memroy",
"object",
"."
] | c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c | https://github.com/Unknwon/cae/blob/c6aac99ea2cae2ebaf23f26f76b04fe3fcfc9f8c/tz/read.go#L86-L96 |
16,855 | gowww/router | node.go | countChildren | func (n *node) countChildren() (i int) {
for _, n := range n.children {
i++
i += n.countChildren()
}
return
} | go | func (n *node) countChildren() (i int) {
for _, n := range n.children {
i++
i += n.countChildren()
}
return
} | [
"func",
"(",
"n",
"*",
"node",
")",
"countChildren",
"(",
")",
"(",
"i",
"int",
")",
"{",
"for",
"_",
",",
"n",
":=",
"range",
"n",
".",
"children",
"{",
"i",
"++",
"\n",
"i",
"+=",
"n",
".",
"countChildren",
"(",
")",
"\n",
"}",
"\n",
"retur... | // countChildren returns the number of children + grandchildren in node. | [
"countChildren",
"returns",
"the",
"number",
"of",
"children",
"+",
"grandchildren",
"in",
"node",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/node.go#L52-L58 |
16,856 | gowww/router | node.go | makeChild | func (n *node) makeChild(path string, params map[string]uint16, re *regexp.Regexp, handler http.Handler, isRoot bool) {
defer n.sortChildren()
NodesLoop:
for _, child := range n.children {
minlen := len(child.s)
if len(path) < minlen {
minlen = len(path)
}
for i := 0; i < minlen; i++ {
if child.s[i] == path[i] {
continue
}
if i == 0 { // No match from the first byte: see next same-level node.
continue NodesLoop
}
// Difference in the middle of a node: split current node to make subnode and transfer handler to it.
*child = node{
s: child.s[:i],
children: []*node{
{s: child.s[i:], params: child.params, re: child.re, children: child.children, handler: child.handler},
{s: path[i:], params: params, re: re, handler: handler},
},
}
// BUG(arthurwhite): If the client has no route for "/" and this split occurs on the first level because of the 2nd byte (just after the leading "/"), the isRoot flag of the parent node ("/") is false.
// It's not a problem because it has no handler and will never match a request, but it's not clean.
// A first solution would be to let makeChild know the current level in tree, but... All that for this?
return
}
if len(path) < len(child.s) { // s fully matched first part of n.s: split node.
*child = node{
s: child.s[:len(path)],
params: params,
re: re,
children: []*node{
{s: child.s[len(path):], params: child.params, re: child.re, children: child.children, handler: child.handler},
},
handler: handler,
isRoot: isRoot,
}
} else if len(path) > len(child.s) { // n.s fully matched first part of s: see subnodes for the rest.
child.makeChild(path[len(child.s):], params, re, handler, false)
} else { // s == n.s and no rest: node has no handler or route is duplicated.
if handler == nil { // No handler provided (must be a non-ending path parameter): don't overwrite.
return
}
if child.handler != nil { // Handler provided but child.handler already set: it's a parameter with another re value, or route is duplicated.
if re == nil && child.re == nil || re != nil && child.re != nil && re.String() == child.re.String() {
panic("router: two or more routes have same path")
}
continue NodesLoop // It's a parameter with a different regular expression: check next child for "same path" error. Otherwise, node will be appended.
}
child.params = params
child.re = re
child.handler = handler
child.isRoot = isRoot
}
return
}
n.children = append(n.children, &node{s: path, params: params, re: re, handler: handler, isRoot: isRoot}) // Not a single byte match on same-level nodes: append a new one.
} | go | func (n *node) makeChild(path string, params map[string]uint16, re *regexp.Regexp, handler http.Handler, isRoot bool) {
defer n.sortChildren()
NodesLoop:
for _, child := range n.children {
minlen := len(child.s)
if len(path) < minlen {
minlen = len(path)
}
for i := 0; i < minlen; i++ {
if child.s[i] == path[i] {
continue
}
if i == 0 { // No match from the first byte: see next same-level node.
continue NodesLoop
}
// Difference in the middle of a node: split current node to make subnode and transfer handler to it.
*child = node{
s: child.s[:i],
children: []*node{
{s: child.s[i:], params: child.params, re: child.re, children: child.children, handler: child.handler},
{s: path[i:], params: params, re: re, handler: handler},
},
}
// BUG(arthurwhite): If the client has no route for "/" and this split occurs on the first level because of the 2nd byte (just after the leading "/"), the isRoot flag of the parent node ("/") is false.
// It's not a problem because it has no handler and will never match a request, but it's not clean.
// A first solution would be to let makeChild know the current level in tree, but... All that for this?
return
}
if len(path) < len(child.s) { // s fully matched first part of n.s: split node.
*child = node{
s: child.s[:len(path)],
params: params,
re: re,
children: []*node{
{s: child.s[len(path):], params: child.params, re: child.re, children: child.children, handler: child.handler},
},
handler: handler,
isRoot: isRoot,
}
} else if len(path) > len(child.s) { // n.s fully matched first part of s: see subnodes for the rest.
child.makeChild(path[len(child.s):], params, re, handler, false)
} else { // s == n.s and no rest: node has no handler or route is duplicated.
if handler == nil { // No handler provided (must be a non-ending path parameter): don't overwrite.
return
}
if child.handler != nil { // Handler provided but child.handler already set: it's a parameter with another re value, or route is duplicated.
if re == nil && child.re == nil || re != nil && child.re != nil && re.String() == child.re.String() {
panic("router: two or more routes have same path")
}
continue NodesLoop // It's a parameter with a different regular expression: check next child for "same path" error. Otherwise, node will be appended.
}
child.params = params
child.re = re
child.handler = handler
child.isRoot = isRoot
}
return
}
n.children = append(n.children, &node{s: path, params: params, re: re, handler: handler, isRoot: isRoot}) // Not a single byte match on same-level nodes: append a new one.
} | [
"func",
"(",
"n",
"*",
"node",
")",
"makeChild",
"(",
"path",
"string",
",",
"params",
"map",
"[",
"string",
"]",
"uint16",
",",
"re",
"*",
"regexp",
".",
"Regexp",
",",
"handler",
"http",
".",
"Handler",
",",
"isRoot",
"bool",
")",
"{",
"defer",
"... | // makeChild adds a node to the tree. | [
"makeChild",
"adds",
"a",
"node",
"to",
"the",
"tree",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/node.go#L61-L120 |
16,857 | gowww/router | node.go | findChild | func (n *node) findChild(path string) *node {
for _, n = range n.children {
if n.isParameter() {
paramEnd := strings.IndexByte(path, '/')
if paramEnd == -1 { // Path ends with the parameter.
if n.re != nil && !n.re.MatchString(path) {
continue
}
return n
}
if n.re != nil && !n.re.MatchString(path[:paramEnd]) {
continue
}
return n.findChild(path[paramEnd:])
}
if !strings.HasPrefix(path, n.s) { // Node doesn't match beginning of path.
continue
}
if len(path) == len(n.s) { // Node matched until the end of path.
return n
}
child := n.findChild(path[len(n.s):])
if child == nil || child.handler == nil {
if !n.isRoot && n.isWildcard() { // If node is a wildcard, don't use it when it's root.
return n
}
continue // No match from children and current node is not a wildcard, maybe there is a parameter in next same-level node.
}
return child
}
return nil
} | go | func (n *node) findChild(path string) *node {
for _, n = range n.children {
if n.isParameter() {
paramEnd := strings.IndexByte(path, '/')
if paramEnd == -1 { // Path ends with the parameter.
if n.re != nil && !n.re.MatchString(path) {
continue
}
return n
}
if n.re != nil && !n.re.MatchString(path[:paramEnd]) {
continue
}
return n.findChild(path[paramEnd:])
}
if !strings.HasPrefix(path, n.s) { // Node doesn't match beginning of path.
continue
}
if len(path) == len(n.s) { // Node matched until the end of path.
return n
}
child := n.findChild(path[len(n.s):])
if child == nil || child.handler == nil {
if !n.isRoot && n.isWildcard() { // If node is a wildcard, don't use it when it's root.
return n
}
continue // No match from children and current node is not a wildcard, maybe there is a parameter in next same-level node.
}
return child
}
return nil
} | [
"func",
"(",
"n",
"*",
"node",
")",
"findChild",
"(",
"path",
"string",
")",
"*",
"node",
"{",
"for",
"_",
",",
"n",
"=",
"range",
"n",
".",
"children",
"{",
"if",
"n",
".",
"isParameter",
"(",
")",
"{",
"paramEnd",
":=",
"strings",
".",
"IndexBy... | // findChild returns the deepest node matching path. | [
"findChild",
"returns",
"the",
"deepest",
"node",
"matching",
"path",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/node.go#L123-L154 |
16,858 | gowww/router | node.go | sortChildren | func (n *node) sortChildren() {
sort.Slice(n.children, func(i, j int) bool {
a := n.children[i]
b := n.children[j]
return a.isParameter() && b.isParameter() && a.re != nil ||
!a.isParameter() && b.isParameter() ||
a.countChildren() > b.countChildren()
})
} | go | func (n *node) sortChildren() {
sort.Slice(n.children, func(i, j int) bool {
a := n.children[i]
b := n.children[j]
return a.isParameter() && b.isParameter() && a.re != nil ||
!a.isParameter() && b.isParameter() ||
a.countChildren() > b.countChildren()
})
} | [
"func",
"(",
"n",
"*",
"node",
")",
"sortChildren",
"(",
")",
"{",
"sort",
".",
"Slice",
"(",
"n",
".",
"children",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"a",
":=",
"n",
".",
"children",
"[",
"i",
"]",
"\n",
"b",
":=",
"... | // sortChildren puts children with most subnodes on top, plain strings before parameters, and parameters with regular expressions before the parameter without. | [
"sortChildren",
"puts",
"children",
"with",
"most",
"subnodes",
"on",
"top",
"plain",
"strings",
"before",
"parameters",
"and",
"parameters",
"with",
"regular",
"expressions",
"before",
"the",
"parameter",
"without",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/node.go#L157-L165 |
16,859 | gowww/router | router.go | Handle | func (rt *Router) Handle(method, path string, handler http.Handler) {
if len(path) == 0 || path[0] != '/' {
panic(fmt.Errorf("router: path %q must begin with %q", path, "/"))
}
// Get (or set) tree for method.
n := rt.trees[method]
if n == nil {
n = new(node)
rt.trees[method] = n
}
// Put parameters in their own node.
parts := splitPath(path)
var s string
var params map[string]uint16
for i, part := range parts {
s += "/"
if len(part) > 0 && part[0] == ':' { // It's a parameter.
n.makeChild(s, params, nil, nil, (i == 0 && s == "/")) // Make child without ":".
part = part[1:]
reSep := strings.IndexByte(part, ':') // Search for a name/regexp separator.
var re *regexp.Regexp
if reSep == -1 { // No regular expression.
if part == "" {
panic(fmt.Errorf("router: path %q has anonymous parameter", path))
}
if params == nil {
params = make(map[string]uint16)
}
params[part] = uint16(i) // Store parameter name with part index.
} else { // Parameter comes with regular expression.
if name := part[:reSep]; name != "" {
if params == nil {
params = make(map[string]uint16)
}
params[name] = uint16(i) // Store parameter name with part index.
}
res := part[reSep+1:]
if res == "" {
panic(fmt.Errorf("router: path %q has empty regular expression", path))
}
re = regexp.MustCompile(res)
}
s += ":" // Only keep colon to represent parameter in tree.
if i == len(parts)-1 { // Parameter is the last part: make it with handler.
n.makeChild(s, params, re, handler, false)
} else {
n.makeChild(s, params, re, nil, false)
}
} else {
s += part
if i == len(parts)-1 { // Last part: make it with handler.
if s != "/" && isWildcard(s) {
if params == nil {
params = make(map[string]uint16)
}
params["*"] = uint16(i)
}
n.makeChild(s, params, nil, handler, (i == 0 && s == "/"))
}
}
}
} | go | func (rt *Router) Handle(method, path string, handler http.Handler) {
if len(path) == 0 || path[0] != '/' {
panic(fmt.Errorf("router: path %q must begin with %q", path, "/"))
}
// Get (or set) tree for method.
n := rt.trees[method]
if n == nil {
n = new(node)
rt.trees[method] = n
}
// Put parameters in their own node.
parts := splitPath(path)
var s string
var params map[string]uint16
for i, part := range parts {
s += "/"
if len(part) > 0 && part[0] == ':' { // It's a parameter.
n.makeChild(s, params, nil, nil, (i == 0 && s == "/")) // Make child without ":".
part = part[1:]
reSep := strings.IndexByte(part, ':') // Search for a name/regexp separator.
var re *regexp.Regexp
if reSep == -1 { // No regular expression.
if part == "" {
panic(fmt.Errorf("router: path %q has anonymous parameter", path))
}
if params == nil {
params = make(map[string]uint16)
}
params[part] = uint16(i) // Store parameter name with part index.
} else { // Parameter comes with regular expression.
if name := part[:reSep]; name != "" {
if params == nil {
params = make(map[string]uint16)
}
params[name] = uint16(i) // Store parameter name with part index.
}
res := part[reSep+1:]
if res == "" {
panic(fmt.Errorf("router: path %q has empty regular expression", path))
}
re = regexp.MustCompile(res)
}
s += ":" // Only keep colon to represent parameter in tree.
if i == len(parts)-1 { // Parameter is the last part: make it with handler.
n.makeChild(s, params, re, handler, false)
} else {
n.makeChild(s, params, re, nil, false)
}
} else {
s += part
if i == len(parts)-1 { // Last part: make it with handler.
if s != "/" && isWildcard(s) {
if params == nil {
params = make(map[string]uint16)
}
params["*"] = uint16(i)
}
n.makeChild(s, params, nil, handler, (i == 0 && s == "/"))
}
}
}
} | [
"func",
"(",
"rt",
"*",
"Router",
")",
"Handle",
"(",
"method",
",",
"path",
"string",
",",
"handler",
"http",
".",
"Handler",
")",
"{",
"if",
"len",
"(",
"path",
")",
"==",
"0",
"||",
"path",
"[",
"0",
"]",
"!=",
"'/'",
"{",
"panic",
"(",
"fmt... | // Handle adds a route with method, path and handler. | [
"Handle",
"adds",
"a",
"route",
"with",
"method",
"path",
"and",
"handler",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/router.go#L44-L108 |
16,860 | gowww/router | router.go | Get | func (rt *Router) Get(path string, handler http.Handler) {
rt.Handle(http.MethodGet, path, handler)
} | go | func (rt *Router) Get(path string, handler http.Handler) {
rt.Handle(http.MethodGet, path, handler)
} | [
"func",
"(",
"rt",
"*",
"Router",
")",
"Get",
"(",
"path",
"string",
",",
"handler",
"http",
".",
"Handler",
")",
"{",
"rt",
".",
"Handle",
"(",
"http",
".",
"MethodGet",
",",
"path",
",",
"handler",
")",
"\n",
"}"
] | // Get makes a route for GET method. | [
"Get",
"makes",
"a",
"route",
"for",
"GET",
"method",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/router.go#L111-L113 |
16,861 | gowww/router | router.go | Post | func (rt *Router) Post(path string, handler http.Handler) {
rt.Handle(http.MethodPost, path, handler)
} | go | func (rt *Router) Post(path string, handler http.Handler) {
rt.Handle(http.MethodPost, path, handler)
} | [
"func",
"(",
"rt",
"*",
"Router",
")",
"Post",
"(",
"path",
"string",
",",
"handler",
"http",
".",
"Handler",
")",
"{",
"rt",
".",
"Handle",
"(",
"http",
".",
"MethodPost",
",",
"path",
",",
"handler",
")",
"\n",
"}"
] | // Post makes a route for POST method. | [
"Post",
"makes",
"a",
"route",
"for",
"POST",
"method",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/router.go#L116-L118 |
16,862 | gowww/router | router.go | Put | func (rt *Router) Put(path string, handler http.Handler) {
rt.Handle(http.MethodPut, path, handler)
} | go | func (rt *Router) Put(path string, handler http.Handler) {
rt.Handle(http.MethodPut, path, handler)
} | [
"func",
"(",
"rt",
"*",
"Router",
")",
"Put",
"(",
"path",
"string",
",",
"handler",
"http",
".",
"Handler",
")",
"{",
"rt",
".",
"Handle",
"(",
"http",
".",
"MethodPut",
",",
"path",
",",
"handler",
")",
"\n",
"}"
] | // Put makes a route for PUT method. | [
"Put",
"makes",
"a",
"route",
"for",
"PUT",
"method",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/router.go#L121-L123 |
16,863 | gowww/router | router.go | Patch | func (rt *Router) Patch(path string, handler http.Handler) {
rt.Handle(http.MethodPatch, path, handler)
} | go | func (rt *Router) Patch(path string, handler http.Handler) {
rt.Handle(http.MethodPatch, path, handler)
} | [
"func",
"(",
"rt",
"*",
"Router",
")",
"Patch",
"(",
"path",
"string",
",",
"handler",
"http",
".",
"Handler",
")",
"{",
"rt",
".",
"Handle",
"(",
"http",
".",
"MethodPatch",
",",
"path",
",",
"handler",
")",
"\n",
"}"
] | // Patch makes a route for PATCH method. | [
"Patch",
"makes",
"a",
"route",
"for",
"PATCH",
"method",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/router.go#L126-L128 |
16,864 | gowww/router | router.go | Delete | func (rt *Router) Delete(path string, handler http.Handler) {
rt.Handle(http.MethodDelete, path, handler)
} | go | func (rt *Router) Delete(path string, handler http.Handler) {
rt.Handle(http.MethodDelete, path, handler)
} | [
"func",
"(",
"rt",
"*",
"Router",
")",
"Delete",
"(",
"path",
"string",
",",
"handler",
"http",
".",
"Handler",
")",
"{",
"rt",
".",
"Handle",
"(",
"http",
".",
"MethodDelete",
",",
"path",
",",
"handler",
")",
"\n",
"}"
] | // Delete makes a route for DELETE method. | [
"Delete",
"makes",
"a",
"route",
"for",
"DELETE",
"method",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/router.go#L131-L133 |
16,865 | gowww/router | router.go | Parameter | func Parameter(r *http.Request, key string) string {
params, ok := r.Context().Value(contextKeyParams).(map[string]string)
if ok { // Parameters already parsed.
return params[key]
}
paramsIdx, ok := r.Context().Value(contextKeyParamsIdx).(map[string]uint16)
if !ok {
return ""
}
params = make(map[string]string, len(paramsIdx))
parts := splitPath(r.URL.Path)
for name, idx := range paramsIdx {
switch name {
case "*":
for idx < uint16(len(parts)) {
params[name] += parts[idx]
if idx < uint16(len(parts))-1 {
params[name] += "/"
}
idx++
}
default:
params[name] = parts[idx]
}
}
*r = *r.WithContext(context.WithValue(r.Context(), contextKeyParams, params))
return params[key]
} | go | func Parameter(r *http.Request, key string) string {
params, ok := r.Context().Value(contextKeyParams).(map[string]string)
if ok { // Parameters already parsed.
return params[key]
}
paramsIdx, ok := r.Context().Value(contextKeyParamsIdx).(map[string]uint16)
if !ok {
return ""
}
params = make(map[string]string, len(paramsIdx))
parts := splitPath(r.URL.Path)
for name, idx := range paramsIdx {
switch name {
case "*":
for idx < uint16(len(parts)) {
params[name] += parts[idx]
if idx < uint16(len(parts))-1 {
params[name] += "/"
}
idx++
}
default:
params[name] = parts[idx]
}
}
*r = *r.WithContext(context.WithValue(r.Context(), contextKeyParams, params))
return params[key]
} | [
"func",
"Parameter",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"key",
"string",
")",
"string",
"{",
"params",
",",
"ok",
":=",
"r",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"contextKeyParams",
")",
".",
"(",
"map",
"[",
"string",
"]",
"string... | // Parameter returns the value of path parameter.
// Result is empty if parameter doesn't exist. | [
"Parameter",
"returns",
"the",
"value",
"of",
"path",
"parameter",
".",
"Result",
"is",
"empty",
"if",
"parameter",
"doesn",
"t",
"exist",
"."
] | 5f9c626ef61940c38ace97f795658c6f2b759afa | https://github.com/gowww/router/blob/5f9c626ef61940c38ace97f795658c6f2b759afa/router.go#L166-L193 |
16,866 | denormal/go-gitignore | position.go | String | func (p Position) String() string {
_prefix := ""
if p.File != "" {
_prefix = p.File + ": "
}
if p.Line == 0 {
return fmt.Sprintf("%s+%d", _prefix, p.Offset)
} else if p.Column == 0 {
return fmt.Sprintf("%s%d", _prefix, p.Line)
} else {
return fmt.Sprintf("%s%d:%d", _prefix, p.Line, p.Column)
}
} | go | func (p Position) String() string {
_prefix := ""
if p.File != "" {
_prefix = p.File + ": "
}
if p.Line == 0 {
return fmt.Sprintf("%s+%d", _prefix, p.Offset)
} else if p.Column == 0 {
return fmt.Sprintf("%s%d", _prefix, p.Line)
} else {
return fmt.Sprintf("%s%d:%d", _prefix, p.Line, p.Column)
}
} | [
"func",
"(",
"p",
"Position",
")",
"String",
"(",
")",
"string",
"{",
"_prefix",
":=",
"\"",
"\"",
"\n",
"if",
"p",
".",
"File",
"!=",
"\"",
"\"",
"{",
"_prefix",
"=",
"p",
".",
"File",
"+",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"Lin... | // String returns a string representation of the current position. | [
"String",
"returns",
"a",
"string",
"representation",
"of",
"the",
"current",
"position",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/position.go#L17-L30 |
16,867 | denormal/go-gitignore | position.go | Zero | func (p Position) Zero() bool {
return p.Line+p.Column+p.Offset == 0
} | go | func (p Position) Zero() bool {
return p.Line+p.Column+p.Offset == 0
} | [
"func",
"(",
"p",
"Position",
")",
"Zero",
"(",
")",
"bool",
"{",
"return",
"p",
".",
"Line",
"+",
"p",
".",
"Column",
"+",
"p",
".",
"Offset",
"==",
"0",
"\n",
"}"
] | // Zero returns true if the Position represents the zero Position | [
"Zero",
"returns",
"true",
"if",
"the",
"Position",
"represents",
"the",
"zero",
"Position"
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/position.go#L33-L35 |
16,868 | denormal/go-gitignore | tokentype.go | String | func (t TokenType) String() string {
switch t {
case ILLEGAL:
return "ILLEGAL"
case EOF:
return "EOF"
case EOL:
return "EOL"
case WHITESPACE:
return "WHITESPACE"
case COMMENT:
return "COMMENT"
case SEPARATOR:
return "SEPARATOR"
case NEGATION:
return "NEGATION"
case PATTERN:
return "PATTERN"
case ANY:
return "ANY"
default:
return "BAD TOKEN"
}
} | go | func (t TokenType) String() string {
switch t {
case ILLEGAL:
return "ILLEGAL"
case EOF:
return "EOF"
case EOL:
return "EOL"
case WHITESPACE:
return "WHITESPACE"
case COMMENT:
return "COMMENT"
case SEPARATOR:
return "SEPARATOR"
case NEGATION:
return "NEGATION"
case PATTERN:
return "PATTERN"
case ANY:
return "ANY"
default:
return "BAD TOKEN"
}
} | [
"func",
"(",
"t",
"TokenType",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"t",
"{",
"case",
"ILLEGAL",
":",
"return",
"\"",
"\"",
"\n",
"case",
"EOF",
":",
"return",
"\"",
"\"",
"\n",
"case",
"EOL",
":",
"return",
"\"",
"\"",
"\n",
"case",
... | // String returns a string representation of the Token type. | [
"String",
"returns",
"a",
"string",
"representation",
"of",
"the",
"Token",
"type",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/tokentype.go#L19-L42 |
16,869 | denormal/go-gitignore | error.go | NewError | func NewError(e error, p Position) Error {
return &err{error: e, _position: p}
} | go | func NewError(e error, p Position) Error {
return &err{error: e, _position: p}
} | [
"func",
"NewError",
"(",
"e",
"error",
",",
"p",
"Position",
")",
"Error",
"{",
"return",
"&",
"err",
"{",
"error",
":",
"e",
",",
"_position",
":",
"p",
"}",
"\n",
"}"
] | // NewError returns a new Error instance for the given error e and position p. | [
"NewError",
"returns",
"a",
"new",
"Error",
"instance",
"for",
"the",
"given",
"error",
"e",
"and",
"position",
"p",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/error.go#L21-L23 |
16,870 | denormal/go-gitignore | cache.go | Set | func (c *cache) Set(path string, ignore GitIgnore) {
if ignore == nil {
return
}
// ensure the map is defined
if c._i == nil {
c._i = make(map[string]GitIgnore)
}
// set the cache item
c._lock.Lock()
c._i[path] = ignore
c._lock.Unlock()
} | go | func (c *cache) Set(path string, ignore GitIgnore) {
if ignore == nil {
return
}
// ensure the map is defined
if c._i == nil {
c._i = make(map[string]GitIgnore)
}
// set the cache item
c._lock.Lock()
c._i[path] = ignore
c._lock.Unlock()
} | [
"func",
"(",
"c",
"*",
"cache",
")",
"Set",
"(",
"path",
"string",
",",
"ignore",
"GitIgnore",
")",
"{",
"if",
"ignore",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// ensure the map is defined",
"if",
"c",
".",
"_i",
"==",
"nil",
"{",
"c",
".",
... | // Set stores the GitIgnore ignore against its path. | [
"Set",
"stores",
"the",
"GitIgnore",
"ignore",
"against",
"its",
"path",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/cache.go#L30-L44 |
16,871 | denormal/go-gitignore | cache.go | Get | func (c *cache) Get(path string) GitIgnore {
c._lock.Lock()
_ignore, _ok := c._i[path]
c._lock.Unlock()
if _ok {
return _ignore
} else {
return nil
}
} | go | func (c *cache) Get(path string) GitIgnore {
c._lock.Lock()
_ignore, _ok := c._i[path]
c._lock.Unlock()
if _ok {
return _ignore
} else {
return nil
}
} | [
"func",
"(",
"c",
"*",
"cache",
")",
"Get",
"(",
"path",
"string",
")",
"GitIgnore",
"{",
"c",
".",
"_lock",
".",
"Lock",
"(",
")",
"\n",
"_ignore",
",",
"_ok",
":=",
"c",
".",
"_i",
"[",
"path",
"]",
"\n",
"c",
".",
"_lock",
".",
"Unlock",
"... | // Get attempts to retrieve an GitIgnore instance associated with the given
// path. If the path is not known nil is returned. | [
"Get",
"attempts",
"to",
"retrieve",
"an",
"GitIgnore",
"instance",
"associated",
"with",
"the",
"given",
"path",
".",
"If",
"the",
"path",
"is",
"not",
"known",
"nil",
"is",
"returned",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/cache.go#L48-L57 |
16,872 | denormal/go-gitignore | repository.go | Absolute | func (r *repository) Absolute(path string, isdir bool) Match {
// does the file share the same directory as this ignore file?
if !strings.HasPrefix(path, r.Base()) {
return nil
}
// extract the relative path of this file
_prefix := len(r.Base()) + 1
_rel := string(path[_prefix:])
return r.Relative(_rel, isdir)
} | go | func (r *repository) Absolute(path string, isdir bool) Match {
// does the file share the same directory as this ignore file?
if !strings.HasPrefix(path, r.Base()) {
return nil
}
// extract the relative path of this file
_prefix := len(r.Base()) + 1
_rel := string(path[_prefix:])
return r.Relative(_rel, isdir)
} | [
"func",
"(",
"r",
"*",
"repository",
")",
"Absolute",
"(",
"path",
"string",
",",
"isdir",
"bool",
")",
"Match",
"{",
"// does the file share the same directory as this ignore file?",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"r",
".",
"Base",
... | // Absolute attempts to match an absolute path against this repository. If the
// path is not located under the base directory of this repository, or is not
// matched by this repository, nil is returned. | [
"Absolute",
"attempts",
"to",
"match",
"an",
"absolute",
"path",
"against",
"this",
"repository",
".",
"If",
"the",
"path",
"is",
"not",
"located",
"under",
"the",
"base",
"directory",
"of",
"this",
"repository",
"or",
"is",
"not",
"matched",
"by",
"this",
... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/repository.go#L197-L207 |
16,873 | denormal/go-gitignore | repository.go | Relative | func (r *repository) Relative(path string, isdir bool) Match {
// if there's no path, then there's nothing to match
_path := filepath.Clean(path)
if _path == "." {
return nil
}
// repository matching:
// - a child path cannot be considered if its parent is ignored
// - a .gitignore in a lower directory overrides a .gitignore in a
// higher directory
// first, is the parent directory ignored?
// - extract the parent directory from the current path
_parent, _local := filepath.Split(_path)
_match := r.Relative(_parent, true)
if _match != nil {
if _match.Ignore() {
return _match
}
}
_parent = filepath.Clean(_parent)
// the parent directory isn't ignored, so we now look at the original path
// - we consider .gitignore files in the current directory first, then
// move up the path hierarchy
var _last string
for {
_file := filepath.Join(r._base, _parent, r._file)
_ignore := NewWithCache(_file, r._cache, r._errors)
if _ignore != nil {
_match := _ignore.Relative(_local, isdir)
if _match != nil {
return _match
}
}
// if there's no parent, then we're done
// - since we use filepath.Clean() we look for "."
if _parent == "." {
break
}
// we don't have a match for this file, so we progress up the
// path hierarchy
// - we are manually building _local using the .gitignore
// separator "/", which is how we handle operating system
// file system differences
_parent, _last = filepath.Split(_parent)
_parent = filepath.Clean(_parent)
_local = _last + string(_SEPARATOR) + _local
}
// do we have a global exclude file? (i.e. GIT_DIR/info/exclude)
if r._exclude != nil {
return r._exclude.Relative(path, isdir)
}
// we have no match
return nil
} | go | func (r *repository) Relative(path string, isdir bool) Match {
// if there's no path, then there's nothing to match
_path := filepath.Clean(path)
if _path == "." {
return nil
}
// repository matching:
// - a child path cannot be considered if its parent is ignored
// - a .gitignore in a lower directory overrides a .gitignore in a
// higher directory
// first, is the parent directory ignored?
// - extract the parent directory from the current path
_parent, _local := filepath.Split(_path)
_match := r.Relative(_parent, true)
if _match != nil {
if _match.Ignore() {
return _match
}
}
_parent = filepath.Clean(_parent)
// the parent directory isn't ignored, so we now look at the original path
// - we consider .gitignore files in the current directory first, then
// move up the path hierarchy
var _last string
for {
_file := filepath.Join(r._base, _parent, r._file)
_ignore := NewWithCache(_file, r._cache, r._errors)
if _ignore != nil {
_match := _ignore.Relative(_local, isdir)
if _match != nil {
return _match
}
}
// if there's no parent, then we're done
// - since we use filepath.Clean() we look for "."
if _parent == "." {
break
}
// we don't have a match for this file, so we progress up the
// path hierarchy
// - we are manually building _local using the .gitignore
// separator "/", which is how we handle operating system
// file system differences
_parent, _last = filepath.Split(_parent)
_parent = filepath.Clean(_parent)
_local = _last + string(_SEPARATOR) + _local
}
// do we have a global exclude file? (i.e. GIT_DIR/info/exclude)
if r._exclude != nil {
return r._exclude.Relative(path, isdir)
}
// we have no match
return nil
} | [
"func",
"(",
"r",
"*",
"repository",
")",
"Relative",
"(",
"path",
"string",
",",
"isdir",
"bool",
")",
"Match",
"{",
"// if there's no path, then there's nothing to match",
"_path",
":=",
"filepath",
".",
"Clean",
"(",
"path",
")",
"\n",
"if",
"_path",
"==",
... | // Relative attempts to match a path relative to the repository base directory.
// If the path is not matched by the repository, nil is returned. | [
"Relative",
"attempts",
"to",
"match",
"a",
"path",
"relative",
"to",
"the",
"repository",
"base",
"directory",
".",
"If",
"the",
"path",
"is",
"not",
"matched",
"by",
"the",
"repository",
"nil",
"is",
"returned",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/repository.go#L211-L271 |
16,874 | denormal/go-gitignore | token.go | NewToken | func NewToken(t TokenType, word []rune, pos Position) *Token {
// ensure the type is valid
if t < ILLEGAL || t > BAD {
t = BAD
}
// return the token
return &Token{Type: t, Word: word, Position: pos}
} | go | func NewToken(t TokenType, word []rune, pos Position) *Token {
// ensure the type is valid
if t < ILLEGAL || t > BAD {
t = BAD
}
// return the token
return &Token{Type: t, Word: word, Position: pos}
} | [
"func",
"NewToken",
"(",
"t",
"TokenType",
",",
"word",
"[",
"]",
"rune",
",",
"pos",
"Position",
")",
"*",
"Token",
"{",
"// ensure the type is valid",
"if",
"t",
"<",
"ILLEGAL",
"||",
"t",
">",
"BAD",
"{",
"t",
"=",
"BAD",
"\n",
"}",
"\n\n",
"// re... | // NewToken returns a Token instance of the given t, represented by the
// word runes, at the stream position pos. If the token type is not know, the
// returned instance will have type BAD. | [
"NewToken",
"returns",
"a",
"Token",
"instance",
"of",
"the",
"given",
"t",
"represented",
"by",
"the",
"word",
"runes",
"at",
"the",
"stream",
"position",
"pos",
".",
"If",
"the",
"token",
"type",
"is",
"not",
"know",
"the",
"returned",
"instance",
"will"... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/token.go#L19-L27 |
16,875 | denormal/go-gitignore | gitignore.go | NewFromFile | func NewFromFile(file string) (GitIgnore, error) {
// define an error handler to catch any file access errors
// - record the first encountered error
var _error Error
_errors := func(e Error) bool {
if _error == nil {
_error = e
}
return true
}
// attempt to retrieve the GitIgnore represented by this file
_ignore := NewWithErrors(file, _errors)
// did we encounter an error?
// - if the error has a zero Position then it was encountered
// before parsing was attempted, so we return that error
if _error != nil {
if _error.Position().Zero() {
return nil, _error.Underlying()
}
}
// otherwise, we ignore the parser errors
return _ignore, nil
} | go | func NewFromFile(file string) (GitIgnore, error) {
// define an error handler to catch any file access errors
// - record the first encountered error
var _error Error
_errors := func(e Error) bool {
if _error == nil {
_error = e
}
return true
}
// attempt to retrieve the GitIgnore represented by this file
_ignore := NewWithErrors(file, _errors)
// did we encounter an error?
// - if the error has a zero Position then it was encountered
// before parsing was attempted, so we return that error
if _error != nil {
if _error.Position().Zero() {
return nil, _error.Underlying()
}
}
// otherwise, we ignore the parser errors
return _ignore, nil
} | [
"func",
"NewFromFile",
"(",
"file",
"string",
")",
"(",
"GitIgnore",
",",
"error",
")",
"{",
"// define an error handler to catch any file access errors",
"//\t\t- record the first encountered error",
"var",
"_error",
"Error",
"\n",
"_errors",
":=",
"func",
"(",
"e",
"E... | // NewFromFile creates a GitIgnore instance from the given file. An error
// will be returned if file cannot be opened or its absolute path determined. | [
"NewFromFile",
"creates",
"a",
"GitIgnore",
"instance",
"from",
"the",
"given",
"file",
".",
"An",
"error",
"will",
"be",
"returned",
"if",
"file",
"cannot",
"be",
"opened",
"or",
"its",
"absolute",
"path",
"determined",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/gitignore.go#L80-L105 |
16,876 | denormal/go-gitignore | gitignore.go | Absolute | func (i *ignore) Absolute(path string, isdir bool) Match {
// does the file share the same directory as this ignore file?
if !strings.HasPrefix(path, i._base) {
return nil
}
// extract the relative path of this file
_prefix := len(i._base) + 1
_rel := string(path[_prefix:])
return i.Relative(_rel, isdir)
} | go | func (i *ignore) Absolute(path string, isdir bool) Match {
// does the file share the same directory as this ignore file?
if !strings.HasPrefix(path, i._base) {
return nil
}
// extract the relative path of this file
_prefix := len(i._base) + 1
_rel := string(path[_prefix:])
return i.Relative(_rel, isdir)
} | [
"func",
"(",
"i",
"*",
"ignore",
")",
"Absolute",
"(",
"path",
"string",
",",
"isdir",
"bool",
")",
"Match",
"{",
"// does the file share the same directory as this ignore file?",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"i",
".",
"_base",
")"... | // Absolute attempts to match an absolute path against this GitIgnore. If
// the path is not located under the base directory of this GitIgnore, or
// is not matched by this GitIgnore, nil is returned. | [
"Absolute",
"attempts",
"to",
"match",
"an",
"absolute",
"path",
"against",
"this",
"GitIgnore",
".",
"If",
"the",
"path",
"is",
"not",
"located",
"under",
"the",
"base",
"directory",
"of",
"this",
"GitIgnore",
"or",
"is",
"not",
"matched",
"by",
"this",
"... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/gitignore.go#L244-L254 |
16,877 | denormal/go-gitignore | gitignore.go | Relative | func (i *ignore) Relative(path string, isdir bool) Match {
// if we are on Windows, then translate the path to Unix form
_rel := path
if runtime.GOOS == "windows" {
_rel = filepath.ToSlash(_rel)
}
// iterate over the patterns for this ignore file
// - iterate in reverse, since later patterns overwrite earlier
for _i := len(i._pattern) - 1; _i >= 0; _i-- {
_pattern := i._pattern[_i]
if _pattern.Match(_rel, isdir) {
return _pattern
}
}
// we don't match this file
return nil
} | go | func (i *ignore) Relative(path string, isdir bool) Match {
// if we are on Windows, then translate the path to Unix form
_rel := path
if runtime.GOOS == "windows" {
_rel = filepath.ToSlash(_rel)
}
// iterate over the patterns for this ignore file
// - iterate in reverse, since later patterns overwrite earlier
for _i := len(i._pattern) - 1; _i >= 0; _i-- {
_pattern := i._pattern[_i]
if _pattern.Match(_rel, isdir) {
return _pattern
}
}
// we don't match this file
return nil
} | [
"func",
"(",
"i",
"*",
"ignore",
")",
"Relative",
"(",
"path",
"string",
",",
"isdir",
"bool",
")",
"Match",
"{",
"// if we are on Windows, then translate the path to Unix form",
"_rel",
":=",
"path",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
"{",
... | // Relative attempts to match a path relative to the GitIgnore base
// directory. isdir is used to indicate whether the path represents a file
// or a directory. If the path is not matched by the GitIgnore, nil is
// returned. | [
"Relative",
"attempts",
"to",
"match",
"a",
"path",
"relative",
"to",
"the",
"GitIgnore",
"base",
"directory",
".",
"isdir",
"is",
"used",
"to",
"indicate",
"whether",
"the",
"path",
"represents",
"a",
"file",
"or",
"a",
"directory",
".",
"If",
"the",
"pat... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/gitignore.go#L260-L278 |
16,878 | denormal/go-gitignore | lexer.go | NewLexer | func NewLexer(r io.Reader) Lexer {
return &lexer{_r: bufio.NewReader(r), _line: 1, _column: 1}
} | go | func NewLexer(r io.Reader) Lexer {
return &lexer{_r: bufio.NewReader(r), _line: 1, _column: 1}
} | [
"func",
"NewLexer",
"(",
"r",
"io",
".",
"Reader",
")",
"Lexer",
"{",
"return",
"&",
"lexer",
"{",
"_r",
":",
"bufio",
".",
"NewReader",
"(",
"r",
")",
",",
"_line",
":",
"1",
",",
"_column",
":",
"1",
"}",
"\n",
"}"
] | // NewLexer returns a Lexer instance for the io.Reader r. | [
"NewLexer",
"returns",
"a",
"Lexer",
"instance",
"for",
"the",
"io",
".",
"Reader",
"r",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/lexer.go#L38-L40 |
16,879 | denormal/go-gitignore | lexer.go | Next | func (l *lexer) Next() (*Token, Error) {
// are we at the beginning of the line?
_beginning := l.beginning()
// read the next rune
_r, _err := l.read()
if _err != nil {
return nil, _err
}
switch _r {
// end of file
case _EOF:
return l.token(EOF, nil, nil)
// whitespace ' ', '\t'
case _SPACE:
fallthrough
case _TAB:
l.unread(_r)
_rtn, _err := l.whitespace()
return l.token(WHITESPACE, _rtn, _err)
// end of line '\n' or '\r\n'
case _CR:
fallthrough
case _NEWLINE:
l.unread(_r)
_rtn, _err := l.eol()
return l.token(EOL, _rtn, _err)
// separator '/'
case _SEPARATOR:
return l.token(SEPARATOR, []rune{_r}, nil)
// '*' or any '**'
case _WILDCARD:
// is the wildcard followed by another wildcard?
// - does this represent the "any" token (i.e. "**")
_next, _err := l.peek()
if _err != nil {
return nil, _err
} else if _next == _WILDCARD {
// we know read() will succeed here since we used peek() above
l.read()
return l.token(ANY, []rune{_WILDCARD, _WILDCARD}, nil)
}
// we have a single wildcard, so treat this as a pattern
l.unread(_r)
_rtn, _err := l.pattern()
return l.token(PATTERN, _rtn, _err)
// comment '#'
case _COMMENT:
l.unread(_r)
// if we are at the start of the line, then we treat this as a comment
if _beginning {
_rtn, _err := l.comment()
return l.token(COMMENT, _rtn, _err)
}
// otherwise, we regard this as a pattern
_rtn, _err := l.pattern()
return l.token(PATTERN, _rtn, _err)
// negation '!'
case _NEGATION:
if _beginning {
return l.token(NEGATION, []rune{_r}, nil)
}
fallthrough
// pattern
default:
l.unread(_r)
_rtn, _err := l.pattern()
return l.token(PATTERN, _rtn, _err)
}
} | go | func (l *lexer) Next() (*Token, Error) {
// are we at the beginning of the line?
_beginning := l.beginning()
// read the next rune
_r, _err := l.read()
if _err != nil {
return nil, _err
}
switch _r {
// end of file
case _EOF:
return l.token(EOF, nil, nil)
// whitespace ' ', '\t'
case _SPACE:
fallthrough
case _TAB:
l.unread(_r)
_rtn, _err := l.whitespace()
return l.token(WHITESPACE, _rtn, _err)
// end of line '\n' or '\r\n'
case _CR:
fallthrough
case _NEWLINE:
l.unread(_r)
_rtn, _err := l.eol()
return l.token(EOL, _rtn, _err)
// separator '/'
case _SEPARATOR:
return l.token(SEPARATOR, []rune{_r}, nil)
// '*' or any '**'
case _WILDCARD:
// is the wildcard followed by another wildcard?
// - does this represent the "any" token (i.e. "**")
_next, _err := l.peek()
if _err != nil {
return nil, _err
} else if _next == _WILDCARD {
// we know read() will succeed here since we used peek() above
l.read()
return l.token(ANY, []rune{_WILDCARD, _WILDCARD}, nil)
}
// we have a single wildcard, so treat this as a pattern
l.unread(_r)
_rtn, _err := l.pattern()
return l.token(PATTERN, _rtn, _err)
// comment '#'
case _COMMENT:
l.unread(_r)
// if we are at the start of the line, then we treat this as a comment
if _beginning {
_rtn, _err := l.comment()
return l.token(COMMENT, _rtn, _err)
}
// otherwise, we regard this as a pattern
_rtn, _err := l.pattern()
return l.token(PATTERN, _rtn, _err)
// negation '!'
case _NEGATION:
if _beginning {
return l.token(NEGATION, []rune{_r}, nil)
}
fallthrough
// pattern
default:
l.unread(_r)
_rtn, _err := l.pattern()
return l.token(PATTERN, _rtn, _err)
}
} | [
"func",
"(",
"l",
"*",
"lexer",
")",
"Next",
"(",
")",
"(",
"*",
"Token",
",",
"Error",
")",
"{",
"// are we at the beginning of the line?",
"_beginning",
":=",
"l",
".",
"beginning",
"(",
")",
"\n\n",
"// read the next rune",
"_r",
",",
"_err",
":=",
"l",... | // Next returns the next Token from the Lexer reader. If an error is
// encountered, it will be returned as an Error instance, detailing the error
// and its position within the stream. | [
"Next",
"returns",
"the",
"next",
"Token",
"from",
"the",
"Lexer",
"reader",
".",
"If",
"an",
"error",
"is",
"encountered",
"it",
"will",
"be",
"returned",
"as",
"an",
"Error",
"instance",
"detailing",
"the",
"error",
"and",
"its",
"position",
"within",
"t... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/lexer.go#L45-L125 |
16,880 | denormal/go-gitignore | lexer.go | Position | func (l *lexer) Position() Position {
return Position{"", l._line, l._column, l._offset}
} | go | func (l *lexer) Position() Position {
return Position{"", l._line, l._column, l._offset}
} | [
"func",
"(",
"l",
"*",
"lexer",
")",
"Position",
"(",
")",
"Position",
"{",
"return",
"Position",
"{",
"\"",
"\"",
",",
"l",
".",
"_line",
",",
"l",
".",
"_column",
",",
"l",
".",
"_offset",
"}",
"\n",
"}"
] | // Position returns the current position of the Lexer. | [
"Position",
"returns",
"the",
"current",
"position",
"of",
"the",
"Lexer",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/lexer.go#L128-L130 |
16,881 | denormal/go-gitignore | lexer.go | read | func (l *lexer) read() (rune, Error) {
var _r rune
var _err error
// do we have any unread runes to read?
_length := len(l._unread)
if _length > 0 {
_r = l._unread[_length-1]
l._unread = l._unread[:_length-1]
// otherwise, attempt to read a new rune
} else {
_r, _, _err = l._r.ReadRune()
if _err == io.EOF {
return _EOF, nil
}
}
// increment the offset and column counts
l._offset++
l._column++
return _r, l.err(_err)
} | go | func (l *lexer) read() (rune, Error) {
var _r rune
var _err error
// do we have any unread runes to read?
_length := len(l._unread)
if _length > 0 {
_r = l._unread[_length-1]
l._unread = l._unread[:_length-1]
// otherwise, attempt to read a new rune
} else {
_r, _, _err = l._r.ReadRune()
if _err == io.EOF {
return _EOF, nil
}
}
// increment the offset and column counts
l._offset++
l._column++
return _r, l.err(_err)
} | [
"func",
"(",
"l",
"*",
"lexer",
")",
"read",
"(",
")",
"(",
"rune",
",",
"Error",
")",
"{",
"var",
"_r",
"rune",
"\n",
"var",
"_err",
"error",
"\n\n",
"// do we have any unread runes to read?",
"_length",
":=",
"len",
"(",
"l",
".",
"_unread",
")",
"\n... | //
// private methods
//
// read the next rune from the stream. Return an Error if there is a problem
// reading from the stream. If the end of stream is reached, return the EOF
// Token. | [
"private",
"methods",
"read",
"the",
"next",
"rune",
"from",
"the",
"stream",
".",
"Return",
"an",
"Error",
"if",
"there",
"is",
"a",
"problem",
"reading",
"from",
"the",
"stream",
".",
"If",
"the",
"end",
"of",
"stream",
"is",
"reached",
"return",
"the"... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/lexer.go#L145-L168 |
16,882 | denormal/go-gitignore | lexer.go | unread | func (l *lexer) unread(r ...rune) {
// ignore EOF runes
_r := make([]rune, 0)
for _, _rune := range r {
if _rune != _EOF {
_r = append(_r, _rune)
}
}
// initialise the unread rune list if necessary
if l._unread == nil {
l._unread = make([]rune, 0)
}
if len(_r) != 0 {
l._unread = append(l._unread, _r...)
}
// decrement the offset and column counts
// - we have to take care of column being 0
// - at present we can only unwind across a single line boundary
_length := len(_r)
for ; _length > 0; _length-- {
l._offset--
if l._column == 1 {
_length := len(l._previous)
if _length > 0 {
l._column = l._previous[_length-1]
l._previous = l._previous[:_length-1]
l._line--
}
} else {
l._column--
}
}
} | go | func (l *lexer) unread(r ...rune) {
// ignore EOF runes
_r := make([]rune, 0)
for _, _rune := range r {
if _rune != _EOF {
_r = append(_r, _rune)
}
}
// initialise the unread rune list if necessary
if l._unread == nil {
l._unread = make([]rune, 0)
}
if len(_r) != 0 {
l._unread = append(l._unread, _r...)
}
// decrement the offset and column counts
// - we have to take care of column being 0
// - at present we can only unwind across a single line boundary
_length := len(_r)
for ; _length > 0; _length-- {
l._offset--
if l._column == 1 {
_length := len(l._previous)
if _length > 0 {
l._column = l._previous[_length-1]
l._previous = l._previous[:_length-1]
l._line--
}
} else {
l._column--
}
}
} | [
"func",
"(",
"l",
"*",
"lexer",
")",
"unread",
"(",
"r",
"...",
"rune",
")",
"{",
"// ignore EOF runes",
"_r",
":=",
"make",
"(",
"[",
"]",
"rune",
",",
"0",
")",
"\n",
"for",
"_",
",",
"_rune",
":=",
"range",
"r",
"{",
"if",
"_rune",
"!=",
"_E... | // unread returns the given runes to the stream, making them eligible to be
// read again. The runes are returned in the order given, so the last rune
// specified will be the next rune read from the stream. | [
"unread",
"returns",
"the",
"given",
"runes",
"to",
"the",
"stream",
"making",
"them",
"eligible",
"to",
"be",
"read",
"again",
".",
"The",
"runes",
"are",
"returned",
"in",
"the",
"order",
"given",
"so",
"the",
"last",
"rune",
"specified",
"will",
"be",
... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/lexer.go#L173-L207 |
16,883 | denormal/go-gitignore | lexer.go | newline | func (l *lexer) newline() {
// adjust the counters for the new line
if l._previous == nil {
l._previous = make([]int, 0)
}
l._previous = append(l._previous, l._column)
l._column = 1
l._line++
} | go | func (l *lexer) newline() {
// adjust the counters for the new line
if l._previous == nil {
l._previous = make([]int, 0)
}
l._previous = append(l._previous, l._column)
l._column = 1
l._line++
} | [
"func",
"(",
"l",
"*",
"lexer",
")",
"newline",
"(",
")",
"{",
"// adjust the counters for the new line",
"if",
"l",
".",
"_previous",
"==",
"nil",
"{",
"l",
".",
"_previous",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
")",
"\n",
"}",
"\n",
"l",
... | // newline adjusts the positional counters when an end of line is reached | [
"newline",
"adjusts",
"the",
"positional",
"counters",
"when",
"an",
"end",
"of",
"line",
"is",
"reached"
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/lexer.go#L225-L233 |
16,884 | denormal/go-gitignore | lexer.go | comment | func (l *lexer) comment() ([]rune, Error) {
_comment := make([]rune, 0)
// read until we reach end of line or end of file
// - as we are in a comment, we ignore escape characters
for {
_next, _err := l.read()
if _err != nil {
return _comment, _err
}
// read until we have end of line or end of file
switch _next {
case _CR:
fallthrough
case _NEWLINE:
fallthrough
case _EOF:
// return the read run to the stream and stop
l.unread(_next)
return _comment, nil
}
// otherwise, add this run to the comment
_comment = append(_comment, _next)
}
} | go | func (l *lexer) comment() ([]rune, Error) {
_comment := make([]rune, 0)
// read until we reach end of line or end of file
// - as we are in a comment, we ignore escape characters
for {
_next, _err := l.read()
if _err != nil {
return _comment, _err
}
// read until we have end of line or end of file
switch _next {
case _CR:
fallthrough
case _NEWLINE:
fallthrough
case _EOF:
// return the read run to the stream and stop
l.unread(_next)
return _comment, nil
}
// otherwise, add this run to the comment
_comment = append(_comment, _next)
}
} | [
"func",
"(",
"l",
"*",
"lexer",
")",
"comment",
"(",
")",
"(",
"[",
"]",
"rune",
",",
"Error",
")",
"{",
"_comment",
":=",
"make",
"(",
"[",
"]",
"rune",
",",
"0",
")",
"\n\n",
"// read until we reach end of line or end of file",
"//\t\t- as we are in a comm... | // comment reads all runes until a newline or end of file is reached. An
// error is returned if an error is encountered reading from the stream. | [
"comment",
"reads",
"all",
"runes",
"until",
"a",
"newline",
"or",
"end",
"of",
"file",
"is",
"reached",
".",
"An",
"error",
"is",
"returned",
"if",
"an",
"error",
"is",
"encountered",
"reading",
"from",
"the",
"stream",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/lexer.go#L237-L263 |
16,885 | denormal/go-gitignore | lexer.go | eol | func (l *lexer) eol() ([]rune, Error) {
// read the to the end of the line
// - we should only be called here when we encounter an end of line
// sequence
_line := make([]rune, 0, 1)
// loop until there's nothing more to do
for {
_next, _err := l.read()
if _err != nil {
return _line, _err
}
// read until we have a newline or we're at end of file
switch _next {
// end of file
case _EOF:
return _line, nil
// carriage return - we expect to see a newline next
case _CR:
_line = append(_line, _next)
_next, _err = l.read()
if _err != nil {
return _line, _err
} else if _next != _NEWLINE {
l.unread(_next)
return _line, l.err(CarriageReturnError)
}
fallthrough
// newline
case _NEWLINE:
_line = append(_line, _next)
return _line, nil
}
}
} | go | func (l *lexer) eol() ([]rune, Error) {
// read the to the end of the line
// - we should only be called here when we encounter an end of line
// sequence
_line := make([]rune, 0, 1)
// loop until there's nothing more to do
for {
_next, _err := l.read()
if _err != nil {
return _line, _err
}
// read until we have a newline or we're at end of file
switch _next {
// end of file
case _EOF:
return _line, nil
// carriage return - we expect to see a newline next
case _CR:
_line = append(_line, _next)
_next, _err = l.read()
if _err != nil {
return _line, _err
} else if _next != _NEWLINE {
l.unread(_next)
return _line, l.err(CarriageReturnError)
}
fallthrough
// newline
case _NEWLINE:
_line = append(_line, _next)
return _line, nil
}
}
} | [
"func",
"(",
"l",
"*",
"lexer",
")",
"eol",
"(",
")",
"(",
"[",
"]",
"rune",
",",
"Error",
")",
"{",
"// read the to the end of the line",
"// - we should only be called here when we encounter an end of line",
"// sequence",
"_line",
":=",
"make",
"(",
"["... | // eol returns all runes from the current position to the end of the line. An
// error is returned if there is a problem reading from the stream, or if a
// carriage return character '\r' is encountered that is not followed by a
// newline '\n'. | [
"eol",
"returns",
"all",
"runes",
"from",
"the",
"current",
"position",
"to",
"the",
"end",
"of",
"the",
"line",
".",
"An",
"error",
"is",
"returned",
"if",
"there",
"is",
"a",
"problem",
"reading",
"from",
"the",
"stream",
"or",
"if",
"a",
"carriage",
... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/lexer.go#L299-L336 |
16,886 | denormal/go-gitignore | lexer.go | token | func (l *lexer) token(type_ TokenType, word []rune, e Error) (*Token, Error) {
// if we have an error, then we return a BAD token
if e != nil {
type_ = BAD
}
// extract the lexer position
// - the column is taken from the current column position
// minus the length of the consumed "word"
_word := len(word)
_column := l._column - _word
_offset := l._offset - _word
position := Position{"", l._line, _column, _offset}
// if this is a newline token, we adjust the line & column counts
if type_ == EOL {
l.newline()
}
// return the Token
return NewToken(type_, word, position), e
} | go | func (l *lexer) token(type_ TokenType, word []rune, e Error) (*Token, Error) {
// if we have an error, then we return a BAD token
if e != nil {
type_ = BAD
}
// extract the lexer position
// - the column is taken from the current column position
// minus the length of the consumed "word"
_word := len(word)
_column := l._column - _word
_offset := l._offset - _word
position := Position{"", l._line, _column, _offset}
// if this is a newline token, we adjust the line & column counts
if type_ == EOL {
l.newline()
}
// return the Token
return NewToken(type_, word, position), e
} | [
"func",
"(",
"l",
"*",
"lexer",
")",
"token",
"(",
"type_",
"TokenType",
",",
"word",
"[",
"]",
"rune",
",",
"e",
"Error",
")",
"(",
"*",
"Token",
",",
"Error",
")",
"{",
"// if we have an error, then we return a BAD token",
"if",
"e",
"!=",
"nil",
"{",
... | // token returns a Token instance of the given type_ represented by word runes. | [
"token",
"returns",
"a",
"Token",
"instance",
"of",
"the",
"given",
"type_",
"represented",
"by",
"word",
"runes",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/lexer.go#L434-L455 |
16,887 | denormal/go-gitignore | lexer.go | err | func (l *lexer) err(e error) Error {
// do we have an error?
if e == nil {
return nil
} else {
return NewError(e, l.Position())
}
} | go | func (l *lexer) err(e error) Error {
// do we have an error?
if e == nil {
return nil
} else {
return NewError(e, l.Position())
}
} | [
"func",
"(",
"l",
"*",
"lexer",
")",
"err",
"(",
"e",
"error",
")",
"Error",
"{",
"// do we have an error?",
"if",
"e",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"else",
"{",
"return",
"NewError",
"(",
"e",
",",
"l",
".",
"Position",
"(",
")",
... | // err returns an Error encapsulating the error e and the current Lexer
// position. | [
"err",
"returns",
"an",
"Error",
"encapsulating",
"the",
"error",
"e",
"and",
"the",
"current",
"Lexer",
"position",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/lexer.go#L459-L466 |
16,888 | denormal/go-gitignore | parser.go | NewParser | func NewParser(r io.Reader, err func(Error) bool) Parser {
return &parser{_lexer: NewLexer(r), _error: err}
} | go | func NewParser(r io.Reader, err func(Error) bool) Parser {
return &parser{_lexer: NewLexer(r), _error: err}
} | [
"func",
"NewParser",
"(",
"r",
"io",
".",
"Reader",
",",
"err",
"func",
"(",
"Error",
")",
"bool",
")",
"Parser",
"{",
"return",
"&",
"parser",
"{",
"_lexer",
":",
"NewLexer",
"(",
"r",
")",
",",
"_error",
":",
"err",
"}",
"\n",
"}"
] | // NewParser returns a new Parser instance for the given stream r.
// If err is not nil, it will be called for every error encountered during
// parsing. Parsing will terminate at the end of the stream, or if err
// returns false. | [
"NewParser",
"returns",
"a",
"new",
"Parser",
"instance",
"for",
"the",
"given",
"stream",
"r",
".",
"If",
"err",
"is",
"not",
"nil",
"it",
"will",
"be",
"called",
"for",
"every",
"error",
"encountered",
"during",
"parsing",
".",
"Parsing",
"will",
"termin... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L38-L40 |
16,889 | denormal/go-gitignore | parser.go | Parse | func (p *parser) Parse() []Pattern {
// keep parsing until there's no more patterns
_patterns := make([]Pattern, 0)
for {
_pattern := p.Next()
if _pattern == nil {
return _patterns
}
_patterns = append(_patterns, _pattern)
}
} | go | func (p *parser) Parse() []Pattern {
// keep parsing until there's no more patterns
_patterns := make([]Pattern, 0)
for {
_pattern := p.Next()
if _pattern == nil {
return _patterns
}
_patterns = append(_patterns, _pattern)
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"Parse",
"(",
")",
"[",
"]",
"Pattern",
"{",
"// keep parsing until there's no more patterns",
"_patterns",
":=",
"make",
"(",
"[",
"]",
"Pattern",
",",
"0",
")",
"\n",
"for",
"{",
"_pattern",
":=",
"p",
".",
"Next",... | // Parse returns all well-formed .gitignore Patterns contained within the
// parser stream. Parsing will terminate at the end of the stream, or if
// the parser error handler returns false. | [
"Parse",
"returns",
"all",
"well",
"-",
"formed",
".",
"gitignore",
"Patterns",
"contained",
"within",
"the",
"parser",
"stream",
".",
"Parsing",
"will",
"terminate",
"at",
"the",
"end",
"of",
"the",
"stream",
"or",
"if",
"the",
"parser",
"error",
"handler",... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L45-L55 |
16,890 | denormal/go-gitignore | parser.go | Next | func (p *parser) Next() Pattern {
// keep searching until we find the next pattern, or until we
// reach the end of the file
for {
_token, _err := p.next()
if _err != nil {
if !p.errors(_err) {
return nil
}
// we got an error from the lexer, so skip the remainder
// of this line and try again from the next line
for _err != nil {
_err = p.skip()
if _err != nil {
if !p.errors(_err) {
return nil
}
}
}
continue
}
switch _token.Type {
// we're at the end of the file
case EOF:
return nil
// we have a blank line or comment
case EOL:
continue
case COMMENT:
continue
// otherwise, attempt to build the next pattern
default:
_pattern, _err := p.build(_token)
if _err != nil {
if !p.errors(_err) {
return nil
}
// we encountered an error parsing the retrieved tokens
// - skip to the end of the line
for _err != nil {
_err = p.skip()
if _err != nil {
if !p.errors(_err) {
return nil
}
}
}
// skip to the next token
continue
} else if _pattern != nil {
return _pattern
}
}
}
} | go | func (p *parser) Next() Pattern {
// keep searching until we find the next pattern, or until we
// reach the end of the file
for {
_token, _err := p.next()
if _err != nil {
if !p.errors(_err) {
return nil
}
// we got an error from the lexer, so skip the remainder
// of this line and try again from the next line
for _err != nil {
_err = p.skip()
if _err != nil {
if !p.errors(_err) {
return nil
}
}
}
continue
}
switch _token.Type {
// we're at the end of the file
case EOF:
return nil
// we have a blank line or comment
case EOL:
continue
case COMMENT:
continue
// otherwise, attempt to build the next pattern
default:
_pattern, _err := p.build(_token)
if _err != nil {
if !p.errors(_err) {
return nil
}
// we encountered an error parsing the retrieved tokens
// - skip to the end of the line
for _err != nil {
_err = p.skip()
if _err != nil {
if !p.errors(_err) {
return nil
}
}
}
// skip to the next token
continue
} else if _pattern != nil {
return _pattern
}
}
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"Next",
"(",
")",
"Pattern",
"{",
"// keep searching until we find the next pattern, or until we",
"// reach the end of the file",
"for",
"{",
"_token",
",",
"_err",
":=",
"p",
".",
"next",
"(",
")",
"\n",
"if",
"_err",
"!="... | // Next returns the next well-formed .gitignore Pattern from the parser stream.
// If an error is encountered, and the error handler is either not defined, or
// returns true, Next will skip to the end of the current line and attempt to
// parse the next Pattern. If the error handler returns false, or the parser
// reaches the end of the stream, Next returns nil. | [
"Next",
"returns",
"the",
"next",
"well",
"-",
"formed",
".",
"gitignore",
"Pattern",
"from",
"the",
"parser",
"stream",
".",
"If",
"an",
"error",
"is",
"encountered",
"and",
"the",
"error",
"handler",
"is",
"either",
"not",
"defined",
"or",
"returns",
"tr... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L62-L122 |
16,891 | denormal/go-gitignore | parser.go | Position | func (p *parser) Position() Position {
// if we have any previously read tokens, then the token at
// the end of the "undo" list (most recently "undone") gives the
// position of the parser
_length := len(p._undo)
if _length != 0 {
return p._undo[_length-1].Position
}
// otherwise, return the position of the lexer
return p._lexer.Position()
} | go | func (p *parser) Position() Position {
// if we have any previously read tokens, then the token at
// the end of the "undo" list (most recently "undone") gives the
// position of the parser
_length := len(p._undo)
if _length != 0 {
return p._undo[_length-1].Position
}
// otherwise, return the position of the lexer
return p._lexer.Position()
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"Position",
"(",
")",
"Position",
"{",
"// if we have any previously read tokens, then the token at",
"// the end of the \"undo\" list (most recently \"undone\") gives the",
"// position of the parser",
"_length",
":=",
"len",
"(",
"p",
"."... | // Position returns the current position of the parser in the input stream. | [
"Position",
"returns",
"the",
"current",
"position",
"of",
"the",
"parser",
"in",
"the",
"input",
"stream",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L125-L136 |
16,892 | denormal/go-gitignore | parser.go | build | func (p *parser) build(t *Token) (Pattern, Error) {
// attempt to create a valid pattern
switch t.Type {
// we have a negated pattern
case NEGATION:
return p.negation(t)
// attempt to build a path specification
default:
return p.path(t)
}
} | go | func (p *parser) build(t *Token) (Pattern, Error) {
// attempt to create a valid pattern
switch t.Type {
// we have a negated pattern
case NEGATION:
return p.negation(t)
// attempt to build a path specification
default:
return p.path(t)
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"build",
"(",
"t",
"*",
"Token",
")",
"(",
"Pattern",
",",
"Error",
")",
"{",
"// attempt to create a valid pattern",
"switch",
"t",
".",
"Type",
"{",
"// we have a negated pattern",
"case",
"NEGATION",
":",
"return",
"p... | //
// private methods
//
// build attempts to build a well-formed .gitignore Pattern starting from the
// given Token t. An Error will be returned if the sequence of tokens returned
// by the Lexer does not represent a valid Pattern. | [
"private",
"methods",
"build",
"attempts",
"to",
"build",
"a",
"well",
"-",
"formed",
".",
"gitignore",
"Pattern",
"starting",
"from",
"the",
"given",
"Token",
"t",
".",
"An",
"Error",
"will",
"be",
"returned",
"if",
"the",
"sequence",
"of",
"tokens",
"ret... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L145-L156 |
16,893 | denormal/go-gitignore | parser.go | negation | func (p *parser) negation(t *Token) (Pattern, Error) {
// a negation appears before a path specification, so
// skip the negation token
_next, _err := p.next()
if _err != nil {
return nil, _err
}
// extract the sequence of tokens for this path
_tokens, _err := p.sequence(_next)
if _err != nil {
return nil, _err
}
// include the "negation" token at the front of the sequence
_tokens = append([]*Token{t}, _tokens...)
// return the Pattern instance
return NewPattern(_tokens), nil
} | go | func (p *parser) negation(t *Token) (Pattern, Error) {
// a negation appears before a path specification, so
// skip the negation token
_next, _err := p.next()
if _err != nil {
return nil, _err
}
// extract the sequence of tokens for this path
_tokens, _err := p.sequence(_next)
if _err != nil {
return nil, _err
}
// include the "negation" token at the front of the sequence
_tokens = append([]*Token{t}, _tokens...)
// return the Pattern instance
return NewPattern(_tokens), nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"negation",
"(",
"t",
"*",
"Token",
")",
"(",
"Pattern",
",",
"Error",
")",
"{",
"// a negation appears before a path specification, so",
"// skip the negation token",
"_next",
",",
"_err",
":=",
"p",
".",
"next",
"(",
")"... | // negation attempts to build a well-formed negated .gitignore Pattern starting
// from the negation Token t. As with build, negation returns an Error if the
// sequence of tokens returned by the Lexer does not represent a valid Pattern. | [
"negation",
"attempts",
"to",
"build",
"a",
"well",
"-",
"formed",
"negated",
".",
"gitignore",
"Pattern",
"starting",
"from",
"the",
"negation",
"Token",
"t",
".",
"As",
"with",
"build",
"negation",
"returns",
"an",
"Error",
"if",
"the",
"sequence",
"of",
... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L161-L180 |
16,894 | denormal/go-gitignore | parser.go | path | func (p *parser) path(t *Token) (Pattern, Error) {
// extract the sequence of tokens for this path
_tokens, _err := p.sequence(t)
if _err != nil {
return nil, _err
}
// remove trailing whitespace tokens
_length := len(_tokens)
for _length > 0 {
// if we have a non-whitespace token, we can stop
_length--
if _tokens[_length].Type != WHITESPACE {
break
}
// otherwise, truncate the token list
_tokens = _tokens[:_length]
}
// return the Pattern instance
return NewPattern(_tokens), nil
} | go | func (p *parser) path(t *Token) (Pattern, Error) {
// extract the sequence of tokens for this path
_tokens, _err := p.sequence(t)
if _err != nil {
return nil, _err
}
// remove trailing whitespace tokens
_length := len(_tokens)
for _length > 0 {
// if we have a non-whitespace token, we can stop
_length--
if _tokens[_length].Type != WHITESPACE {
break
}
// otherwise, truncate the token list
_tokens = _tokens[:_length]
}
// return the Pattern instance
return NewPattern(_tokens), nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"path",
"(",
"t",
"*",
"Token",
")",
"(",
"Pattern",
",",
"Error",
")",
"{",
"// extract the sequence of tokens for this path",
"_tokens",
",",
"_err",
":=",
"p",
".",
"sequence",
"(",
"t",
")",
"\n",
"if",
"_err",
... | // path attempts to build a well-formed .gitignore Pattern representing a path
// specification, starting with the Token t. If the sequence of tokens returned
// by the Lexer does not represent a valid Pattern, path returns an Error.
// Trailing whitespace is dropped from the sequence of pattern tokens. | [
"path",
"attempts",
"to",
"build",
"a",
"well",
"-",
"formed",
".",
"gitignore",
"Pattern",
"representing",
"a",
"path",
"specification",
"starting",
"with",
"the",
"Token",
"t",
".",
"If",
"the",
"sequence",
"of",
"tokens",
"returned",
"by",
"the",
"Lexer",... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L186-L208 |
16,895 | denormal/go-gitignore | parser.go | sequence | func (p *parser) sequence(t *Token) ([]*Token, Error) {
// extract the sequence of tokens for a valid path
// - this excludes the negation token, which is handled as
// a special case before sequence() is called
switch t.Type {
// the path starts with a separator
case SEPARATOR:
return p.separator(t)
// the path starts with the "any" pattern ("**")
case ANY:
return p.any(t)
// the path starts with whitespace, wildcard or a pattern
case WHITESPACE:
fallthrough
case PATTERN:
return p.pattern(t)
}
// otherwise, we have an invalid specification
p.undo(t)
return nil, p.err(InvalidPatternError)
} | go | func (p *parser) sequence(t *Token) ([]*Token, Error) {
// extract the sequence of tokens for a valid path
// - this excludes the negation token, which is handled as
// a special case before sequence() is called
switch t.Type {
// the path starts with a separator
case SEPARATOR:
return p.separator(t)
// the path starts with the "any" pattern ("**")
case ANY:
return p.any(t)
// the path starts with whitespace, wildcard or a pattern
case WHITESPACE:
fallthrough
case PATTERN:
return p.pattern(t)
}
// otherwise, we have an invalid specification
p.undo(t)
return nil, p.err(InvalidPatternError)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"sequence",
"(",
"t",
"*",
"Token",
")",
"(",
"[",
"]",
"*",
"Token",
",",
"Error",
")",
"{",
"// extract the sequence of tokens for a valid path",
"// - this excludes the negation token, which is handled as",
"// a spec... | // sequence attempts to extract a well-formed Token sequence from the Lexer
// representing a .gitignore Pattern. sequence returns an Error if the
// retrieved sequence of tokens does not represent a valid Pattern. | [
"sequence",
"attempts",
"to",
"extract",
"a",
"well",
"-",
"formed",
"Token",
"sequence",
"from",
"the",
"Lexer",
"representing",
"a",
".",
"gitignore",
"Pattern",
".",
"sequence",
"returns",
"an",
"Error",
"if",
"the",
"retrieved",
"sequence",
"of",
"tokens",... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L213-L236 |
16,896 | denormal/go-gitignore | parser.go | pattern | func (p *parser) pattern(t *Token) ([]*Token, Error) {
// build the list of tokens that may appear after a pattern
_tokens := []*Token{t}
_token, _err := p.next()
if _err != nil {
return _tokens, _err
}
// what tokens are we allowed to have follow a pattern?
var _next []*Token
switch _token.Type {
case SEPARATOR:
_next, _err = p.separator(_token)
return append(_tokens, _next...), _err
case WHITESPACE:
fallthrough
case PATTERN:
_next, _err = p.pattern(_token)
return append(_tokens, _next...), _err
// if we encounter end of line or file we are done
case EOL:
fallthrough
case EOF:
return _tokens, nil
}
// any other token is invalid
p.undo(_token)
return _tokens, p.err(InvalidPatternError)
} | go | func (p *parser) pattern(t *Token) ([]*Token, Error) {
// build the list of tokens that may appear after a pattern
_tokens := []*Token{t}
_token, _err := p.next()
if _err != nil {
return _tokens, _err
}
// what tokens are we allowed to have follow a pattern?
var _next []*Token
switch _token.Type {
case SEPARATOR:
_next, _err = p.separator(_token)
return append(_tokens, _next...), _err
case WHITESPACE:
fallthrough
case PATTERN:
_next, _err = p.pattern(_token)
return append(_tokens, _next...), _err
// if we encounter end of line or file we are done
case EOL:
fallthrough
case EOF:
return _tokens, nil
}
// any other token is invalid
p.undo(_token)
return _tokens, p.err(InvalidPatternError)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"pattern",
"(",
"t",
"*",
"Token",
")",
"(",
"[",
"]",
"*",
"Token",
",",
"Error",
")",
"{",
"// build the list of tokens that may appear after a pattern",
"_tokens",
":=",
"[",
"]",
"*",
"Token",
"{",
"t",
"}",
"\n"... | // pattern attempts to retrieve a valid sequence of tokens that may appear
// after the path pattern Token t. An Error is returned if the sequence if
// tokens is not valid, or if there is an error extracting tokens from the
// input stream. | [
"pattern",
"attempts",
"to",
"retrieve",
"a",
"valid",
"sequence",
"of",
"tokens",
"that",
"may",
"appear",
"after",
"the",
"path",
"pattern",
"Token",
"t",
".",
"An",
"Error",
"is",
"returned",
"if",
"the",
"sequence",
"if",
"tokens",
"is",
"not",
"valid"... | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L324-L355 |
16,897 | denormal/go-gitignore | parser.go | eol | func (p *parser) eol() Error {
// are we at the end of the line?
_token, _err := p.next()
if _err != nil {
return _err
}
// have we encountered whitespace only?
switch _token.Type {
// if we're at the end of the line or file, we're done
case EOL:
fallthrough
case EOF:
p.undo(_token)
return nil
}
// otherwise, we have an invalid pattern
p.undo(_token)
return p.err(InvalidPatternError)
} | go | func (p *parser) eol() Error {
// are we at the end of the line?
_token, _err := p.next()
if _err != nil {
return _err
}
// have we encountered whitespace only?
switch _token.Type {
// if we're at the end of the line or file, we're done
case EOL:
fallthrough
case EOF:
p.undo(_token)
return nil
}
// otherwise, we have an invalid pattern
p.undo(_token)
return p.err(InvalidPatternError)
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"eol",
"(",
")",
"Error",
"{",
"// are we at the end of the line?",
"_token",
",",
"_err",
":=",
"p",
".",
"next",
"(",
")",
"\n",
"if",
"_err",
"!=",
"nil",
"{",
"return",
"_err",
"\n",
"}",
"\n\n",
"// have we en... | // eol attempts to consume the next Lexer token to read the end of line or end
// of file. If a EOL or EOF is not reached , eol will return an error. | [
"eol",
"attempts",
"to",
"consume",
"the",
"next",
"Lexer",
"token",
"to",
"read",
"the",
"end",
"of",
"line",
"or",
"end",
"of",
"file",
".",
"If",
"a",
"EOL",
"or",
"EOF",
"is",
"not",
"reached",
"eol",
"will",
"return",
"an",
"error",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L359-L379 |
16,898 | denormal/go-gitignore | parser.go | next | func (p *parser) next() (*Token, Error) {
// do we have any previously read tokens?
_length := len(p._undo)
if _length > 0 {
_token := p._undo[_length-1]
p._undo = p._undo[:_length-1]
return _token, nil
}
// otherwise, attempt to retrieve the next token from the lexer
return p._lexer.Next()
} | go | func (p *parser) next() (*Token, Error) {
// do we have any previously read tokens?
_length := len(p._undo)
if _length > 0 {
_token := p._undo[_length-1]
p._undo = p._undo[:_length-1]
return _token, nil
}
// otherwise, attempt to retrieve the next token from the lexer
return p._lexer.Next()
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"next",
"(",
")",
"(",
"*",
"Token",
",",
"Error",
")",
"{",
"// do we have any previously read tokens?",
"_length",
":=",
"len",
"(",
"p",
".",
"_undo",
")",
"\n",
"if",
"_length",
">",
"0",
"{",
"_token",
":=",
... | // next returns the next token from the Lexer, or an error if there is a
// problem reading from the input stream. | [
"next",
"returns",
"the",
"next",
"token",
"from",
"the",
"Lexer",
"or",
"an",
"error",
"if",
"there",
"is",
"a",
"problem",
"reading",
"from",
"the",
"input",
"stream",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L383-L394 |
16,899 | denormal/go-gitignore | parser.go | skip | func (p *parser) skip() Error {
// skip to the next end of line or end of file token
for {
_token, _err := p.next()
if _err != nil {
return _err
}
// if we have an end of line or file token, then we can stop
switch _token.Type {
case EOL:
fallthrough
case EOF:
return nil
}
}
} | go | func (p *parser) skip() Error {
// skip to the next end of line or end of file token
for {
_token, _err := p.next()
if _err != nil {
return _err
}
// if we have an end of line or file token, then we can stop
switch _token.Type {
case EOL:
fallthrough
case EOF:
return nil
}
}
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"skip",
"(",
")",
"Error",
"{",
"// skip to the next end of line or end of file token",
"for",
"{",
"_token",
",",
"_err",
":=",
"p",
".",
"next",
"(",
")",
"\n",
"if",
"_err",
"!=",
"nil",
"{",
"return",
"_err",
"\n... | // skip reads Tokens from the input until the end of line or end of file is
// reached. If there is a problem reading tokens, an Error is returned. | [
"skip",
"reads",
"Tokens",
"from",
"the",
"input",
"until",
"the",
"end",
"of",
"line",
"or",
"end",
"of",
"file",
"is",
"reached",
".",
"If",
"there",
"is",
"a",
"problem",
"reading",
"tokens",
"an",
"Error",
"is",
"returned",
"."
] | ae8ad1d07817b3d3b49cabb21559a3f493a357a3 | https://github.com/denormal/go-gitignore/blob/ae8ad1d07817b3d3b49cabb21559a3f493a357a3/parser.go#L398-L414 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.