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
157,300
lucas-clemente/quic-go
internal/wire/extended_header.go
GetLength
func (h *ExtendedHeader) GetLength(v protocol.VersionNumber) protocol.ByteCount { if h.IsLongHeader { length := 1 /* type byte */ + 4 /* version */ + 1 /* conn id len byte */ + protocol.ByteCount(h.DestConnectionID.Len()+h.SrcConnectionID.Len()) + protocol.ByteCount(h.PacketNumberLen) + utils.VarIntLen(uint64(h.Length)) if h.Type == protocol.PacketTypeInitial { length += utils.VarIntLen(uint64(len(h.Token))) + protocol.ByteCount(len(h.Token)) } return length } length := protocol.ByteCount(1 /* type byte */ + h.DestConnectionID.Len()) length += protocol.ByteCount(h.PacketNumberLen) return length }
go
func (h *ExtendedHeader) GetLength(v protocol.VersionNumber) protocol.ByteCount { if h.IsLongHeader { length := 1 /* type byte */ + 4 /* version */ + 1 /* conn id len byte */ + protocol.ByteCount(h.DestConnectionID.Len()+h.SrcConnectionID.Len()) + protocol.ByteCount(h.PacketNumberLen) + utils.VarIntLen(uint64(h.Length)) if h.Type == protocol.PacketTypeInitial { length += utils.VarIntLen(uint64(len(h.Token))) + protocol.ByteCount(len(h.Token)) } return length } length := protocol.ByteCount(1 /* type byte */ + h.DestConnectionID.Len()) length += protocol.ByteCount(h.PacketNumberLen) return length }
[ "func", "(", "h", "*", "ExtendedHeader", ")", "GetLength", "(", "v", "protocol", ".", "VersionNumber", ")", "protocol", ".", "ByteCount", "{", "if", "h", ".", "IsLongHeader", "{", "length", ":=", "1", "/* type byte */", "+", "4", "/* version */", "+", "1",...
// GetLength determines the length of the Header.
[ "GetLength", "determines", "the", "length", "of", "the", "Header", "." ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/wire/extended_header.go#L148-L160
157,301
lucas-clemente/quic-go
internal/wire/extended_header.go
Log
func (h *ExtendedHeader) Log(logger utils.Logger) { if h.IsLongHeader { var token string if h.Type == protocol.PacketTypeInitial || h.Type == protocol.PacketTypeRetry { if len(h.Token) == 0 { token = "Token: (empty), " } else { token = fmt.Sprintf("Token: %#x, ", h.Token) } if h.Type == protocol.PacketTypeRetry { logger.Debugf("\tLong Header{Type: %s, DestConnectionID: %s, SrcConnectionID: %s, %sOrigDestConnectionID: %s, Version: %s}", h.Type, h.DestConnectionID, h.SrcConnectionID, token, h.OrigDestConnectionID, h.Version) return } } logger.Debugf("\tLong Header{Type: %s, DestConnectionID: %s, SrcConnectionID: %s, %sPacketNumber: %#x, PacketNumberLen: %d, Length: %d, Version: %s}", h.Type, h.DestConnectionID, h.SrcConnectionID, token, h.PacketNumber, h.PacketNumberLen, h.Length, h.Version) } else { logger.Debugf("\tShort Header{DestConnectionID: %s, PacketNumber: %#x, PacketNumberLen: %d, KeyPhase: %d}", h.DestConnectionID, h.PacketNumber, h.PacketNumberLen, h.KeyPhase) } }
go
func (h *ExtendedHeader) Log(logger utils.Logger) { if h.IsLongHeader { var token string if h.Type == protocol.PacketTypeInitial || h.Type == protocol.PacketTypeRetry { if len(h.Token) == 0 { token = "Token: (empty), " } else { token = fmt.Sprintf("Token: %#x, ", h.Token) } if h.Type == protocol.PacketTypeRetry { logger.Debugf("\tLong Header{Type: %s, DestConnectionID: %s, SrcConnectionID: %s, %sOrigDestConnectionID: %s, Version: %s}", h.Type, h.DestConnectionID, h.SrcConnectionID, token, h.OrigDestConnectionID, h.Version) return } } logger.Debugf("\tLong Header{Type: %s, DestConnectionID: %s, SrcConnectionID: %s, %sPacketNumber: %#x, PacketNumberLen: %d, Length: %d, Version: %s}", h.Type, h.DestConnectionID, h.SrcConnectionID, token, h.PacketNumber, h.PacketNumberLen, h.Length, h.Version) } else { logger.Debugf("\tShort Header{DestConnectionID: %s, PacketNumber: %#x, PacketNumberLen: %d, KeyPhase: %d}", h.DestConnectionID, h.PacketNumber, h.PacketNumberLen, h.KeyPhase) } }
[ "func", "(", "h", "*", "ExtendedHeader", ")", "Log", "(", "logger", "utils", ".", "Logger", ")", "{", "if", "h", ".", "IsLongHeader", "{", "var", "token", "string", "\n", "if", "h", ".", "Type", "==", "protocol", ".", "PacketTypeInitial", "||", "h", ...
// Log logs the Header
[ "Log", "logs", "the", "Header" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/wire/extended_header.go#L163-L181
157,302
lucas-clemente/quic-go
internal/protocol/packet_number.go
DecodePacketNumber
func DecodePacketNumber( packetNumberLength PacketNumberLen, lastPacketNumber PacketNumber, wirePacketNumber PacketNumber, ) PacketNumber { var epochDelta PacketNumber switch packetNumberLength { case PacketNumberLen1: epochDelta = PacketNumber(1) << 8 case PacketNumberLen2: epochDelta = PacketNumber(1) << 16 case PacketNumberLen3: epochDelta = PacketNumber(1) << 24 case PacketNumberLen4: epochDelta = PacketNumber(1) << 32 } epoch := lastPacketNumber & ^(epochDelta - 1) prevEpochBegin := epoch - epochDelta nextEpochBegin := epoch + epochDelta return closestTo( lastPacketNumber+1, epoch+wirePacketNumber, closestTo(lastPacketNumber+1, prevEpochBegin+wirePacketNumber, nextEpochBegin+wirePacketNumber), ) }
go
func DecodePacketNumber( packetNumberLength PacketNumberLen, lastPacketNumber PacketNumber, wirePacketNumber PacketNumber, ) PacketNumber { var epochDelta PacketNumber switch packetNumberLength { case PacketNumberLen1: epochDelta = PacketNumber(1) << 8 case PacketNumberLen2: epochDelta = PacketNumber(1) << 16 case PacketNumberLen3: epochDelta = PacketNumber(1) << 24 case PacketNumberLen4: epochDelta = PacketNumber(1) << 32 } epoch := lastPacketNumber & ^(epochDelta - 1) prevEpochBegin := epoch - epochDelta nextEpochBegin := epoch + epochDelta return closestTo( lastPacketNumber+1, epoch+wirePacketNumber, closestTo(lastPacketNumber+1, prevEpochBegin+wirePacketNumber, nextEpochBegin+wirePacketNumber), ) }
[ "func", "DecodePacketNumber", "(", "packetNumberLength", "PacketNumberLen", ",", "lastPacketNumber", "PacketNumber", ",", "wirePacketNumber", "PacketNumber", ",", ")", "PacketNumber", "{", "var", "epochDelta", "PacketNumber", "\n", "switch", "packetNumberLength", "{", "ca...
// DecodePacketNumber calculates the packet number based on the received packet number, its length and the last seen packet number
[ "DecodePacketNumber", "calculates", "the", "packet", "number", "based", "on", "the", "received", "packet", "number", "its", "length", "and", "the", "last", "seen", "packet", "number" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/protocol/packet_number.go#L20-L44
157,303
lucas-clemente/quic-go
internal/protocol/packet_number.go
GetPacketNumberLengthForHeader
func GetPacketNumberLengthForHeader(packetNumber, leastUnacked PacketNumber) PacketNumberLen { diff := uint64(packetNumber - leastUnacked) if diff < (1 << (16 - 1)) { return PacketNumberLen2 } if diff < (1 << (24 - 1)) { return PacketNumberLen3 } return PacketNumberLen4 }
go
func GetPacketNumberLengthForHeader(packetNumber, leastUnacked PacketNumber) PacketNumberLen { diff := uint64(packetNumber - leastUnacked) if diff < (1 << (16 - 1)) { return PacketNumberLen2 } if diff < (1 << (24 - 1)) { return PacketNumberLen3 } return PacketNumberLen4 }
[ "func", "GetPacketNumberLengthForHeader", "(", "packetNumber", ",", "leastUnacked", "PacketNumber", ")", "PacketNumberLen", "{", "diff", ":=", "uint64", "(", "packetNumber", "-", "leastUnacked", ")", "\n", "if", "diff", "<", "(", "1", "<<", "(", "16", "-", "1"...
// GetPacketNumberLengthForHeader gets the length of the packet number for the public header // it never chooses a PacketNumberLen of 1 byte, since this is too short under certain circumstances
[ "GetPacketNumberLengthForHeader", "gets", "the", "length", "of", "the", "packet", "number", "for", "the", "public", "header", "it", "never", "chooses", "a", "PacketNumberLen", "of", "1", "byte", "since", "this", "is", "too", "short", "under", "certain", "circums...
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/protocol/packet_number.go#L62-L71
157,304
lucas-clemente/quic-go
internal/protocol/packet_number.go
GetPacketNumberLength
func GetPacketNumberLength(packetNumber PacketNumber) PacketNumberLen { if packetNumber < (1 << (uint8(PacketNumberLen1) * 8)) { return PacketNumberLen1 } if packetNumber < (1 << (uint8(PacketNumberLen2) * 8)) { return PacketNumberLen2 } if packetNumber < (1 << (uint8(PacketNumberLen3) * 8)) { return PacketNumberLen3 } return PacketNumberLen4 }
go
func GetPacketNumberLength(packetNumber PacketNumber) PacketNumberLen { if packetNumber < (1 << (uint8(PacketNumberLen1) * 8)) { return PacketNumberLen1 } if packetNumber < (1 << (uint8(PacketNumberLen2) * 8)) { return PacketNumberLen2 } if packetNumber < (1 << (uint8(PacketNumberLen3) * 8)) { return PacketNumberLen3 } return PacketNumberLen4 }
[ "func", "GetPacketNumberLength", "(", "packetNumber", "PacketNumber", ")", "PacketNumberLen", "{", "if", "packetNumber", "<", "(", "1", "<<", "(", "uint8", "(", "PacketNumberLen1", ")", "*", "8", ")", ")", "{", "return", "PacketNumberLen1", "\n", "}", "\n", ...
// GetPacketNumberLength gets the minimum length needed to fully represent the packet number
[ "GetPacketNumberLength", "gets", "the", "minimum", "length", "needed", "to", "fully", "represent", "the", "packet", "number" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/protocol/packet_number.go#L74-L85
157,305
lucas-clemente/quic-go
internal/handshake/tls_extension_handler.go
newExtensionHandler
func newExtensionHandler(params []byte, pers protocol.Perspective) tlsExtensionHandler { return &extensionHandler{ ourParams: params, paramsChan: make(chan []byte), perspective: pers, } }
go
func newExtensionHandler(params []byte, pers protocol.Perspective) tlsExtensionHandler { return &extensionHandler{ ourParams: params, paramsChan: make(chan []byte), perspective: pers, } }
[ "func", "newExtensionHandler", "(", "params", "[", "]", "byte", ",", "pers", "protocol", ".", "Perspective", ")", "tlsExtensionHandler", "{", "return", "&", "extensionHandler", "{", "ourParams", ":", "params", ",", "paramsChan", ":", "make", "(", "chan", "[", ...
// newExtensionHandler creates a new extension handler
[ "newExtensionHandler", "creates", "a", "new", "extension", "handler" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/handshake/tls_extension_handler.go#L20-L26
157,306
lucas-clemente/quic-go
internal/ackhandler/sent_packet_handler.go
NewSentPacketHandler
func NewSentPacketHandler( initialPacketNumber protocol.PacketNumber, rttStats *congestion.RTTStats, logger utils.Logger, ) SentPacketHandler { congestion := congestion.NewCubicSender( congestion.DefaultClock{}, rttStats, false, /* don't use reno since chromium doesn't (why?) */ protocol.InitialCongestionWindow, protocol.DefaultMaxCongestionWindow, ) return &sentPacketHandler{ initialPackets: newPacketNumberSpace(initialPacketNumber), handshakePackets: newPacketNumberSpace(0), oneRTTPackets: newPacketNumberSpace(0), rttStats: rttStats, congestion: congestion, logger: logger, } }
go
func NewSentPacketHandler( initialPacketNumber protocol.PacketNumber, rttStats *congestion.RTTStats, logger utils.Logger, ) SentPacketHandler { congestion := congestion.NewCubicSender( congestion.DefaultClock{}, rttStats, false, /* don't use reno since chromium doesn't (why?) */ protocol.InitialCongestionWindow, protocol.DefaultMaxCongestionWindow, ) return &sentPacketHandler{ initialPackets: newPacketNumberSpace(initialPacketNumber), handshakePackets: newPacketNumberSpace(0), oneRTTPackets: newPacketNumberSpace(0), rttStats: rttStats, congestion: congestion, logger: logger, } }
[ "func", "NewSentPacketHandler", "(", "initialPacketNumber", "protocol", ".", "PacketNumber", ",", "rttStats", "*", "congestion", ".", "RTTStats", ",", "logger", "utils", ".", "Logger", ",", ")", "SentPacketHandler", "{", "congestion", ":=", "congestion", ".", "New...
// NewSentPacketHandler creates a new sentPacketHandler
[ "NewSentPacketHandler", "creates", "a", "new", "sentPacketHandler" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/ackhandler/sent_packet_handler.go#L82-L103
157,307
lucas-clemente/quic-go
stream.go
newStream
func newStream(streamID protocol.StreamID, sender streamSender, flowController flowcontrol.StreamFlowController, version protocol.VersionNumber, ) *stream { s := &stream{sender: sender, version: version} senderForSendStream := &uniStreamSender{ streamSender: sender, onStreamCompletedImpl: func() { s.completedMutex.Lock() s.sendStreamCompleted = true s.checkIfCompleted() s.completedMutex.Unlock() }, } s.sendStream = *newSendStream(streamID, senderForSendStream, flowController, version) senderForReceiveStream := &uniStreamSender{ streamSender: sender, onStreamCompletedImpl: func() { s.completedMutex.Lock() s.receiveStreamCompleted = true s.checkIfCompleted() s.completedMutex.Unlock() }, } s.receiveStream = *newReceiveStream(streamID, senderForReceiveStream, flowController, version) return s }
go
func newStream(streamID protocol.StreamID, sender streamSender, flowController flowcontrol.StreamFlowController, version protocol.VersionNumber, ) *stream { s := &stream{sender: sender, version: version} senderForSendStream := &uniStreamSender{ streamSender: sender, onStreamCompletedImpl: func() { s.completedMutex.Lock() s.sendStreamCompleted = true s.checkIfCompleted() s.completedMutex.Unlock() }, } s.sendStream = *newSendStream(streamID, senderForSendStream, flowController, version) senderForReceiveStream := &uniStreamSender{ streamSender: sender, onStreamCompletedImpl: func() { s.completedMutex.Lock() s.receiveStreamCompleted = true s.checkIfCompleted() s.completedMutex.Unlock() }, } s.receiveStream = *newReceiveStream(streamID, senderForReceiveStream, flowController, version) return s }
[ "func", "newStream", "(", "streamID", "protocol", ".", "StreamID", ",", "sender", "streamSender", ",", "flowController", "flowcontrol", ".", "StreamFlowController", ",", "version", "protocol", ".", "VersionNumber", ",", ")", "*", "stream", "{", "s", ":=", "&", ...
// newStream creates a new Stream
[ "newStream", "creates", "a", "new", "Stream" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/stream.go#L97-L124
157,308
lucas-clemente/quic-go
stream.go
checkIfCompleted
func (s *stream) checkIfCompleted() { if s.sendStreamCompleted && s.receiveStreamCompleted { s.sender.onStreamCompleted(s.StreamID()) } }
go
func (s *stream) checkIfCompleted() { if s.sendStreamCompleted && s.receiveStreamCompleted { s.sender.onStreamCompleted(s.StreamID()) } }
[ "func", "(", "s", "*", "stream", ")", "checkIfCompleted", "(", ")", "{", "if", "s", ".", "sendStreamCompleted", "&&", "s", ".", "receiveStreamCompleted", "{", "s", ".", "sender", ".", "onStreamCompleted", "(", "s", ".", "StreamID", "(", ")", ")", "\n", ...
// checkIfCompleted is called from the uniStreamSender, when one of the stream halves is completed. // It makes sure that the onStreamCompleted callback is only called if both receive and send side have completed.
[ "checkIfCompleted", "is", "called", "from", "the", "uniStreamSender", "when", "one", "of", "the", "stream", "halves", "is", "completed", ".", "It", "makes", "sure", "that", "the", "onStreamCompleted", "callback", "is", "only", "called", "if", "both", "receive", ...
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/stream.go#L159-L163
157,309
lucas-clemente/quic-go
packet_packer.go
PackConnectionClose
func (p *packetPacker) PackConnectionClose(ccf *wire.ConnectionCloseFrame) (*packedPacket, error) { payload := payload{ frames: []wire.Frame{ccf}, length: ccf.Length(p.version), } encLevel, sealer := p.cryptoSetup.GetSealer() header := p.getHeader(encLevel) return p.writeAndSealPacket(header, payload, encLevel, sealer) }
go
func (p *packetPacker) PackConnectionClose(ccf *wire.ConnectionCloseFrame) (*packedPacket, error) { payload := payload{ frames: []wire.Frame{ccf}, length: ccf.Length(p.version), } encLevel, sealer := p.cryptoSetup.GetSealer() header := p.getHeader(encLevel) return p.writeAndSealPacket(header, payload, encLevel, sealer) }
[ "func", "(", "p", "*", "packetPacker", ")", "PackConnectionClose", "(", "ccf", "*", "wire", ".", "ConnectionCloseFrame", ")", "(", "*", "packedPacket", ",", "error", ")", "{", "payload", ":=", "payload", "{", "frames", ":", "[", "]", "wire", ".", "Frame"...
// PackConnectionClose packs a packet that ONLY contains a ConnectionCloseFrame
[ "PackConnectionClose", "packs", "a", "packet", "that", "ONLY", "contains", "a", "ConnectionCloseFrame" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/packet_packer.go#L161-L169
157,310
lucas-clemente/quic-go
packet_packer.go
PackPacket
func (p *packetPacker) PackPacket() (*packedPacket, error) { packet, err := p.maybePackCryptoPacket() if err != nil { return nil, err } if packet != nil { return packet, nil } encLevel, sealer := p.cryptoSetup.GetSealer() header := p.getHeader(encLevel) headerLen := header.GetLength(p.version) if err != nil { return nil, err } maxSize := p.maxPacketSize - protocol.ByteCount(sealer.Overhead()) - headerLen payload, err := p.composeNextPacket(maxSize) if err != nil { return nil, err } // check if we have anything to send if len(payload.frames) == 0 && payload.ack == nil { return nil, nil } if len(payload.frames) == 0 { // the packet only contains an ACK if p.numNonAckElicitingAcks >= protocol.MaxNonAckElicitingAcks { ping := &wire.PingFrame{} payload.frames = append(payload.frames, ping) payload.length += ping.Length(p.version) p.numNonAckElicitingAcks = 0 } else { p.numNonAckElicitingAcks++ } } else { p.numNonAckElicitingAcks = 0 } return p.writeAndSealPacket(header, payload, encLevel, sealer) }
go
func (p *packetPacker) PackPacket() (*packedPacket, error) { packet, err := p.maybePackCryptoPacket() if err != nil { return nil, err } if packet != nil { return packet, nil } encLevel, sealer := p.cryptoSetup.GetSealer() header := p.getHeader(encLevel) headerLen := header.GetLength(p.version) if err != nil { return nil, err } maxSize := p.maxPacketSize - protocol.ByteCount(sealer.Overhead()) - headerLen payload, err := p.composeNextPacket(maxSize) if err != nil { return nil, err } // check if we have anything to send if len(payload.frames) == 0 && payload.ack == nil { return nil, nil } if len(payload.frames) == 0 { // the packet only contains an ACK if p.numNonAckElicitingAcks >= protocol.MaxNonAckElicitingAcks { ping := &wire.PingFrame{} payload.frames = append(payload.frames, ping) payload.length += ping.Length(p.version) p.numNonAckElicitingAcks = 0 } else { p.numNonAckElicitingAcks++ } } else { p.numNonAckElicitingAcks = 0 } return p.writeAndSealPacket(header, payload, encLevel, sealer) }
[ "func", "(", "p", "*", "packetPacker", ")", "PackPacket", "(", ")", "(", "*", "packedPacket", ",", "error", ")", "{", "packet", ",", "err", ":=", "p", ".", "maybePackCryptoPacket", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", ...
// PackPacket packs a new packet // the other controlFrames are sent in the next packet, but might be queued and sent in the next packet if the packet would overflow MaxPacketSize otherwise
[ "PackPacket", "packs", "a", "new", "packet", "the", "other", "controlFrames", "are", "sent", "in", "the", "next", "packet", "but", "might", "be", "queued", "and", "sent", "in", "the", "next", "packet", "if", "the", "packet", "would", "overflow", "MaxPacketSi...
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/packet_packer.go#L261-L301
157,311
lucas-clemente/quic-go
internal/ackhandler/received_packet_history.go
ReceivedPacket
func (h *receivedPacketHistory) ReceivedPacket(p protocol.PacketNumber) error { if h.ranges.Len() >= protocol.MaxTrackedReceivedAckRanges { return errTooManyOutstandingReceivedAckRanges } if h.ranges.Len() == 0 { h.ranges.PushBack(utils.PacketInterval{Start: p, End: p}) return nil } for el := h.ranges.Back(); el != nil; el = el.Prev() { // p already included in an existing range. Nothing to do here if p >= el.Value.Start && p <= el.Value.End { return nil } var rangeExtended bool if el.Value.End == p-1 { // extend a range at the end rangeExtended = true el.Value.End = p } else if el.Value.Start == p+1 { // extend a range at the beginning rangeExtended = true el.Value.Start = p } // if a range was extended (either at the beginning or at the end, maybe it is possible to merge two ranges into one) if rangeExtended { prev := el.Prev() if prev != nil && prev.Value.End+1 == el.Value.Start { // merge two ranges prev.Value.End = el.Value.End h.ranges.Remove(el) return nil } return nil // if the two ranges were not merge, we're done here } // create a new range at the end if p > el.Value.End { h.ranges.InsertAfter(utils.PacketInterval{Start: p, End: p}, el) return nil } } // create a new range at the beginning h.ranges.InsertBefore(utils.PacketInterval{Start: p, End: p}, h.ranges.Front()) return nil }
go
func (h *receivedPacketHistory) ReceivedPacket(p protocol.PacketNumber) error { if h.ranges.Len() >= protocol.MaxTrackedReceivedAckRanges { return errTooManyOutstandingReceivedAckRanges } if h.ranges.Len() == 0 { h.ranges.PushBack(utils.PacketInterval{Start: p, End: p}) return nil } for el := h.ranges.Back(); el != nil; el = el.Prev() { // p already included in an existing range. Nothing to do here if p >= el.Value.Start && p <= el.Value.End { return nil } var rangeExtended bool if el.Value.End == p-1 { // extend a range at the end rangeExtended = true el.Value.End = p } else if el.Value.Start == p+1 { // extend a range at the beginning rangeExtended = true el.Value.Start = p } // if a range was extended (either at the beginning or at the end, maybe it is possible to merge two ranges into one) if rangeExtended { prev := el.Prev() if prev != nil && prev.Value.End+1 == el.Value.Start { // merge two ranges prev.Value.End = el.Value.End h.ranges.Remove(el) return nil } return nil // if the two ranges were not merge, we're done here } // create a new range at the end if p > el.Value.End { h.ranges.InsertAfter(utils.PacketInterval{Start: p, End: p}, el) return nil } } // create a new range at the beginning h.ranges.InsertBefore(utils.PacketInterval{Start: p, End: p}, h.ranges.Front()) return nil }
[ "func", "(", "h", "*", "receivedPacketHistory", ")", "ReceivedPacket", "(", "p", "protocol", ".", "PacketNumber", ")", "error", "{", "if", "h", ".", "ranges", ".", "Len", "(", ")", ">=", "protocol", ".", "MaxTrackedReceivedAckRanges", "{", "return", "errTooM...
// ReceivedPacket registers a packet with PacketNumber p and updates the ranges
[ "ReceivedPacket", "registers", "a", "packet", "with", "PacketNumber", "p", "and", "updates", "the", "ranges" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/ackhandler/received_packet_history.go#L29-L76
157,312
lucas-clemente/quic-go
internal/ackhandler/received_packet_history.go
GetAckRanges
func (h *receivedPacketHistory) GetAckRanges() []wire.AckRange { if h.ranges.Len() == 0 { return nil } ackRanges := make([]wire.AckRange, h.ranges.Len()) i := 0 for el := h.ranges.Back(); el != nil; el = el.Prev() { ackRanges[i] = wire.AckRange{Smallest: el.Value.Start, Largest: el.Value.End} i++ } return ackRanges }
go
func (h *receivedPacketHistory) GetAckRanges() []wire.AckRange { if h.ranges.Len() == 0 { return nil } ackRanges := make([]wire.AckRange, h.ranges.Len()) i := 0 for el := h.ranges.Back(); el != nil; el = el.Prev() { ackRanges[i] = wire.AckRange{Smallest: el.Value.Start, Largest: el.Value.End} i++ } return ackRanges }
[ "func", "(", "h", "*", "receivedPacketHistory", ")", "GetAckRanges", "(", ")", "[", "]", "wire", ".", "AckRange", "{", "if", "h", ".", "ranges", ".", "Len", "(", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "ackRanges", ":=", "make", "(...
// GetAckRanges gets a slice of all AckRanges that can be used in an AckFrame
[ "GetAckRanges", "gets", "a", "slice", "of", "all", "AckRanges", "that", "can", "be", "used", "in", "an", "AckFrame" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/ackhandler/received_packet_history.go#L100-L112
157,313
lucas-clemente/quic-go
internal/congestion/prr_sender.go
OnPacketLost
func (p *PrrSender) OnPacketLost(priorInFlight protocol.ByteCount) { p.bytesSentSinceLoss = 0 p.bytesInFlightBeforeLoss = priorInFlight p.bytesDeliveredSinceLoss = 0 p.ackCountSinceLoss = 0 }
go
func (p *PrrSender) OnPacketLost(priorInFlight protocol.ByteCount) { p.bytesSentSinceLoss = 0 p.bytesInFlightBeforeLoss = priorInFlight p.bytesDeliveredSinceLoss = 0 p.ackCountSinceLoss = 0 }
[ "func", "(", "p", "*", "PrrSender", ")", "OnPacketLost", "(", "priorInFlight", "protocol", ".", "ByteCount", ")", "{", "p", ".", "bytesSentSinceLoss", "=", "0", "\n", "p", ".", "bytesInFlightBeforeLoss", "=", "priorInFlight", "\n", "p", ".", "bytesDeliveredSin...
// OnPacketLost should be called on the first loss that triggers a recovery // period and all other methods in this class should only be called when in // recovery.
[ "OnPacketLost", "should", "be", "called", "on", "the", "first", "loss", "that", "triggers", "a", "recovery", "period", "and", "all", "other", "methods", "in", "this", "class", "should", "only", "be", "called", "when", "in", "recovery", "." ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/congestion/prr_sender.go#L23-L28
157,314
lucas-clemente/quic-go
internal/congestion/prr_sender.go
OnPacketAcked
func (p *PrrSender) OnPacketAcked(ackedBytes protocol.ByteCount) { p.bytesDeliveredSinceLoss += ackedBytes p.ackCountSinceLoss++ }
go
func (p *PrrSender) OnPacketAcked(ackedBytes protocol.ByteCount) { p.bytesDeliveredSinceLoss += ackedBytes p.ackCountSinceLoss++ }
[ "func", "(", "p", "*", "PrrSender", ")", "OnPacketAcked", "(", "ackedBytes", "protocol", ".", "ByteCount", ")", "{", "p", ".", "bytesDeliveredSinceLoss", "+=", "ackedBytes", "\n", "p", ".", "ackCountSinceLoss", "++", "\n", "}" ]
// OnPacketAcked should be called after a packet was acked
[ "OnPacketAcked", "should", "be", "called", "after", "a", "packet", "was", "acked" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/congestion/prr_sender.go#L31-L34
157,315
lucas-clemente/quic-go
internal/congestion/prr_sender.go
CanSend
func (p *PrrSender) CanSend(congestionWindow, bytesInFlight, slowstartThreshold protocol.ByteCount) bool { // Return QuicTime::Zero In order to ensure limited transmit always works. if p.bytesSentSinceLoss == 0 || bytesInFlight < protocol.DefaultTCPMSS { return true } if congestionWindow > bytesInFlight { // During PRR-SSRB, limit outgoing packets to 1 extra MSS per ack, instead // of sending the entire available window. This prevents burst retransmits // when more packets are lost than the CWND reduction. // limit = MAX(prr_delivered - prr_out, DeliveredData) + MSS return p.bytesDeliveredSinceLoss+p.ackCountSinceLoss*protocol.DefaultTCPMSS > p.bytesSentSinceLoss } // Implement Proportional Rate Reduction (RFC6937). // Checks a simplified version of the PRR formula that doesn't use division: // AvailableSendWindow = // CEIL(prr_delivered * ssthresh / BytesInFlightAtLoss) - prr_sent return p.bytesDeliveredSinceLoss*slowstartThreshold > p.bytesSentSinceLoss*p.bytesInFlightBeforeLoss }
go
func (p *PrrSender) CanSend(congestionWindow, bytesInFlight, slowstartThreshold protocol.ByteCount) bool { // Return QuicTime::Zero In order to ensure limited transmit always works. if p.bytesSentSinceLoss == 0 || bytesInFlight < protocol.DefaultTCPMSS { return true } if congestionWindow > bytesInFlight { // During PRR-SSRB, limit outgoing packets to 1 extra MSS per ack, instead // of sending the entire available window. This prevents burst retransmits // when more packets are lost than the CWND reduction. // limit = MAX(prr_delivered - prr_out, DeliveredData) + MSS return p.bytesDeliveredSinceLoss+p.ackCountSinceLoss*protocol.DefaultTCPMSS > p.bytesSentSinceLoss } // Implement Proportional Rate Reduction (RFC6937). // Checks a simplified version of the PRR formula that doesn't use division: // AvailableSendWindow = // CEIL(prr_delivered * ssthresh / BytesInFlightAtLoss) - prr_sent return p.bytesDeliveredSinceLoss*slowstartThreshold > p.bytesSentSinceLoss*p.bytesInFlightBeforeLoss }
[ "func", "(", "p", "*", "PrrSender", ")", "CanSend", "(", "congestionWindow", ",", "bytesInFlight", ",", "slowstartThreshold", "protocol", ".", "ByteCount", ")", "bool", "{", "// Return QuicTime::Zero In order to ensure limited transmit always works.", "if", "p", ".", "b...
// CanSend returns if packets can be sent
[ "CanSend", "returns", "if", "packets", "can", "be", "sent" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/congestion/prr_sender.go#L37-L54
157,316
lucas-clemente/quic-go
internal/flowcontrol/base_flow_controller.go
IsNewlyBlocked
func (c *baseFlowController) IsNewlyBlocked() (bool, protocol.ByteCount) { if c.sendWindowSize() != 0 || c.sendWindow == c.lastBlockedAt { return false, 0 } c.lastBlockedAt = c.sendWindow return true, c.sendWindow }
go
func (c *baseFlowController) IsNewlyBlocked() (bool, protocol.ByteCount) { if c.sendWindowSize() != 0 || c.sendWindow == c.lastBlockedAt { return false, 0 } c.lastBlockedAt = c.sendWindow return true, c.sendWindow }
[ "func", "(", "c", "*", "baseFlowController", ")", "IsNewlyBlocked", "(", ")", "(", "bool", ",", "protocol", ".", "ByteCount", ")", "{", "if", "c", ".", "sendWindowSize", "(", ")", "!=", "0", "||", "c", ".", "sendWindow", "==", "c", ".", "lastBlockedAt"...
// IsNewlyBlocked says if it is newly blocked by flow control. // For every offset, it only returns true once. // If it is blocked, the offset is returned.
[ "IsNewlyBlocked", "says", "if", "it", "is", "newly", "blocked", "by", "flow", "control", ".", "For", "every", "offset", "it", "only", "returns", "true", "once", ".", "If", "it", "is", "blocked", "the", "offset", "is", "returned", "." ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/flowcontrol/base_flow_controller.go#L36-L42
157,317
lucas-clemente/quic-go
internal/flowcontrol/base_flow_controller.go
UpdateSendWindow
func (c *baseFlowController) UpdateSendWindow(offset protocol.ByteCount) { if offset > c.sendWindow { c.sendWindow = offset } }
go
func (c *baseFlowController) UpdateSendWindow(offset protocol.ByteCount) { if offset > c.sendWindow { c.sendWindow = offset } }
[ "func", "(", "c", "*", "baseFlowController", ")", "UpdateSendWindow", "(", "offset", "protocol", ".", "ByteCount", ")", "{", "if", "offset", ">", "c", ".", "sendWindow", "{", "c", ".", "sendWindow", "=", "offset", "\n", "}", "\n", "}" ]
// UpdateSendWindow should be called after receiving a WindowUpdateFrame // it returns true if the window was actually updated
[ "UpdateSendWindow", "should", "be", "called", "after", "receiving", "a", "WindowUpdateFrame", "it", "returns", "true", "if", "the", "window", "was", "actually", "updated" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/flowcontrol/base_flow_controller.go#L50-L54
157,318
lucas-clemente/quic-go
internal/flowcontrol/base_flow_controller.go
getWindowUpdate
func (c *baseFlowController) getWindowUpdate() protocol.ByteCount { if !c.hasWindowUpdate() { return 0 } c.maybeAdjustWindowSize() c.receiveWindow = c.bytesRead + c.receiveWindowSize return c.receiveWindow }
go
func (c *baseFlowController) getWindowUpdate() protocol.ByteCount { if !c.hasWindowUpdate() { return 0 } c.maybeAdjustWindowSize() c.receiveWindow = c.bytesRead + c.receiveWindowSize return c.receiveWindow }
[ "func", "(", "c", "*", "baseFlowController", ")", "getWindowUpdate", "(", ")", "protocol", ".", "ByteCount", "{", "if", "!", "c", ".", "hasWindowUpdate", "(", ")", "{", "return", "0", "\n", "}", "\n\n", "c", ".", "maybeAdjustWindowSize", "(", ")", "\n", ...
// getWindowUpdate updates the receive window, if necessary // it returns the new offset
[ "getWindowUpdate", "updates", "the", "receive", "window", "if", "necessary", "it", "returns", "the", "new", "offset" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/flowcontrol/base_flow_controller.go#L84-L92
157,319
lucas-clemente/quic-go
internal/protocol/connection_id.go
GenerateConnectionID
func GenerateConnectionID(len int) (ConnectionID, error) { b := make([]byte, len) if _, err := rand.Read(b); err != nil { return nil, err } return ConnectionID(b), nil }
go
func GenerateConnectionID(len int) (ConnectionID, error) { b := make([]byte, len) if _, err := rand.Read(b); err != nil { return nil, err } return ConnectionID(b), nil }
[ "func", "GenerateConnectionID", "(", "len", "int", ")", "(", "ConnectionID", ",", "error", ")", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "len", ")", "\n", "if", "_", ",", "err", ":=", "rand", ".", "Read", "(", "b", ")", ";", "err", "...
// GenerateConnectionID generates a connection ID using cryptographic random
[ "GenerateConnectionID", "generates", "a", "connection", "ID", "using", "cryptographic", "random" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/protocol/connection_id.go#L16-L22
157,320
lucas-clemente/quic-go
internal/protocol/connection_id.go
GenerateConnectionIDForInitial
func GenerateConnectionIDForInitial() (ConnectionID, error) { r := make([]byte, 1) if _, err := rand.Read(r); err != nil { return nil, err } len := MinConnectionIDLenInitial + int(r[0])%(maxConnectionIDLen-MinConnectionIDLenInitial+1) return GenerateConnectionID(len) }
go
func GenerateConnectionIDForInitial() (ConnectionID, error) { r := make([]byte, 1) if _, err := rand.Read(r); err != nil { return nil, err } len := MinConnectionIDLenInitial + int(r[0])%(maxConnectionIDLen-MinConnectionIDLenInitial+1) return GenerateConnectionID(len) }
[ "func", "GenerateConnectionIDForInitial", "(", ")", "(", "ConnectionID", ",", "error", ")", "{", "r", ":=", "make", "(", "[", "]", "byte", ",", "1", ")", "\n", "if", "_", ",", "err", ":=", "rand", ".", "Read", "(", "r", ")", ";", "err", "!=", "ni...
// GenerateConnectionIDForInitial generates a connection ID for the Initial packet. // It uses a length randomly chosen between 8 and 18 bytes.
[ "GenerateConnectionIDForInitial", "generates", "a", "connection", "ID", "for", "the", "Initial", "packet", ".", "It", "uses", "a", "length", "randomly", "chosen", "between", "8", "and", "18", "bytes", "." ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/protocol/connection_id.go#L26-L33
157,321
lucas-clemente/quic-go
internal/protocol/connection_id.go
ReadConnectionID
func ReadConnectionID(r io.Reader, len int) (ConnectionID, error) { if len == 0 { return nil, nil } c := make(ConnectionID, len) _, err := io.ReadFull(r, c) if err == io.ErrUnexpectedEOF { return nil, io.EOF } return c, err }
go
func ReadConnectionID(r io.Reader, len int) (ConnectionID, error) { if len == 0 { return nil, nil } c := make(ConnectionID, len) _, err := io.ReadFull(r, c) if err == io.ErrUnexpectedEOF { return nil, io.EOF } return c, err }
[ "func", "ReadConnectionID", "(", "r", "io", ".", "Reader", ",", "len", "int", ")", "(", "ConnectionID", ",", "error", ")", "{", "if", "len", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "c", ":=", "make", "(", "ConnectionID", ",", ...
// ReadConnectionID reads a connection ID of length len from the given io.Reader. // It returns io.EOF if there are not enough bytes to read.
[ "ReadConnectionID", "reads", "a", "connection", "ID", "of", "length", "len", "from", "the", "given", "io", ".", "Reader", ".", "It", "returns", "io", ".", "EOF", "if", "there", "are", "not", "enough", "bytes", "to", "read", "." ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/protocol/connection_id.go#L37-L47
157,322
lucas-clemente/quic-go
internal/protocol/connection_id.go
Equal
func (c ConnectionID) Equal(other ConnectionID) bool { return bytes.Equal(c, other) }
go
func (c ConnectionID) Equal(other ConnectionID) bool { return bytes.Equal(c, other) }
[ "func", "(", "c", "ConnectionID", ")", "Equal", "(", "other", "ConnectionID", ")", "bool", "{", "return", "bytes", ".", "Equal", "(", "c", ",", "other", ")", "\n", "}" ]
// Equal says if two connection IDs are equal
[ "Equal", "says", "if", "two", "connection", "IDs", "are", "equal" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/protocol/connection_id.go#L50-L52
157,323
lucas-clemente/quic-go
internal/ackhandler/received_packet_tracker.go
IgnoreBelow
func (h *receivedPacketTracker) IgnoreBelow(p protocol.PacketNumber) { if p <= h.ignoreBelow { return } h.ignoreBelow = p h.packetHistory.DeleteBelow(p) if h.logger.Debug() { h.logger.Debugf("\tIgnoring all packets below %#x.", p) } }
go
func (h *receivedPacketTracker) IgnoreBelow(p protocol.PacketNumber) { if p <= h.ignoreBelow { return } h.ignoreBelow = p h.packetHistory.DeleteBelow(p) if h.logger.Debug() { h.logger.Debugf("\tIgnoring all packets below %#x.", p) } }
[ "func", "(", "h", "*", "receivedPacketTracker", ")", "IgnoreBelow", "(", "p", "protocol", ".", "PacketNumber", ")", "{", "if", "p", "<=", "h", ".", "ignoreBelow", "{", "return", "\n", "}", "\n", "h", ".", "ignoreBelow", "=", "p", "\n", "h", ".", "pac...
// IgnoreBelow sets a lower limit for acking packets. // Packets with packet numbers smaller than p will not be acked.
[ "IgnoreBelow", "sets", "a", "lower", "limit", "for", "acking", "packets", ".", "Packets", "with", "packet", "numbers", "smaller", "than", "p", "will", "not", "be", "acked", "." ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/ackhandler/received_packet_tracker.go#L67-L76
157,324
lucas-clemente/quic-go
internal/ackhandler/received_packet_tracker.go
isMissing
func (h *receivedPacketTracker) isMissing(p protocol.PacketNumber) bool { if h.lastAck == nil || p < h.ignoreBelow { return false } return p < h.lastAck.LargestAcked() && !h.lastAck.AcksPacket(p) }
go
func (h *receivedPacketTracker) isMissing(p protocol.PacketNumber) bool { if h.lastAck == nil || p < h.ignoreBelow { return false } return p < h.lastAck.LargestAcked() && !h.lastAck.AcksPacket(p) }
[ "func", "(", "h", "*", "receivedPacketTracker", ")", "isMissing", "(", "p", "protocol", ".", "PacketNumber", ")", "bool", "{", "if", "h", ".", "lastAck", "==", "nil", "||", "p", "<", "h", ".", "ignoreBelow", "{", "return", "false", "\n", "}", "\n", "...
// isMissing says if a packet was reported missing in the last ACK.
[ "isMissing", "says", "if", "a", "packet", "was", "reported", "missing", "in", "the", "last", "ACK", "." ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/ackhandler/received_packet_tracker.go#L79-L84
157,325
lucas-clemente/quic-go
internal/wire/version_negotiation.go
ComposeVersionNegotiation
func ComposeVersionNegotiation(destConnID, srcConnID protocol.ConnectionID, versions []protocol.VersionNumber) ([]byte, error) { greasedVersions := protocol.GetGreasedVersions(versions) expectedLen := 1 /* type byte */ + 4 /* version field */ + 1 /* connection ID length field */ + destConnID.Len() + srcConnID.Len() + len(greasedVersions)*4 buf := bytes.NewBuffer(make([]byte, 0, expectedLen)) r := make([]byte, 1) _, _ = rand.Read(r) // ignore the error here. It is not critical to have perfect random here. buf.WriteByte(r[0] | 0xc0) utils.BigEndian.WriteUint32(buf, 0) // version 0 connIDLen, err := encodeConnIDLen(destConnID, srcConnID) if err != nil { return nil, err } buf.WriteByte(connIDLen) buf.Write(destConnID) buf.Write(srcConnID) for _, v := range greasedVersions { utils.BigEndian.WriteUint32(buf, uint32(v)) } return buf.Bytes(), nil }
go
func ComposeVersionNegotiation(destConnID, srcConnID protocol.ConnectionID, versions []protocol.VersionNumber) ([]byte, error) { greasedVersions := protocol.GetGreasedVersions(versions) expectedLen := 1 /* type byte */ + 4 /* version field */ + 1 /* connection ID length field */ + destConnID.Len() + srcConnID.Len() + len(greasedVersions)*4 buf := bytes.NewBuffer(make([]byte, 0, expectedLen)) r := make([]byte, 1) _, _ = rand.Read(r) // ignore the error here. It is not critical to have perfect random here. buf.WriteByte(r[0] | 0xc0) utils.BigEndian.WriteUint32(buf, 0) // version 0 connIDLen, err := encodeConnIDLen(destConnID, srcConnID) if err != nil { return nil, err } buf.WriteByte(connIDLen) buf.Write(destConnID) buf.Write(srcConnID) for _, v := range greasedVersions { utils.BigEndian.WriteUint32(buf, uint32(v)) } return buf.Bytes(), nil }
[ "func", "ComposeVersionNegotiation", "(", "destConnID", ",", "srcConnID", "protocol", ".", "ConnectionID", ",", "versions", "[", "]", "protocol", ".", "VersionNumber", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "greasedVersions", ":=", "protocol", "."...
// ComposeVersionNegotiation composes a Version Negotiation
[ "ComposeVersionNegotiation", "composes", "a", "Version", "Negotiation" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/wire/version_negotiation.go#L12-L31
157,326
lucas-clemente/quic-go
internal/flowcontrol/stream_flow_controller.go
NewStreamFlowController
func NewStreamFlowController( streamID protocol.StreamID, cfc ConnectionFlowController, receiveWindow protocol.ByteCount, maxReceiveWindow protocol.ByteCount, initialSendWindow protocol.ByteCount, queueWindowUpdate func(protocol.StreamID), rttStats *congestion.RTTStats, logger utils.Logger, ) StreamFlowController { return &streamFlowController{ streamID: streamID, connection: cfc.(connectionFlowControllerI), queueWindowUpdate: func() { queueWindowUpdate(streamID) }, baseFlowController: baseFlowController{ rttStats: rttStats, receiveWindow: receiveWindow, receiveWindowSize: receiveWindow, maxReceiveWindowSize: maxReceiveWindow, sendWindow: initialSendWindow, logger: logger, }, } }
go
func NewStreamFlowController( streamID protocol.StreamID, cfc ConnectionFlowController, receiveWindow protocol.ByteCount, maxReceiveWindow protocol.ByteCount, initialSendWindow protocol.ByteCount, queueWindowUpdate func(protocol.StreamID), rttStats *congestion.RTTStats, logger utils.Logger, ) StreamFlowController { return &streamFlowController{ streamID: streamID, connection: cfc.(connectionFlowControllerI), queueWindowUpdate: func() { queueWindowUpdate(streamID) }, baseFlowController: baseFlowController{ rttStats: rttStats, receiveWindow: receiveWindow, receiveWindowSize: receiveWindow, maxReceiveWindowSize: maxReceiveWindow, sendWindow: initialSendWindow, logger: logger, }, } }
[ "func", "NewStreamFlowController", "(", "streamID", "protocol", ".", "StreamID", ",", "cfc", "ConnectionFlowController", ",", "receiveWindow", "protocol", ".", "ByteCount", ",", "maxReceiveWindow", "protocol", ".", "ByteCount", ",", "initialSendWindow", "protocol", ".",...
// NewStreamFlowController gets a new flow controller for a stream
[ "NewStreamFlowController", "gets", "a", "new", "flow", "controller", "for", "a", "stream" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/flowcontrol/stream_flow_controller.go#L27-L50
157,327
lucas-clemente/quic-go
internal/flowcontrol/stream_flow_controller.go
UpdateHighestReceived
func (c *streamFlowController) UpdateHighestReceived(offset protocol.ByteCount, final bool) error { c.mutex.Lock() defer c.mutex.Unlock() // If the final offset for this stream is already known, check for consistency. if c.receivedFinalOffset { // If we receive another final offset, check that it's the same. if final && offset != c.highestReceived { return qerr.Error(qerr.FinalSizeError, fmt.Sprintf("Received inconsistent final offset for stream %d (old: %#x, new: %#x bytes)", c.streamID, c.highestReceived, offset)) } // Check that the offset is below the final offset. if offset > c.highestReceived { return qerr.Error(qerr.FinalSizeError, fmt.Sprintf("Received offset %#x for stream %d. Final offset was already received at %#x", offset, c.streamID, c.highestReceived)) } } if final { c.receivedFinalOffset = true } if offset == c.highestReceived { return nil } // A higher offset was received before. // This can happen due to reordering. if offset <= c.highestReceived { if final { return qerr.Error(qerr.FinalSizeError, fmt.Sprintf("Received final offset %#x for stream %d, but already received offset %#x before", offset, c.streamID, c.highestReceived)) } return nil } increment := offset - c.highestReceived c.highestReceived = offset if c.checkFlowControlViolation() { return qerr.Error(qerr.FlowControlError, fmt.Sprintf("Received %#x bytes on stream %d, allowed %#x bytes", offset, c.streamID, c.receiveWindow)) } return c.connection.IncrementHighestReceived(increment) }
go
func (c *streamFlowController) UpdateHighestReceived(offset protocol.ByteCount, final bool) error { c.mutex.Lock() defer c.mutex.Unlock() // If the final offset for this stream is already known, check for consistency. if c.receivedFinalOffset { // If we receive another final offset, check that it's the same. if final && offset != c.highestReceived { return qerr.Error(qerr.FinalSizeError, fmt.Sprintf("Received inconsistent final offset for stream %d (old: %#x, new: %#x bytes)", c.streamID, c.highestReceived, offset)) } // Check that the offset is below the final offset. if offset > c.highestReceived { return qerr.Error(qerr.FinalSizeError, fmt.Sprintf("Received offset %#x for stream %d. Final offset was already received at %#x", offset, c.streamID, c.highestReceived)) } } if final { c.receivedFinalOffset = true } if offset == c.highestReceived { return nil } // A higher offset was received before. // This can happen due to reordering. if offset <= c.highestReceived { if final { return qerr.Error(qerr.FinalSizeError, fmt.Sprintf("Received final offset %#x for stream %d, but already received offset %#x before", offset, c.streamID, c.highestReceived)) } return nil } increment := offset - c.highestReceived c.highestReceived = offset if c.checkFlowControlViolation() { return qerr.Error(qerr.FlowControlError, fmt.Sprintf("Received %#x bytes on stream %d, allowed %#x bytes", offset, c.streamID, c.receiveWindow)) } return c.connection.IncrementHighestReceived(increment) }
[ "func", "(", "c", "*", "streamFlowController", ")", "UpdateHighestReceived", "(", "offset", "protocol", ".", "ByteCount", ",", "final", "bool", ")", "error", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", ...
// UpdateHighestReceived updates the highestReceived value, if the offset is higher.
[ "UpdateHighestReceived", "updates", "the", "highestReceived", "value", "if", "the", "offset", "is", "higher", "." ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/flowcontrol/stream_flow_controller.go#L53-L90
157,328
lucas-clemente/quic-go
internal/wire/crypto_frame.go
MaxDataLen
func (f *CryptoFrame) MaxDataLen(maxSize protocol.ByteCount) protocol.ByteCount { // pretend that the data size will be 1 bytes // if it turns out that varint encoding the length will consume 2 bytes, we need to adjust the data length afterwards headerLen := 1 + utils.VarIntLen(uint64(f.Offset)) + 1 if headerLen > maxSize { return 0 } maxDataLen := maxSize - headerLen if utils.VarIntLen(uint64(maxDataLen)) != 1 { maxDataLen-- } return maxDataLen }
go
func (f *CryptoFrame) MaxDataLen(maxSize protocol.ByteCount) protocol.ByteCount { // pretend that the data size will be 1 bytes // if it turns out that varint encoding the length will consume 2 bytes, we need to adjust the data length afterwards headerLen := 1 + utils.VarIntLen(uint64(f.Offset)) + 1 if headerLen > maxSize { return 0 } maxDataLen := maxSize - headerLen if utils.VarIntLen(uint64(maxDataLen)) != 1 { maxDataLen-- } return maxDataLen }
[ "func", "(", "f", "*", "CryptoFrame", ")", "MaxDataLen", "(", "maxSize", "protocol", ".", "ByteCount", ")", "protocol", ".", "ByteCount", "{", "// pretend that the data size will be 1 bytes", "// if it turns out that varint encoding the length will consume 2 bytes, we need to adj...
// MaxDataLen returns the maximum data length
[ "MaxDataLen", "returns", "the", "maximum", "data", "length" ]
c135b4f1e34c621c24563def836af2c04af90ae6
https://github.com/lucas-clemente/quic-go/blob/c135b4f1e34c621c24563def836af2c04af90ae6/internal/wire/crypto_frame.go#L59-L71
157,329
git-lfs/git-lfs
commands/pull.go
newSingleCheckout
func newSingleCheckout(gitEnv config.Environment, remote string) abstractCheckout { manifest := getTransferManifestOperationRemote("download", remote) clean, ok := gitEnv.Get("filter.lfs.clean") if !ok || len(clean) == 0 { return &noOpCheckout{manifest: manifest} } // Get a converter from repo-relative to cwd-relative // Since writing data & calling git update-index must be relative to cwd pathConverter, err := lfs.NewRepoToCurrentPathConverter(cfg) if err != nil { Panic(err, "Could not convert file paths") } return &singleCheckout{ gitIndexer: &gitIndexer{}, pathConverter: pathConverter, manifest: manifest, } }
go
func newSingleCheckout(gitEnv config.Environment, remote string) abstractCheckout { manifest := getTransferManifestOperationRemote("download", remote) clean, ok := gitEnv.Get("filter.lfs.clean") if !ok || len(clean) == 0 { return &noOpCheckout{manifest: manifest} } // Get a converter from repo-relative to cwd-relative // Since writing data & calling git update-index must be relative to cwd pathConverter, err := lfs.NewRepoToCurrentPathConverter(cfg) if err != nil { Panic(err, "Could not convert file paths") } return &singleCheckout{ gitIndexer: &gitIndexer{}, pathConverter: pathConverter, manifest: manifest, } }
[ "func", "newSingleCheckout", "(", "gitEnv", "config", ".", "Environment", ",", "remote", "string", ")", "abstractCheckout", "{", "manifest", ":=", "getTransferManifestOperationRemote", "(", "\"", "\"", ",", "remote", ")", "\n\n", "clean", ",", "ok", ":=", "gitEn...
// Handles the process of checking out a single file, and updating the git // index.
[ "Handles", "the", "process", "of", "checking", "out", "a", "single", "file", "and", "updating", "the", "git", "index", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/pull.go#L20-L40
157,330
git-lfs/git-lfs
commands/pull.go
RunToPath
func (c *singleCheckout) RunToPath(p *lfs.WrappedPointer, path string) error { gitfilter := lfs.NewGitFilter(cfg) return gitfilter.SmudgeToFile(path, p.Pointer, false, c.manifest, nil) }
go
func (c *singleCheckout) RunToPath(p *lfs.WrappedPointer, path string) error { gitfilter := lfs.NewGitFilter(cfg) return gitfilter.SmudgeToFile(path, p.Pointer, false, c.manifest, nil) }
[ "func", "(", "c", "*", "singleCheckout", ")", "RunToPath", "(", "p", "*", "lfs", ".", "WrappedPointer", ",", "path", "string", ")", "error", "{", "gitfilter", ":=", "lfs", ".", "NewGitFilter", "(", "cfg", ")", "\n", "return", "gitfilter", ".", "SmudgeToF...
// RunToPath checks out the pointer specified by p to the given path. It does // not perform any sort of sanity checking or add the path to the index.
[ "RunToPath", "checks", "out", "the", "pointer", "specified", "by", "p", "to", "the", "given", "path", ".", "It", "does", "not", "perform", "any", "sort", "of", "sanity", "checking", "or", "add", "the", "path", "to", "the", "index", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/pull.go#L103-L106
157,331
git-lfs/git-lfs
creds/creds.go
GetCredentialHelper
func (ctxt *CredentialHelperContext) GetCredentialHelper(helper CredentialHelper, u *url.URL) (CredentialHelper, Creds) { rawurl := fmt.Sprintf("%s://%s%s", u.Scheme, u.Host, u.Path) input := Creds{"protocol": u.Scheme, "host": u.Host} if u.User != nil && u.User.Username() != "" { input["username"] = u.User.Username() } if u.Scheme == "cert" || ctxt.urlConfig.Bool("credential", rawurl, "usehttppath", false) { input["path"] = strings.TrimPrefix(u.Path, "/") } if helper != nil { return helper, input } helpers := make([]CredentialHelper, 0, 4) if ctxt.netrcCredHelper != nil { helpers = append(helpers, ctxt.netrcCredHelper) } if ctxt.cachingCredHelper != nil { helpers = append(helpers, ctxt.cachingCredHelper) } if ctxt.askpassCredHelper != nil { helper, _ := ctxt.urlConfig.Get("credential", rawurl, "helper") if len(helper) == 0 { helpers = append(helpers, ctxt.askpassCredHelper) } } return NewCredentialHelpers(append(helpers, ctxt.commandCredHelper)), input }
go
func (ctxt *CredentialHelperContext) GetCredentialHelper(helper CredentialHelper, u *url.URL) (CredentialHelper, Creds) { rawurl := fmt.Sprintf("%s://%s%s", u.Scheme, u.Host, u.Path) input := Creds{"protocol": u.Scheme, "host": u.Host} if u.User != nil && u.User.Username() != "" { input["username"] = u.User.Username() } if u.Scheme == "cert" || ctxt.urlConfig.Bool("credential", rawurl, "usehttppath", false) { input["path"] = strings.TrimPrefix(u.Path, "/") } if helper != nil { return helper, input } helpers := make([]CredentialHelper, 0, 4) if ctxt.netrcCredHelper != nil { helpers = append(helpers, ctxt.netrcCredHelper) } if ctxt.cachingCredHelper != nil { helpers = append(helpers, ctxt.cachingCredHelper) } if ctxt.askpassCredHelper != nil { helper, _ := ctxt.urlConfig.Get("credential", rawurl, "helper") if len(helper) == 0 { helpers = append(helpers, ctxt.askpassCredHelper) } } return NewCredentialHelpers(append(helpers, ctxt.commandCredHelper)), input }
[ "func", "(", "ctxt", "*", "CredentialHelperContext", ")", "GetCredentialHelper", "(", "helper", "CredentialHelper", ",", "u", "*", "url", ".", "URL", ")", "(", "CredentialHelper", ",", "Creds", ")", "{", "rawurl", ":=", "fmt", ".", "Sprintf", "(", "\"", "\...
// getCredentialHelper parses a 'credsConfig' from the git and OS environments, // returning the appropriate CredentialHelper to authenticate requests with. // // It returns an error if any configuration was invalid, or otherwise // un-useable.
[ "getCredentialHelper", "parses", "a", "credsConfig", "from", "the", "git", "and", "OS", "environments", "returning", "the", "appropriate", "CredentialHelper", "to", "authenticate", "requests", "with", ".", "It", "returns", "an", "error", "if", "any", "configuration"...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/creds/creds.go#L87-L116
157,332
git-lfs/git-lfs
creds/creds.go
NewCredentialHelpers
func NewCredentialHelpers(helpers []CredentialHelper) CredentialHelper { return &CredentialHelpers{ helpers: helpers, skippedHelpers: make(map[int]bool), } }
go
func NewCredentialHelpers(helpers []CredentialHelper) CredentialHelper { return &CredentialHelpers{ helpers: helpers, skippedHelpers: make(map[int]bool), } }
[ "func", "NewCredentialHelpers", "(", "helpers", "[", "]", "CredentialHelper", ")", "CredentialHelper", "{", "return", "&", "CredentialHelpers", "{", "helpers", ":", "helpers", ",", "skippedHelpers", ":", "make", "(", "map", "[", "int", "]", "bool", ")", ",", ...
// NewCredentialHelpers initializes a new CredentialHelpers from the given // slice of CredentialHelper instances.
[ "NewCredentialHelpers", "initializes", "a", "new", "CredentialHelpers", "from", "the", "given", "slice", "of", "CredentialHelper", "instances", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/creds/creds.go#L394-L399
157,333
git-lfs/git-lfs
creds/creds.go
Fill
func (s *CredentialHelpers) Fill(what Creds) (Creds, error) { errs := make([]string, 0, len(s.helpers)) for i, h := range s.helpers { if s.skipped(i) { continue } creds, err := h.Fill(what) if err != nil { if err != credHelperNoOp { s.skip(i) tracerx.Printf("credential fill error: %s", err) errs = append(errs, err.Error()) } continue } if creds != nil { return creds, nil } } if len(errs) > 0 { return nil, errors.New("credential fill errors:\n" + strings.Join(errs, "\n")) } return nil, nil }
go
func (s *CredentialHelpers) Fill(what Creds) (Creds, error) { errs := make([]string, 0, len(s.helpers)) for i, h := range s.helpers { if s.skipped(i) { continue } creds, err := h.Fill(what) if err != nil { if err != credHelperNoOp { s.skip(i) tracerx.Printf("credential fill error: %s", err) errs = append(errs, err.Error()) } continue } if creds != nil { return creds, nil } } if len(errs) > 0 { return nil, errors.New("credential fill errors:\n" + strings.Join(errs, "\n")) } return nil, nil }
[ "func", "(", "s", "*", "CredentialHelpers", ")", "Fill", "(", "what", "Creds", ")", "(", "Creds", ",", "error", ")", "{", "errs", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "s", ".", "helpers", ")", ")", "\n", "for", "i",...
// Fill implements CredentialHelper.Fill by asking each CredentialHelper in // order to fill the credentials. // // If a fill was successful, it is returned immediately, and no other // `CredentialHelper`s are consulted. If any CredentialHelper returns an error, // it is reported to tracerx, and the next one is attempted. If they all error, // then a collection of all the error messages is returned. Erroring credential // helpers are added to the skip list, and never attempted again for the // lifetime of the current Git LFS command.
[ "Fill", "implements", "CredentialHelper", ".", "Fill", "by", "asking", "each", "CredentialHelper", "in", "order", "to", "fill", "the", "credentials", ".", "If", "a", "fill", "was", "successful", "it", "is", "returned", "immediately", "and", "no", "other", "Cre...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/creds/creds.go#L412-L439
157,334
git-lfs/git-lfs
creds/creds.go
Reject
func (s *CredentialHelpers) Reject(what Creds) error { for i, h := range s.helpers { if s.skipped(i) { continue } if err := h.Reject(what); err != credHelperNoOp { return err } } return errors.New("no valid credential helpers to reject") }
go
func (s *CredentialHelpers) Reject(what Creds) error { for i, h := range s.helpers { if s.skipped(i) { continue } if err := h.Reject(what); err != credHelperNoOp { return err } } return errors.New("no valid credential helpers to reject") }
[ "func", "(", "s", "*", "CredentialHelpers", ")", "Reject", "(", "what", "Creds", ")", "error", "{", "for", "i", ",", "h", ":=", "range", "s", ".", "helpers", "{", "if", "s", ".", "skipped", "(", "i", ")", "{", "continue", "\n", "}", "\n\n", "if",...
// Reject implements CredentialHelper.Reject and rejects the given Creds "what" // with the first successful attempt.
[ "Reject", "implements", "CredentialHelper", ".", "Reject", "and", "rejects", "the", "given", "Creds", "what", "with", "the", "first", "successful", "attempt", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/creds/creds.go#L443-L455
157,335
git-lfs/git-lfs
tq/adapterbase.go
worker
func (a *adapterBase) worker(workerNum int, ctx interface{}) { a.Trace("xfer: adapter %q worker %d starting", a.Name(), workerNum) waitForAuth := workerNum > 0 signalAuthOnResponse := workerNum == 0 // First worker is the only one allowed to start immediately // The rest wait until successful response from 1st worker to // make sure only 1 login prompt is presented if necessary // Deliberately outside jobChan processing so we know worker 0 will process 1st item if waitForAuth { a.Trace("xfer: adapter %q worker %d waiting for Auth", a.Name(), workerNum) a.authWait.Wait() a.Trace("xfer: adapter %q worker %d auth signal received", a.Name(), workerNum) } for job := range a.jobChan { t := job.T var authCallback func() if signalAuthOnResponse { authCallback = func() { a.authWait.Done() signalAuthOnResponse = false } } a.Trace("xfer: adapter %q worker %d processing job for %q", a.Name(), workerNum, t.Oid) // Actual transfer happens here var err error if t.Size < 0 { err = fmt.Errorf("Git LFS: object %q has invalid size (got: %d)", t.Oid, t.Size) } else { err = a.transferImpl.DoTransfer(ctx, t, a.cb, authCallback) } // Mark the job as completed, and alter all listeners job.Done(err) a.Trace("xfer: adapter %q worker %d finished job for %q", a.Name(), workerNum, t.Oid) } // This will only happen if no jobs were submitted; just wake up all workers to finish if signalAuthOnResponse { a.authWait.Done() } a.Trace("xfer: adapter %q worker %d stopping", a.Name(), workerNum) a.transferImpl.WorkerEnding(workerNum, ctx) a.workerWait.Done() }
go
func (a *adapterBase) worker(workerNum int, ctx interface{}) { a.Trace("xfer: adapter %q worker %d starting", a.Name(), workerNum) waitForAuth := workerNum > 0 signalAuthOnResponse := workerNum == 0 // First worker is the only one allowed to start immediately // The rest wait until successful response from 1st worker to // make sure only 1 login prompt is presented if necessary // Deliberately outside jobChan processing so we know worker 0 will process 1st item if waitForAuth { a.Trace("xfer: adapter %q worker %d waiting for Auth", a.Name(), workerNum) a.authWait.Wait() a.Trace("xfer: adapter %q worker %d auth signal received", a.Name(), workerNum) } for job := range a.jobChan { t := job.T var authCallback func() if signalAuthOnResponse { authCallback = func() { a.authWait.Done() signalAuthOnResponse = false } } a.Trace("xfer: adapter %q worker %d processing job for %q", a.Name(), workerNum, t.Oid) // Actual transfer happens here var err error if t.Size < 0 { err = fmt.Errorf("Git LFS: object %q has invalid size (got: %d)", t.Oid, t.Size) } else { err = a.transferImpl.DoTransfer(ctx, t, a.cb, authCallback) } // Mark the job as completed, and alter all listeners job.Done(err) a.Trace("xfer: adapter %q worker %d finished job for %q", a.Name(), workerNum, t.Oid) } // This will only happen if no jobs were submitted; just wake up all workers to finish if signalAuthOnResponse { a.authWait.Done() } a.Trace("xfer: adapter %q worker %d stopping", a.Name(), workerNum) a.transferImpl.WorkerEnding(workerNum, ctx) a.workerWait.Done() }
[ "func", "(", "a", "*", "adapterBase", ")", "worker", "(", "workerNum", "int", ",", "ctx", "interface", "{", "}", ")", "{", "a", ".", "Trace", "(", "\"", "\"", ",", "a", ".", "Name", "(", ")", ",", "workerNum", ")", "\n", "waitForAuth", ":=", "wor...
// worker function, many of these run per adapter
[ "worker", "function", "many", "of", "these", "run", "per", "adapter" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/adapterbase.go#L150-L197
157,336
git-lfs/git-lfs
tools/math.go
ClampInt
func ClampInt(n, min, max int) int { return MinInt(min, MaxInt(max, n)) }
go
func ClampInt(n, min, max int) int { return MinInt(min, MaxInt(max, n)) }
[ "func", "ClampInt", "(", "n", ",", "min", ",", "max", "int", ")", "int", "{", "return", "MinInt", "(", "min", ",", "MaxInt", "(", "max", ",", "n", ")", ")", "\n", "}" ]
// ClampInt returns the integer "n" bounded between "min" and "max".
[ "ClampInt", "returns", "the", "integer", "n", "bounded", "between", "min", "and", "max", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/math.go#L22-L24
157,337
git-lfs/git-lfs
lfs/gitscanner_refs.go
Check
func (s *lockableNameSet) Check(blobSha string) (string, bool) { if s == nil || s.opt == nil || s.set == nil { return "", false } name, ok := s.opt.GetName(blobSha) if !ok { return name, ok } if s.set.Contains(name) { return name, true } return name, false }
go
func (s *lockableNameSet) Check(blobSha string) (string, bool) { if s == nil || s.opt == nil || s.set == nil { return "", false } name, ok := s.opt.GetName(blobSha) if !ok { return name, ok } if s.set.Contains(name) { return name, true } return name, false }
[ "func", "(", "s", "*", "lockableNameSet", ")", "Check", "(", "blobSha", "string", ")", "(", "string", ",", "bool", ")", "{", "if", "s", "==", "nil", "||", "s", ".", "opt", "==", "nil", "||", "s", ".", "set", "==", "nil", "{", "return", "\"", "\...
// Determines if the given blob sha matches a locked file.
[ "Determines", "if", "the", "given", "blob", "sha", "matches", "a", "locked", "file", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfs/gitscanner_refs.go#L18-L32
157,338
git-lfs/git-lfs
lfs/gitscanner_refs.go
scanRefsToChan
func scanRefsToChan(scanner *GitScanner, pointerCb GitScannerFoundPointer, include, exclude []string, opt *ScanRefsOptions) error { if opt == nil { panic("no scan ref options") } revs, err := revListShas(include, exclude, opt) if err != nil { return err } lockableSet := &lockableNameSet{opt: opt, set: scanner.PotentialLockables} smallShas, batchLockableCh, err := catFileBatchCheck(revs, lockableSet) if err != nil { return err } lockableCb := scanner.FoundLockable if lockableCb == nil { lockableCb = noopFoundLockable } go func(cb GitScannerFoundLockable, ch chan string) { for name := range ch { cb(name) } }(lockableCb, batchLockableCh) pointers, checkLockableCh, err := catFileBatch(smallShas, lockableSet) if err != nil { return err } for p := range pointers.Results { if name, ok := opt.GetName(p.Sha1); ok { p.Name = name } if scanner.Filter.Allows(p.Name) { pointerCb(p, nil) } } for lockableName := range checkLockableCh { if scanner.Filter.Allows(lockableName) { lockableCb(lockableName) } } if err := pointers.Wait(); err != nil { pointerCb(nil, err) } return nil }
go
func scanRefsToChan(scanner *GitScanner, pointerCb GitScannerFoundPointer, include, exclude []string, opt *ScanRefsOptions) error { if opt == nil { panic("no scan ref options") } revs, err := revListShas(include, exclude, opt) if err != nil { return err } lockableSet := &lockableNameSet{opt: opt, set: scanner.PotentialLockables} smallShas, batchLockableCh, err := catFileBatchCheck(revs, lockableSet) if err != nil { return err } lockableCb := scanner.FoundLockable if lockableCb == nil { lockableCb = noopFoundLockable } go func(cb GitScannerFoundLockable, ch chan string) { for name := range ch { cb(name) } }(lockableCb, batchLockableCh) pointers, checkLockableCh, err := catFileBatch(smallShas, lockableSet) if err != nil { return err } for p := range pointers.Results { if name, ok := opt.GetName(p.Sha1); ok { p.Name = name } if scanner.Filter.Allows(p.Name) { pointerCb(p, nil) } } for lockableName := range checkLockableCh { if scanner.Filter.Allows(lockableName) { lockableCb(lockableName) } } if err := pointers.Wait(); err != nil { pointerCb(nil, err) } return nil }
[ "func", "scanRefsToChan", "(", "scanner", "*", "GitScanner", ",", "pointerCb", "GitScannerFoundPointer", ",", "include", ",", "exclude", "[", "]", "string", ",", "opt", "*", "ScanRefsOptions", ")", "error", "{", "if", "opt", "==", "nil", "{", "panic", "(", ...
// scanRefsToChan scans through all commits reachable by refs contained in // "include" and not reachable by any refs included in "excluded" and returns // a channel of WrappedPointer objects for all Git LFS pointers it finds. // Reports unique oids once only, not multiple times if >1 file uses the same content
[ "scanRefsToChan", "scans", "through", "all", "commits", "reachable", "by", "refs", "contained", "in", "include", "and", "not", "reachable", "by", "any", "refs", "included", "in", "excluded", "and", "returns", "a", "channel", "of", "WrappedPointer", "objects", "f...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfs/gitscanner_refs.go#L40-L93
157,339
git-lfs/git-lfs
lfs/gitscanner_refs.go
scanLeftRightToChan
func scanLeftRightToChan(scanner *GitScanner, pointerCb GitScannerFoundPointer, refLeft, refRight string, opt *ScanRefsOptions) error { return scanRefsToChan(scanner, pointerCb, []string{refLeft, refRight}, nil, opt) }
go
func scanLeftRightToChan(scanner *GitScanner, pointerCb GitScannerFoundPointer, refLeft, refRight string, opt *ScanRefsOptions) error { return scanRefsToChan(scanner, pointerCb, []string{refLeft, refRight}, nil, opt) }
[ "func", "scanLeftRightToChan", "(", "scanner", "*", "GitScanner", ",", "pointerCb", "GitScannerFoundPointer", ",", "refLeft", ",", "refRight", "string", ",", "opt", "*", "ScanRefsOptions", ")", "error", "{", "return", "scanRefsToChan", "(", "scanner", ",", "pointe...
// scanLeftRightToChan takes a ref and returns a channel of WrappedPointer objects // for all Git LFS pointers it finds for that ref. // Reports unique oids once only, not multiple times if >1 file uses the same content
[ "scanLeftRightToChan", "takes", "a", "ref", "and", "returns", "a", "channel", "of", "WrappedPointer", "objects", "for", "all", "Git", "LFS", "pointers", "it", "finds", "for", "that", "ref", ".", "Reports", "unique", "oids", "once", "only", "not", "multiple", ...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfs/gitscanner_refs.go#L98-L100
157,340
git-lfs/git-lfs
lfs/gitscanner_refs.go
revListShas
func revListShas(include, exclude []string, opt *ScanRefsOptions) (*StringChannelWrapper, error) { scanner, err := git.NewRevListScanner(include, exclude, &git.ScanRefsOptions{ Mode: git.ScanningMode(opt.ScanMode), Remote: opt.RemoteName, SkipDeletedBlobs: opt.SkipDeletedBlobs, SkippedRefs: opt.skippedRefs, Mutex: opt.mutex, Names: opt.nameMap, }) if err != nil { return nil, err } revs := make(chan string, chanBufSize) errs := make(chan error, 5) // may be multiple errors go func() { for scanner.Scan() { sha := hex.EncodeToString(scanner.OID()) if name := scanner.Name(); len(name) > 0 { opt.SetName(sha, name) } revs <- sha } if err = scanner.Err(); err != nil { errs <- err } if err = scanner.Close(); err != nil { errs <- err } close(revs) close(errs) }() return NewStringChannelWrapper(revs, errs), nil }
go
func revListShas(include, exclude []string, opt *ScanRefsOptions) (*StringChannelWrapper, error) { scanner, err := git.NewRevListScanner(include, exclude, &git.ScanRefsOptions{ Mode: git.ScanningMode(opt.ScanMode), Remote: opt.RemoteName, SkipDeletedBlobs: opt.SkipDeletedBlobs, SkippedRefs: opt.skippedRefs, Mutex: opt.mutex, Names: opt.nameMap, }) if err != nil { return nil, err } revs := make(chan string, chanBufSize) errs := make(chan error, 5) // may be multiple errors go func() { for scanner.Scan() { sha := hex.EncodeToString(scanner.OID()) if name := scanner.Name(); len(name) > 0 { opt.SetName(sha, name) } revs <- sha } if err = scanner.Err(); err != nil { errs <- err } if err = scanner.Close(); err != nil { errs <- err } close(revs) close(errs) }() return NewStringChannelWrapper(revs, errs), nil }
[ "func", "revListShas", "(", "include", ",", "exclude", "[", "]", "string", ",", "opt", "*", "ScanRefsOptions", ")", "(", "*", "StringChannelWrapper", ",", "error", ")", "{", "scanner", ",", "err", ":=", "git", ".", "NewRevListScanner", "(", "include", ",",...
// revListShas uses git rev-list to return the list of object sha1s // for the given ref. If all is true, ref is ignored. It returns a // channel from which sha1 strings can be read.
[ "revListShas", "uses", "git", "rev", "-", "list", "to", "return", "the", "list", "of", "object", "sha1s", "for", "the", "given", "ref", ".", "If", "all", "is", "true", "ref", "is", "ignored", ".", "It", "returns", "a", "channel", "from", "which", "sha1...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfs/gitscanner_refs.go#L105-L144
157,341
git-lfs/git-lfs
locking/cache.go
Add
func (c *LockCache) Add(l Lock) error { // Store reference in both directions // Path -> Lock c.kv.Set(l.Path, &l) // EncodedId -> Lock (encoded so we can easily identify) c.kv.Set(c.encodeIdKey(l.Id), &l) return nil }
go
func (c *LockCache) Add(l Lock) error { // Store reference in both directions // Path -> Lock c.kv.Set(l.Path, &l) // EncodedId -> Lock (encoded so we can easily identify) c.kv.Set(c.encodeIdKey(l.Id), &l) return nil }
[ "func", "(", "c", "*", "LockCache", ")", "Add", "(", "l", "Lock", ")", "error", "{", "// Store reference in both directions", "// Path -> Lock", "c", ".", "kv", ".", "Set", "(", "l", ".", "Path", ",", "&", "l", ")", "\n", "// EncodedId -> Lock (encoded so we...
// Cache a successful lock for faster local lookup later
[ "Cache", "a", "successful", "lock", "for", "faster", "local", "lookup", "later" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/cache.go#L29-L36
157,342
git-lfs/git-lfs
locking/cache.go
RemoveByPath
func (c *LockCache) RemoveByPath(filePath string) error { ilock := c.kv.Get(filePath) if lock, ok := ilock.(*Lock); ok && lock != nil { c.kv.Remove(lock.Path) // Id as key is encoded c.kv.Remove(c.encodeIdKey(lock.Id)) } return nil }
go
func (c *LockCache) RemoveByPath(filePath string) error { ilock := c.kv.Get(filePath) if lock, ok := ilock.(*Lock); ok && lock != nil { c.kv.Remove(lock.Path) // Id as key is encoded c.kv.Remove(c.encodeIdKey(lock.Id)) } return nil }
[ "func", "(", "c", "*", "LockCache", ")", "RemoveByPath", "(", "filePath", "string", ")", "error", "{", "ilock", ":=", "c", ".", "kv", ".", "Get", "(", "filePath", ")", "\n", "if", "lock", ",", "ok", ":=", "ilock", ".", "(", "*", "Lock", ")", ";",...
// Remove a cached lock by path becuase it's been relinquished
[ "Remove", "a", "cached", "lock", "by", "path", "becuase", "it", "s", "been", "relinquished" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/cache.go#L39-L47
157,343
git-lfs/git-lfs
locking/cache.go
RemoveById
func (c *LockCache) RemoveById(id string) error { // Id as key is encoded idkey := c.encodeIdKey(id) ilock := c.kv.Get(idkey) if lock, ok := ilock.(*Lock); ok && lock != nil { c.kv.Remove(idkey) c.kv.Remove(lock.Path) } return nil }
go
func (c *LockCache) RemoveById(id string) error { // Id as key is encoded idkey := c.encodeIdKey(id) ilock := c.kv.Get(idkey) if lock, ok := ilock.(*Lock); ok && lock != nil { c.kv.Remove(idkey) c.kv.Remove(lock.Path) } return nil }
[ "func", "(", "c", "*", "LockCache", ")", "RemoveById", "(", "id", "string", ")", "error", "{", "// Id as key is encoded", "idkey", ":=", "c", ".", "encodeIdKey", "(", "id", ")", "\n", "ilock", ":=", "c", ".", "kv", ".", "Get", "(", "idkey", ")", "\n"...
// Remove a cached lock by id because it's been relinquished
[ "Remove", "a", "cached", "lock", "by", "id", "because", "it", "s", "been", "relinquished" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/cache.go#L50-L59
157,344
git-lfs/git-lfs
locking/cache.go
Locks
func (c *LockCache) Locks() []Lock { var locks []Lock c.kv.Visit(func(key string, val interface{}) bool { // Only report file->id entries not reverse if !c.isIdKey(key) { lock := val.(*Lock) locks = append(locks, *lock) } return true // continue }) return locks }
go
func (c *LockCache) Locks() []Lock { var locks []Lock c.kv.Visit(func(key string, val interface{}) bool { // Only report file->id entries not reverse if !c.isIdKey(key) { lock := val.(*Lock) locks = append(locks, *lock) } return true // continue }) return locks }
[ "func", "(", "c", "*", "LockCache", ")", "Locks", "(", ")", "[", "]", "Lock", "{", "var", "locks", "[", "]", "Lock", "\n", "c", ".", "kv", ".", "Visit", "(", "func", "(", "key", "string", ",", "val", "interface", "{", "}", ")", "bool", "{", "...
// Get the list of cached locked files
[ "Get", "the", "list", "of", "cached", "locked", "files" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/cache.go#L62-L73
157,345
git-lfs/git-lfs
locking/locks.go
NewClient
func NewClient(remote string, lfsClient *lfsapi.Client, cfg *config.Configuration) (*Client, error) { return &Client{ Remote: remote, client: &lockClient{Client: lfsClient}, cache: &nilLockCacher{}, cfg: cfg, ModifyIgnoredFiles: lfsClient.GitEnv().Bool("lfs.lockignoredfiles", false), }, nil }
go
func NewClient(remote string, lfsClient *lfsapi.Client, cfg *config.Configuration) (*Client, error) { return &Client{ Remote: remote, client: &lockClient{Client: lfsClient}, cache: &nilLockCacher{}, cfg: cfg, ModifyIgnoredFiles: lfsClient.GitEnv().Bool("lfs.lockignoredfiles", false), }, nil }
[ "func", "NewClient", "(", "remote", "string", ",", "lfsClient", "*", "lfsapi", ".", "Client", ",", "cfg", "*", "config", ".", "Configuration", ")", "(", "*", "Client", ",", "error", ")", "{", "return", "&", "Client", "{", "Remote", ":", "remote", ",", ...
// NewClient creates a new locking client with the given configuration // You must call the returned object's `Close` method when you are finished with // it
[ "NewClient", "creates", "a", "new", "locking", "client", "with", "the", "given", "configuration", "You", "must", "call", "the", "returned", "object", "s", "Close", "method", "when", "you", "are", "finished", "with", "it" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/locks.go#L63-L71
157,346
git-lfs/git-lfs
locking/locks.go
LockFile
func (c *Client) LockFile(path string) (Lock, error) { lockRes, _, err := c.client.Lock(c.Remote, &lockRequest{ Path: path, Ref: &lockRef{Name: c.RemoteRef.Refspec()}, }) if err != nil { return Lock{}, errors.Wrap(err, "api") } if len(lockRes.Message) > 0 { if len(lockRes.RequestID) > 0 { tracerx.Printf("Server Request ID: %s", lockRes.RequestID) } return Lock{}, fmt.Errorf("Server unable to create lock: %s", lockRes.Message) } lock := *lockRes.Lock if err := c.cache.Add(lock); err != nil { return Lock{}, errors.Wrap(err, "lock cache") } abs, err := getAbsolutePath(path) if err != nil { return Lock{}, errors.Wrap(err, "make lockpath absolute") } // Ensure writeable on return if err := tools.SetFileWriteFlag(abs, true); err != nil { return Lock{}, err } return lock, nil }
go
func (c *Client) LockFile(path string) (Lock, error) { lockRes, _, err := c.client.Lock(c.Remote, &lockRequest{ Path: path, Ref: &lockRef{Name: c.RemoteRef.Refspec()}, }) if err != nil { return Lock{}, errors.Wrap(err, "api") } if len(lockRes.Message) > 0 { if len(lockRes.RequestID) > 0 { tracerx.Printf("Server Request ID: %s", lockRes.RequestID) } return Lock{}, fmt.Errorf("Server unable to create lock: %s", lockRes.Message) } lock := *lockRes.Lock if err := c.cache.Add(lock); err != nil { return Lock{}, errors.Wrap(err, "lock cache") } abs, err := getAbsolutePath(path) if err != nil { return Lock{}, errors.Wrap(err, "make lockpath absolute") } // Ensure writeable on return if err := tools.SetFileWriteFlag(abs, true); err != nil { return Lock{}, err } return lock, nil }
[ "func", "(", "c", "*", "Client", ")", "LockFile", "(", "path", "string", ")", "(", "Lock", ",", "error", ")", "{", "lockRes", ",", "_", ",", "err", ":=", "c", ".", "client", ".", "Lock", "(", "c", ".", "Remote", ",", "&", "lockRequest", "{", "P...
// LockFile attempts to lock a file on the current remote // path must be relative to the root of the repository // Returns the lock id if successful, or an error
[ "LockFile", "attempts", "to", "lock", "a", "file", "on", "the", "current", "remote", "path", "must", "be", "relative", "to", "the", "root", "of", "the", "repository", "Returns", "the", "lock", "id", "if", "successful", "or", "an", "error" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/locks.go#L102-L134
157,347
git-lfs/git-lfs
locking/locks.go
UnlockFile
func (c *Client) UnlockFile(path string, force bool) error { id, err := c.lockIdFromPath(path) if err != nil { return fmt.Errorf("Unable to get lock id: %v", err) } return c.UnlockFileById(id, force) }
go
func (c *Client) UnlockFile(path string, force bool) error { id, err := c.lockIdFromPath(path) if err != nil { return fmt.Errorf("Unable to get lock id: %v", err) } return c.UnlockFileById(id, force) }
[ "func", "(", "c", "*", "Client", ")", "UnlockFile", "(", "path", "string", ",", "force", "bool", ")", "error", "{", "id", ",", "err", ":=", "c", ".", "lockIdFromPath", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "...
// UnlockFile attempts to unlock a file on the current remote // path must be relative to the root of the repository // Force causes the file to be unlocked from other users as well
[ "UnlockFile", "attempts", "to", "unlock", "a", "file", "on", "the", "current", "remote", "path", "must", "be", "relative", "to", "the", "root", "of", "the", "repository", "Force", "causes", "the", "file", "to", "be", "unlocked", "from", "other", "users", "...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/locks.go#L154-L161
157,348
git-lfs/git-lfs
locking/locks.go
UnlockFileById
func (c *Client) UnlockFileById(id string, force bool) error { unlockRes, _, err := c.client.Unlock(c.RemoteRef, c.Remote, id, force) if err != nil { return errors.Wrap(err, "api") } if len(unlockRes.Message) > 0 { if len(unlockRes.RequestID) > 0 { tracerx.Printf("Server Request ID: %s", unlockRes.RequestID) } return fmt.Errorf("Server unable to unlock: %s", unlockRes.Message) } if err := c.cache.RemoveById(id); err != nil { return fmt.Errorf("Error caching unlock information: %v", err) } if unlockRes.Lock != nil { abs, err := getAbsolutePath(unlockRes.Lock.Path) if err != nil { return errors.Wrap(err, "make lockpath absolute") } // Make non-writeable if required if c.SetLockableFilesReadOnly && c.IsFileLockable(unlockRes.Lock.Path) { return tools.SetFileWriteFlag(abs, false) } } return nil }
go
func (c *Client) UnlockFileById(id string, force bool) error { unlockRes, _, err := c.client.Unlock(c.RemoteRef, c.Remote, id, force) if err != nil { return errors.Wrap(err, "api") } if len(unlockRes.Message) > 0 { if len(unlockRes.RequestID) > 0 { tracerx.Printf("Server Request ID: %s", unlockRes.RequestID) } return fmt.Errorf("Server unable to unlock: %s", unlockRes.Message) } if err := c.cache.RemoveById(id); err != nil { return fmt.Errorf("Error caching unlock information: %v", err) } if unlockRes.Lock != nil { abs, err := getAbsolutePath(unlockRes.Lock.Path) if err != nil { return errors.Wrap(err, "make lockpath absolute") } // Make non-writeable if required if c.SetLockableFilesReadOnly && c.IsFileLockable(unlockRes.Lock.Path) { return tools.SetFileWriteFlag(abs, false) } } return nil }
[ "func", "(", "c", "*", "Client", ")", "UnlockFileById", "(", "id", "string", ",", "force", "bool", ")", "error", "{", "unlockRes", ",", "_", ",", "err", ":=", "c", ".", "client", ".", "Unlock", "(", "c", ".", "RemoteRef", ",", "c", ".", "Remote", ...
// UnlockFileById attempts to unlock a lock with a given id on the current remote // Force causes the file to be unlocked from other users as well
[ "UnlockFileById", "attempts", "to", "unlock", "a", "lock", "with", "a", "given", "id", "on", "the", "current", "remote", "Force", "causes", "the", "file", "to", "be", "unlocked", "from", "other", "users", "as", "well" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/locks.go#L165-L195
157,349
git-lfs/git-lfs
locking/locks.go
IsFileLockedByCurrentCommitter
func (c *Client) IsFileLockedByCurrentCommitter(path string) bool { filter := map[string]string{"path": path} locks, err := c.searchLocalLocks(filter, 1) if err != nil { tracerx.Printf("Error searching cached locks: %s\nForcing remote search", err) locks, _ = c.searchRemoteLocks(filter, 1) } return len(locks) > 0 }
go
func (c *Client) IsFileLockedByCurrentCommitter(path string) bool { filter := map[string]string{"path": path} locks, err := c.searchLocalLocks(filter, 1) if err != nil { tracerx.Printf("Error searching cached locks: %s\nForcing remote search", err) locks, _ = c.searchRemoteLocks(filter, 1) } return len(locks) > 0 }
[ "func", "(", "c", "*", "Client", ")", "IsFileLockedByCurrentCommitter", "(", "path", "string", ")", "bool", "{", "filter", ":=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "path", "}", "\n", "locks", ",", "err", ":=", "c", ".", "searc...
// IsFileLockedByCurrentCommitter returns whether a file is locked by the // current user, as cached locally
[ "IsFileLockedByCurrentCommitter", "returns", "whether", "a", "file", "is", "locked", "by", "the", "current", "user", "as", "cached", "locally" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/locks.go#L423-L431
157,350
git-lfs/git-lfs
git/gitattr/tree.go
linesInTree
func linesInTree(db *gitobj.ObjectDatabase, t *gitobj.Tree) ([]*Line, string, error) { var at int = -1 for i, e := range t.Entries { if e.Name == ".gitattributes" { at = i break } } if at < 0 { return nil, "", nil } blob, err := db.Blob(t.Entries[at].Oid) if err != nil { return nil, "", err } defer blob.Close() return ParseLines(blob.Contents) }
go
func linesInTree(db *gitobj.ObjectDatabase, t *gitobj.Tree) ([]*Line, string, error) { var at int = -1 for i, e := range t.Entries { if e.Name == ".gitattributes" { at = i break } } if at < 0 { return nil, "", nil } blob, err := db.Blob(t.Entries[at].Oid) if err != nil { return nil, "", err } defer blob.Close() return ParseLines(blob.Contents) }
[ "func", "linesInTree", "(", "db", "*", "gitobj", ".", "ObjectDatabase", ",", "t", "*", "gitobj", ".", "Tree", ")", "(", "[", "]", "*", "Line", ",", "string", ",", "error", ")", "{", "var", "at", "int", "=", "-", "1", "\n", "for", "i", ",", "e",...
// linesInTree parses a given tree's .gitattributes and returns a slice of lines // in that .gitattributes, or an error. If no .gitattributes blob was found, // return nil.
[ "linesInTree", "parses", "a", "given", "tree", "s", ".", "gitattributes", "and", "returns", "a", "slice", "of", "lines", "in", "that", ".", "gitattributes", "or", "an", "error", ".", "If", "no", ".", "gitattributes", "blob", "was", "found", "return", "nil"...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/gitattr/tree.go#L62-L82
157,351
git-lfs/git-lfs
git/gitattr/tree.go
Applied
func (t *Tree) Applied(to string) []*Attr { var attrs []*Attr for _, line := range t.Lines { if line.Pattern.Match(to) { attrs = append(attrs, line.Attrs...) } } splits := strings.SplitN(to, "/", 2) if len(splits) == 2 { car, cdr := splits[0], splits[1] if child, ok := t.Children[car]; ok { attrs = append(attrs, child.Applied(cdr)...) } } return attrs }
go
func (t *Tree) Applied(to string) []*Attr { var attrs []*Attr for _, line := range t.Lines { if line.Pattern.Match(to) { attrs = append(attrs, line.Attrs...) } } splits := strings.SplitN(to, "/", 2) if len(splits) == 2 { car, cdr := splits[0], splits[1] if child, ok := t.Children[car]; ok { attrs = append(attrs, child.Applied(cdr)...) } } return attrs }
[ "func", "(", "t", "*", "Tree", ")", "Applied", "(", "to", "string", ")", "[", "]", "*", "Attr", "{", "var", "attrs", "[", "]", "*", "Attr", "\n", "for", "_", ",", "line", ":=", "range", "t", ".", "Lines", "{", "if", "line", ".", "Pattern", "....
// Applied returns a slice of attributes applied to the given path, relative to // the receiving tree. It traverse through sub-trees in a topological ordering, // if there are relevant .gitattributes matching that path.
[ "Applied", "returns", "a", "slice", "of", "attributes", "applied", "to", "the", "given", "path", "relative", "to", "the", "receiving", "tree", ".", "It", "traverse", "through", "sub", "-", "trees", "in", "a", "topological", "ordering", "if", "there", "are", ...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/gitattr/tree.go#L87-L104
157,352
git-lfs/git-lfs
tq/meter.go
NewMeter
func NewMeter(cfg *config.Configuration) *Meter { m := &Meter{ fileIndex: make(map[string]int64), fileIndexMutex: &sync.Mutex{}, updates: make(chan *tasklog.Update), cfg: cfg, } return m }
go
func NewMeter(cfg *config.Configuration) *Meter { m := &Meter{ fileIndex: make(map[string]int64), fileIndexMutex: &sync.Mutex{}, updates: make(chan *tasklog.Update), cfg: cfg, } return m }
[ "func", "NewMeter", "(", "cfg", "*", "config", ".", "Configuration", ")", "*", "Meter", "{", "m", ":=", "&", "Meter", "{", "fileIndex", ":", "make", "(", "map", "[", "string", "]", "int64", ")", ",", "fileIndexMutex", ":", "&", "sync", ".", "Mutex", ...
// NewMeter creates a new Meter.
[ "NewMeter", "creates", "a", "new", "Meter", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/meter.go#L80-L89
157,353
git-lfs/git-lfs
tq/meter.go
Skip
func (m *Meter) Skip(size int64) { if m == nil { return } defer m.update(false) atomic.AddInt64(&m.finishedFiles, 1) atomic.AddInt64(&m.currentBytes, size) }
go
func (m *Meter) Skip(size int64) { if m == nil { return } defer m.update(false) atomic.AddInt64(&m.finishedFiles, 1) atomic.AddInt64(&m.currentBytes, size) }
[ "func", "(", "m", "*", "Meter", ")", "Skip", "(", "size", "int64", ")", "{", "if", "m", "==", "nil", "{", "return", "\n", "}", "\n\n", "defer", "m", ".", "update", "(", "false", ")", "\n", "atomic", ".", "AddInt64", "(", "&", "m", ".", "finishe...
// Skip tells the progress meter that a file of size `size` is being skipped // because the transfer is unnecessary.
[ "Skip", "tells", "the", "progress", "meter", "that", "a", "file", "of", "size", "size", "is", "being", "skipped", "because", "the", "transfer", "is", "unnecessary", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/meter.go#L122-L130
157,354
git-lfs/git-lfs
tq/meter.go
StartTransfer
func (m *Meter) StartTransfer(name string) { if m == nil { return } defer m.update(false) idx := atomic.AddInt64(&m.transferringFiles, 1) m.fileIndexMutex.Lock() m.fileIndex[name] = idx m.fileIndexMutex.Unlock() }
go
func (m *Meter) StartTransfer(name string) { if m == nil { return } defer m.update(false) idx := atomic.AddInt64(&m.transferringFiles, 1) m.fileIndexMutex.Lock() m.fileIndex[name] = idx m.fileIndexMutex.Unlock() }
[ "func", "(", "m", "*", "Meter", ")", "StartTransfer", "(", "name", "string", ")", "{", "if", "m", "==", "nil", "{", "return", "\n", "}", "\n\n", "defer", "m", ".", "update", "(", "false", ")", "\n", "idx", ":=", "atomic", ".", "AddInt64", "(", "&...
// StartTransfer tells the progress meter that a transferring file is being // added to the TransferQueue.
[ "StartTransfer", "tells", "the", "progress", "meter", "that", "a", "transferring", "file", "is", "being", "added", "to", "the", "TransferQueue", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/meter.go#L134-L144
157,355
git-lfs/git-lfs
tq/meter.go
TransferBytes
func (m *Meter) TransferBytes(direction, name string, read, total int64, current int) { if m == nil { return } defer m.update(false) now := time.Now() since := now.Sub(m.lastAvg) atomic.AddInt64(&m.currentBytes, int64(current)) atomic.AddInt64(&m.lastBytes, int64(current)) if since > time.Second { m.lastAvg = now bps := float64(m.lastBytes) / since.Seconds() m.avgBytes = (m.avgBytes*float64(m.sampleCount) + bps) / (float64(m.sampleCount) + 1.0) atomic.StoreInt64(&m.lastBytes, 0) atomic.AddUint64(&m.sampleCount, 1) } m.logBytes(direction, name, read, total) }
go
func (m *Meter) TransferBytes(direction, name string, read, total int64, current int) { if m == nil { return } defer m.update(false) now := time.Now() since := now.Sub(m.lastAvg) atomic.AddInt64(&m.currentBytes, int64(current)) atomic.AddInt64(&m.lastBytes, int64(current)) if since > time.Second { m.lastAvg = now bps := float64(m.lastBytes) / since.Seconds() m.avgBytes = (m.avgBytes*float64(m.sampleCount) + bps) / (float64(m.sampleCount) + 1.0) atomic.StoreInt64(&m.lastBytes, 0) atomic.AddUint64(&m.sampleCount, 1) } m.logBytes(direction, name, read, total) }
[ "func", "(", "m", "*", "Meter", ")", "TransferBytes", "(", "direction", ",", "name", "string", ",", "read", ",", "total", "int64", ",", "current", "int", ")", "{", "if", "m", "==", "nil", "{", "return", "\n", "}", "\n\n", "defer", "m", ".", "update...
// TransferBytes increments the number of bytes transferred
[ "TransferBytes", "increments", "the", "number", "of", "bytes", "transferred" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/meter.go#L147-L171
157,356
git-lfs/git-lfs
tq/meter.go
FinishTransfer
func (m *Meter) FinishTransfer(name string) { if m == nil { return } defer m.update(false) atomic.AddInt64(&m.finishedFiles, 1) m.fileIndexMutex.Lock() delete(m.fileIndex, name) m.fileIndexMutex.Unlock() }
go
func (m *Meter) FinishTransfer(name string) { if m == nil { return } defer m.update(false) atomic.AddInt64(&m.finishedFiles, 1) m.fileIndexMutex.Lock() delete(m.fileIndex, name) m.fileIndexMutex.Unlock() }
[ "func", "(", "m", "*", "Meter", ")", "FinishTransfer", "(", "name", "string", ")", "{", "if", "m", "==", "nil", "{", "return", "\n", "}", "\n\n", "defer", "m", ".", "update", "(", "false", ")", "\n", "atomic", ".", "AddInt64", "(", "&", "m", ".",...
// FinishTransfer increments the finished transfer count
[ "FinishTransfer", "increments", "the", "finished", "transfer", "count" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/meter.go#L174-L184
157,357
git-lfs/git-lfs
tq/meter.go
Finish
func (m *Meter) Finish() { if m == nil { return } m.update(false) close(m.updates) }
go
func (m *Meter) Finish() { if m == nil { return } m.update(false) close(m.updates) }
[ "func", "(", "m", "*", "Meter", ")", "Finish", "(", ")", "{", "if", "m", "==", "nil", "{", "return", "\n", "}", "\n\n", "m", ".", "update", "(", "false", ")", "\n", "close", "(", "m", ".", "updates", ")", "\n", "}" ]
// Finish shuts down the Meter.
[ "Finish", "shuts", "down", "the", "Meter", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/meter.go#L196-L203
157,358
git-lfs/git-lfs
tq/meter.go
clamp
func clamp(x int64) uint64 { if x < 0 { return 0 } if x > math.MaxInt64 { return math.MaxUint64 } return uint64(x) }
go
func clamp(x int64) uint64 { if x < 0 { return 0 } if x > math.MaxInt64 { return math.MaxUint64 } return uint64(x) }
[ "func", "clamp", "(", "x", "int64", ")", "uint64", "{", "if", "x", "<", "0", "{", "return", "0", "\n", "}", "\n", "if", "x", ">", "math", ".", "MaxInt64", "{", "return", "math", ".", "MaxUint64", "\n", "}", "\n", "return", "uint64", "(", "x", "...
// clamp clamps the given "x" within the acceptable domain of the uint64 integer // type, so as to prevent over- and underflow.
[ "clamp", "clamps", "the", "given", "x", "within", "the", "acceptable", "domain", "of", "the", "uint64", "integer", "type", "so", "as", "to", "prevent", "over", "-", "and", "underflow", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/meter.go#L248-L256
157,359
git-lfs/git-lfs
commands/command_post_merge.go
postMergeCommand
func postMergeCommand(cmd *cobra.Command, args []string) { if len(args) != 1 { Print("This should be run through Git's post-merge hook. Run `git lfs update` to install it.") os.Exit(1) } // Skip entire hook if lockable read only feature is disabled if !cfg.SetLockableFilesReadOnly() { os.Exit(0) } requireGitVersion() lockClient := newLockClient() // Skip this hook if no lockable patterns have been configured if len(lockClient.GetLockablePatterns()) == 0 { os.Exit(0) } // The only argument this hook receives is a flag indicating whether the // merge was a squash merge; we don't know what files changed. // Whether it's squash or not is irrelevant, either way it could have // reset the read-only flag on files that got merged. tracerx.Printf("post-merge: checking write flags for all lockable files") // Sadly we don't get any information about what files were checked out, // so we have to check the entire repo err := lockClient.FixAllLockableFileWriteFlags() if err != nil { LoggedError(err, "Warning: post-merge locked file check failed: %v", err) } }
go
func postMergeCommand(cmd *cobra.Command, args []string) { if len(args) != 1 { Print("This should be run through Git's post-merge hook. Run `git lfs update` to install it.") os.Exit(1) } // Skip entire hook if lockable read only feature is disabled if !cfg.SetLockableFilesReadOnly() { os.Exit(0) } requireGitVersion() lockClient := newLockClient() // Skip this hook if no lockable patterns have been configured if len(lockClient.GetLockablePatterns()) == 0 { os.Exit(0) } // The only argument this hook receives is a flag indicating whether the // merge was a squash merge; we don't know what files changed. // Whether it's squash or not is irrelevant, either way it could have // reset the read-only flag on files that got merged. tracerx.Printf("post-merge: checking write flags for all lockable files") // Sadly we don't get any information about what files were checked out, // so we have to check the entire repo err := lockClient.FixAllLockableFileWriteFlags() if err != nil { LoggedError(err, "Warning: post-merge locked file check failed: %v", err) } }
[ "func", "postMergeCommand", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "len", "(", "args", ")", "!=", "1", "{", "Print", "(", "\"", "\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", ...
// postMergeCommand is run through Git's post-merge hook. // // This hook checks that files which are lockable and not locked are made read-only, // optimising that as best it can based on the available information.
[ "postMergeCommand", "is", "run", "through", "Git", "s", "post", "-", "merge", "hook", ".", "This", "hook", "checks", "that", "files", "which", "are", "lockable", "and", "not", "locked", "are", "made", "read", "-", "only", "optimising", "that", "as", "best"...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_post_merge.go#L14-L46
157,360
git-lfs/git-lfs
git/filter_process_scanner.go
Init
func (o *FilterProcessScanner) Init() error { tracerx.Printf("Initialize filter-process") reqVer := "version=2" initMsg, err := o.pl.readPacketText() if err != nil { return errors.Wrap(err, "reading filter-process initialization") } if initMsg != "git-filter-client" { return fmt.Errorf("invalid filter-process pkt-line welcome message: %s", initMsg) } supVers, err := o.pl.readPacketList() if err != nil { return errors.Wrap(err, "reading filter-process versions") } if !isStringInSlice(supVers, reqVer) { return fmt.Errorf("filter '%s' not supported (your Git supports: %s)", reqVer, supVers) } err = o.pl.writePacketList([]string{"git-filter-server", reqVer}) if err != nil { return errors.Wrap(err, "writing filter-process initialization failed") } return nil }
go
func (o *FilterProcessScanner) Init() error { tracerx.Printf("Initialize filter-process") reqVer := "version=2" initMsg, err := o.pl.readPacketText() if err != nil { return errors.Wrap(err, "reading filter-process initialization") } if initMsg != "git-filter-client" { return fmt.Errorf("invalid filter-process pkt-line welcome message: %s", initMsg) } supVers, err := o.pl.readPacketList() if err != nil { return errors.Wrap(err, "reading filter-process versions") } if !isStringInSlice(supVers, reqVer) { return fmt.Errorf("filter '%s' not supported (your Git supports: %s)", reqVer, supVers) } err = o.pl.writePacketList([]string{"git-filter-server", reqVer}) if err != nil { return errors.Wrap(err, "writing filter-process initialization failed") } return nil }
[ "func", "(", "o", "*", "FilterProcessScanner", ")", "Init", "(", ")", "error", "{", "tracerx", ".", "Printf", "(", "\"", "\"", ")", "\n", "reqVer", ":=", "\"", "\"", "\n\n", "initMsg", ",", "err", ":=", "o", ".", "pl", ".", "readPacketText", "(", "...
// Init initializes the filter and ACKs back and forth between the Git LFS // subprocess and the Git parent process that each is a git-filter-server and // client respectively. // // If either side wrote an invalid sequence of data, or did not meet // expectations, an error will be returned. If the filter type is not supported, // an error will be returned. If the pkt-line welcome message was invalid, an // error will be returned. // // If there was an error reading or writing any of the packets below, an error // will be returned.
[ "Init", "initializes", "the", "filter", "and", "ACKs", "back", "and", "forth", "between", "the", "Git", "LFS", "subprocess", "and", "the", "Git", "parent", "process", "that", "each", "is", "a", "git", "-", "filter", "-", "server", "and", "client", "respect...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/filter_process_scanner.go#L69-L94
157,361
git-lfs/git-lfs
git/filter_process_scanner.go
NegotiateCapabilities
func (o *FilterProcessScanner) NegotiateCapabilities() ([]string, error) { reqCaps := []string{"capability=clean", "capability=smudge"} supCaps, err := o.pl.readPacketList() if err != nil { return nil, fmt.Errorf("reading filter-process capabilities failed with %s", err) } for _, sup := range supCaps { if sup == "capability=delay" { reqCaps = append(reqCaps, "capability=delay") break } } for _, reqCap := range reqCaps { if !isStringInSlice(supCaps, reqCap) { return nil, fmt.Errorf("filter '%s' not supported (your Git supports: %s)", reqCap, supCaps) } } err = o.pl.writePacketList(reqCaps) if err != nil { return nil, fmt.Errorf("writing filter-process capabilities failed with %s", err) } return supCaps, nil }
go
func (o *FilterProcessScanner) NegotiateCapabilities() ([]string, error) { reqCaps := []string{"capability=clean", "capability=smudge"} supCaps, err := o.pl.readPacketList() if err != nil { return nil, fmt.Errorf("reading filter-process capabilities failed with %s", err) } for _, sup := range supCaps { if sup == "capability=delay" { reqCaps = append(reqCaps, "capability=delay") break } } for _, reqCap := range reqCaps { if !isStringInSlice(supCaps, reqCap) { return nil, fmt.Errorf("filter '%s' not supported (your Git supports: %s)", reqCap, supCaps) } } err = o.pl.writePacketList(reqCaps) if err != nil { return nil, fmt.Errorf("writing filter-process capabilities failed with %s", err) } return supCaps, nil }
[ "func", "(", "o", "*", "FilterProcessScanner", ")", "NegotiateCapabilities", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "reqCaps", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", "\n\n", "supCaps", ",", "err", ":=", ...
// NegotiateCapabilities executes the process of negotiating capabilities // between the filter client and server. If we don't support any of the // capabilities given to LFS by Git, an error will be returned. If there was an // error reading or writing capabilities between the two, an error will be // returned.
[ "NegotiateCapabilities", "executes", "the", "process", "of", "negotiating", "capabilities", "between", "the", "filter", "client", "and", "server", ".", "If", "we", "don", "t", "support", "any", "of", "the", "capabilities", "given", "to", "LFS", "by", "Git", "a...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/filter_process_scanner.go#L101-L128
157,362
git-lfs/git-lfs
git/filter_process_scanner.go
readRequest
func (o *FilterProcessScanner) readRequest() (*Request, error) { requestList, err := o.pl.readPacketList() if err != nil { return nil, err } req := &Request{ Header: make(map[string]string), Payload: &pktlineReader{pl: o.pl}, } for _, pair := range requestList { v := strings.SplitN(pair, "=", 2) req.Header[v[0]] = v[1] } return req, nil }
go
func (o *FilterProcessScanner) readRequest() (*Request, error) { requestList, err := o.pl.readPacketList() if err != nil { return nil, err } req := &Request{ Header: make(map[string]string), Payload: &pktlineReader{pl: o.pl}, } for _, pair := range requestList { v := strings.SplitN(pair, "=", 2) req.Header[v[0]] = v[1] } return req, nil }
[ "func", "(", "o", "*", "FilterProcessScanner", ")", "readRequest", "(", ")", "(", "*", "Request", ",", "error", ")", "{", "requestList", ",", "err", ":=", "o", ".", "pl", ".", "readPacketList", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return",...
// readRequest reads the headers of a request and yields an `io.Reader` which // will read the body of the request. Since the body is _not_ offset, one // request should be read in its entirety before consuming the next request.
[ "readRequest", "reads", "the", "headers", "of", "a", "request", "and", "yields", "an", "io", ".", "Reader", "which", "will", "read", "the", "body", "of", "the", "request", ".", "Since", "the", "body", "is", "_not_", "offset", "one", "request", "should", ...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/filter_process_scanner.go#L174-L191
157,363
git-lfs/git-lfs
git/filter_process_scanner.go
WriteList
func (o *FilterProcessScanner) WriteList(list []string) error { return o.pl.writePacketList(list) }
go
func (o *FilterProcessScanner) WriteList(list []string) error { return o.pl.writePacketList(list) }
[ "func", "(", "o", "*", "FilterProcessScanner", ")", "WriteList", "(", "list", "[", "]", "string", ")", "error", "{", "return", "o", ".", "pl", ".", "writePacketList", "(", "list", ")", "\n", "}" ]
// WriteList writes a list of strings to the underlying pktline data stream in // pktline format.
[ "WriteList", "writes", "a", "list", "of", "strings", "to", "the", "underlying", "pktline", "data", "stream", "in", "pktline", "format", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/filter_process_scanner.go#L195-L197
157,364
git-lfs/git-lfs
lfshttp/retries.go
WithRetries
func WithRetries(req *http.Request, n int) *http.Request { ctx := req.Context() ctx = context.WithValue(ctx, contextKeyRetries, n) return req.WithContext(ctx) }
go
func WithRetries(req *http.Request, n int) *http.Request { ctx := req.Context() ctx = context.WithValue(ctx, contextKeyRetries, n) return req.WithContext(ctx) }
[ "func", "WithRetries", "(", "req", "*", "http", ".", "Request", ",", "n", "int", ")", "*", "http", ".", "Request", "{", "ctx", ":=", "req", ".", "Context", "(", ")", "\n", "ctx", "=", "context", ".", "WithValue", "(", "ctx", ",", "contextKeyRetries",...
// WithRetries stores the desired number of retries "n" on the given // http.Request, and causes it to be retried "n" times in the case of a non-nil // network related error.
[ "WithRetries", "stores", "the", "desired", "number", "of", "retries", "n", "on", "the", "given", "http", ".", "Request", "and", "causes", "it", "to", "be", "retried", "n", "times", "in", "the", "case", "of", "a", "non", "-", "nil", "network", "related", ...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfshttp/retries.go#L24-L29
157,365
git-lfs/git-lfs
lfshttp/retries.go
Retries
func Retries(req *http.Request) (int, bool) { n, ok := req.Context().Value(contextKeyRetries).(int) return n, ok }
go
func Retries(req *http.Request) (int, bool) { n, ok := req.Context().Value(contextKeyRetries).(int) return n, ok }
[ "func", "Retries", "(", "req", "*", "http", ".", "Request", ")", "(", "int", ",", "bool", ")", "{", "n", ",", "ok", ":=", "req", ".", "Context", "(", ")", ".", "Value", "(", "contextKeyRetries", ")", ".", "(", "int", ")", "\n\n", "return", "n", ...
// Retries returns the number of retries requested for a given http.Request.
[ "Retries", "returns", "the", "number", "of", "retries", "requested", "for", "a", "given", "http", ".", "Request", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfshttp/retries.go#L32-L36
157,366
git-lfs/git-lfs
tasklog/simple_task.go
Logf
func (s *SimpleTask) Logf(str string, vals ...interface{}) { s.ch <- &Update{ S: fmt.Sprintf(str, vals...), At: time.Now(), } }
go
func (s *SimpleTask) Logf(str string, vals ...interface{}) { s.ch <- &Update{ S: fmt.Sprintf(str, vals...), At: time.Now(), } }
[ "func", "(", "s", "*", "SimpleTask", ")", "Logf", "(", "str", "string", ",", "vals", "...", "interface", "{", "}", ")", "{", "s", ".", "ch", "<-", "&", "Update", "{", "S", ":", "fmt", ".", "Sprintf", "(", "str", ",", "vals", "...", ")", ",", ...
// Logf logs some formatted string, which is interpreted according to the rules // defined in package "fmt".
[ "Logf", "logs", "some", "formatted", "string", "which", "is", "interpreted", "according", "to", "the", "rules", "defined", "in", "package", "fmt", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tasklog/simple_task.go#L36-L41
157,367
git-lfs/git-lfs
tools/iotools.go
CopyWithCallback
func CopyWithCallback(writer io.Writer, reader io.Reader, totalSize int64, cb CopyCallback) (int64, error) { if success, _ := CloneFile(writer, reader); success { if cb != nil { cb(totalSize, totalSize, 0) } return totalSize, nil } if cb == nil { return io.Copy(writer, reader) } cbReader := &CallbackReader{ C: cb, TotalSize: totalSize, Reader: reader, } return io.Copy(writer, cbReader) }
go
func CopyWithCallback(writer io.Writer, reader io.Reader, totalSize int64, cb CopyCallback) (int64, error) { if success, _ := CloneFile(writer, reader); success { if cb != nil { cb(totalSize, totalSize, 0) } return totalSize, nil } if cb == nil { return io.Copy(writer, reader) } cbReader := &CallbackReader{ C: cb, TotalSize: totalSize, Reader: reader, } return io.Copy(writer, cbReader) }
[ "func", "CopyWithCallback", "(", "writer", "io", ".", "Writer", ",", "reader", "io", ".", "Reader", ",", "totalSize", "int64", ",", "cb", "CopyCallback", ")", "(", "int64", ",", "error", ")", "{", "if", "success", ",", "_", ":=", "CloneFile", "(", "wri...
// CopyWithCallback copies reader to writer while performing a progress callback
[ "CopyWithCallback", "copies", "reader", "to", "writer", "while", "performing", "a", "progress", "callback" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/iotools.go#L23-L40
157,368
git-lfs/git-lfs
tools/iotools.go
Spool
func Spool(to io.Writer, from io.Reader, dir string) (n int64, err error) { // First, buffer up to `memoryBufferLimit` in memory. buf := make([]byte, memoryBufferLimit) if bn, err := from.Read(buf); err != nil && err != io.EOF { return int64(bn), err } else { buf = buf[:bn] } var spool io.Reader = bytes.NewReader(buf) if err != io.EOF { // If we weren't at the end of the stream, create a temporary // file, and spool the remaining contents there. tmp, err := ioutil.TempFile(dir, "") if err != nil { return 0, errors.Wrap(err, "spool tmp") } defer os.Remove(tmp.Name()) if n, err = io.Copy(tmp, from); err != nil { return n, errors.Wrap(err, "unable to spool") } if _, err = tmp.Seek(0, io.SeekStart); err != nil { return 0, errors.Wrap(err, "unable to seek") } // The spooled contents will now be the concatenation of the // contents we stored in memory, then the remainder of the // contents on disk. spool = io.MultiReader(spool, tmp) } return io.Copy(to, spool) }
go
func Spool(to io.Writer, from io.Reader, dir string) (n int64, err error) { // First, buffer up to `memoryBufferLimit` in memory. buf := make([]byte, memoryBufferLimit) if bn, err := from.Read(buf); err != nil && err != io.EOF { return int64(bn), err } else { buf = buf[:bn] } var spool io.Reader = bytes.NewReader(buf) if err != io.EOF { // If we weren't at the end of the stream, create a temporary // file, and spool the remaining contents there. tmp, err := ioutil.TempFile(dir, "") if err != nil { return 0, errors.Wrap(err, "spool tmp") } defer os.Remove(tmp.Name()) if n, err = io.Copy(tmp, from); err != nil { return n, errors.Wrap(err, "unable to spool") } if _, err = tmp.Seek(0, io.SeekStart); err != nil { return 0, errors.Wrap(err, "unable to seek") } // The spooled contents will now be the concatenation of the // contents we stored in memory, then the remainder of the // contents on disk. spool = io.MultiReader(spool, tmp) } return io.Copy(to, spool) }
[ "func", "Spool", "(", "to", "io", ".", "Writer", ",", "from", "io", ".", "Reader", ",", "dir", "string", ")", "(", "n", "int64", ",", "err", "error", ")", "{", "// First, buffer up to `memoryBufferLimit` in memory.", "buf", ":=", "make", "(", "[", "]", "...
// Spool spools the contents from 'from' to 'to' by buffering the entire // contents of 'from' into a temprorary file created in the directory "dir". // That buffer is held in memory until the file grows to larger than // 'memoryBufferLimit`, then the remaining contents are spooled to disk. // // The temporary file is cleaned up after the copy is complete. // // The number of bytes written to "to", as well as any error encountered are // returned.
[ "Spool", "spools", "the", "contents", "from", "from", "to", "to", "by", "buffering", "the", "entire", "contents", "of", "from", "into", "a", "temprorary", "file", "created", "in", "the", "directory", "dir", ".", "That", "buffer", "is", "held", "in", "memor...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/iotools.go#L111-L145
157,369
git-lfs/git-lfs
lfs/gitscanner_tree.go
lsTreeBlobs
func lsTreeBlobs(ref string, filter *filepathfilter.Filter) (*TreeBlobChannelWrapper, error) { cmd, err := git.LsTree(ref) if err != nil { return nil, err } cmd.Stdin.Close() blobs := make(chan TreeBlob, chanBufSize) errchan := make(chan error, 1) go func() { scanner := newLsTreeScanner(cmd.Stdout) for scanner.Scan() { if t := scanner.TreeBlob(); t != nil && filter.Allows(t.Filename) { blobs <- *t } } stderr, _ := ioutil.ReadAll(cmd.Stderr) err := cmd.Wait() if err != nil { errchan <- fmt.Errorf("Error in git ls-tree: %v %v", err, string(stderr)) } close(blobs) close(errchan) }() return NewTreeBlobChannelWrapper(blobs, errchan), nil }
go
func lsTreeBlobs(ref string, filter *filepathfilter.Filter) (*TreeBlobChannelWrapper, error) { cmd, err := git.LsTree(ref) if err != nil { return nil, err } cmd.Stdin.Close() blobs := make(chan TreeBlob, chanBufSize) errchan := make(chan error, 1) go func() { scanner := newLsTreeScanner(cmd.Stdout) for scanner.Scan() { if t := scanner.TreeBlob(); t != nil && filter.Allows(t.Filename) { blobs <- *t } } stderr, _ := ioutil.ReadAll(cmd.Stderr) err := cmd.Wait() if err != nil { errchan <- fmt.Errorf("Error in git ls-tree: %v %v", err, string(stderr)) } close(blobs) close(errchan) }() return NewTreeBlobChannelWrapper(blobs, errchan), nil }
[ "func", "lsTreeBlobs", "(", "ref", "string", ",", "filter", "*", "filepathfilter", ".", "Filter", ")", "(", "*", "TreeBlobChannelWrapper", ",", "error", ")", "{", "cmd", ",", "err", ":=", "git", ".", "LsTree", "(", "ref", ")", "\n", "if", "err", "!=", ...
// Use ls-tree at ref to find a list of candidate tree blobs which might be lfs files // The returned channel will be sent these blobs which should be sent to catFileBatchTree // for final check & conversion to Pointer
[ "Use", "ls", "-", "tree", "at", "ref", "to", "find", "a", "list", "of", "candidate", "tree", "blobs", "which", "might", "be", "lfs", "files", "The", "returned", "channel", "will", "be", "sent", "these", "blobs", "which", "should", "be", "sent", "to", "...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfs/gitscanner_tree.go#L101-L130
157,370
git-lfs/git-lfs
docs/man/mangen.go
main
func main() { flag.Parse() infof(os.Stderr, "Converting man pages into code...\n") rootDir, fs := readManDir() manDir := filepath.Join(rootDir, "docs", "man") out, err := os.Create(filepath.Join(rootDir, "commands", "mancontent_gen.go")) if err != nil { warnf(os.Stderr, "Failed to create go file: %v\n", err) os.Exit(2) } out.WriteString("package commands\n\nfunc init() {\n") out.WriteString("// THIS FILE IS GENERATED, DO NOT EDIT\n") out.WriteString("// Use 'go generate ./commands' to update\n") fileregex := regexp.MustCompile(`git-lfs(?:-([A-Za-z\-]+))?.\d.ronn`) headerregex := regexp.MustCompile(`^###?\s+([A-Za-z0-9 ]+)`) // only pick up caps in links to avoid matching optional args linkregex := regexp.MustCompile(`\[([A-Z\- ]+)\]`) // man links manlinkregex := regexp.MustCompile(`(git)(?:-(lfs))?-([a-z\-]+)\(\d\)`) count := 0 for _, f := range fs { if match := fileregex.FindStringSubmatch(f.Name()); match != nil { infof(os.Stderr, "%v\n", f.Name()) cmd := match[1] if len(cmd) == 0 { // This is git-lfs.1.ronn cmd = "git-lfs" } out.WriteString("ManPages[\"" + cmd + "\"] = `") contentf, err := os.Open(filepath.Join(manDir, f.Name())) if err != nil { warnf(os.Stderr, "Failed to open %v: %v\n", f.Name(), err) os.Exit(2) } // Process the ronn to make it nicer as help text scanner := bufio.NewScanner(contentf) firstHeaderDone := false skipNextLineIfBlank := false lastLineWasBullet := false scanloop: for scanner.Scan() { line := scanner.Text() trimmedline := strings.TrimSpace(line) if skipNextLineIfBlank && len(trimmedline) == 0 { skipNextLineIfBlank = false lastLineWasBullet = false continue } // Special case headers if hmatch := headerregex.FindStringSubmatch(line); hmatch != nil { header := strings.ToLower(hmatch[1]) switch header { case "synopsis": // Ignore this, just go direct to command case "description": // Just skip the header & newline skipNextLineIfBlank = true case "options": out.WriteString("Options:" + "\n") case "see also": // don't include any content after this break scanloop default: out.WriteString(strings.ToUpper(header[:1]) + header[1:] + "\n") out.WriteString(strings.Repeat("-", len(header)) + "\n") } firstHeaderDone = true lastLineWasBullet = false continue } if lmatches := linkregex.FindAllStringSubmatch(line, -1); lmatches != nil { for _, lmatch := range lmatches { linktext := strings.ToLower(lmatch[1]) line = strings.Replace(line, lmatch[0], `"`+strings.ToUpper(linktext[:1])+linktext[1:]+`"`, 1) } } if manmatches := manlinkregex.FindAllStringSubmatch(line, -1); manmatches != nil { for _, manmatch := range manmatches { line = strings.Replace(line, manmatch[0], strings.Join(manmatch[1:], " "), 1) } } // Skip content until after first header if !firstHeaderDone { continue } // OK, content here // remove characters that markdown would render invisible in a text env. for _, invis := range []string{"`", "<br>"} { line = strings.Replace(line, invis, "", -1) } // indent bullets if strings.HasPrefix(line, "*") { lastLineWasBullet = true } else if lastLineWasBullet && !strings.HasPrefix(line, " ") { // indent paragraphs under bullets if not already done line = " " + line } out.WriteString(line + "\n") } out.WriteString("`\n") contentf.Close() count++ } } out.WriteString("}\n") infof(os.Stderr, "Successfully processed %d man pages.\n", count) }
go
func main() { flag.Parse() infof(os.Stderr, "Converting man pages into code...\n") rootDir, fs := readManDir() manDir := filepath.Join(rootDir, "docs", "man") out, err := os.Create(filepath.Join(rootDir, "commands", "mancontent_gen.go")) if err != nil { warnf(os.Stderr, "Failed to create go file: %v\n", err) os.Exit(2) } out.WriteString("package commands\n\nfunc init() {\n") out.WriteString("// THIS FILE IS GENERATED, DO NOT EDIT\n") out.WriteString("// Use 'go generate ./commands' to update\n") fileregex := regexp.MustCompile(`git-lfs(?:-([A-Za-z\-]+))?.\d.ronn`) headerregex := regexp.MustCompile(`^###?\s+([A-Za-z0-9 ]+)`) // only pick up caps in links to avoid matching optional args linkregex := regexp.MustCompile(`\[([A-Z\- ]+)\]`) // man links manlinkregex := regexp.MustCompile(`(git)(?:-(lfs))?-([a-z\-]+)\(\d\)`) count := 0 for _, f := range fs { if match := fileregex.FindStringSubmatch(f.Name()); match != nil { infof(os.Stderr, "%v\n", f.Name()) cmd := match[1] if len(cmd) == 0 { // This is git-lfs.1.ronn cmd = "git-lfs" } out.WriteString("ManPages[\"" + cmd + "\"] = `") contentf, err := os.Open(filepath.Join(manDir, f.Name())) if err != nil { warnf(os.Stderr, "Failed to open %v: %v\n", f.Name(), err) os.Exit(2) } // Process the ronn to make it nicer as help text scanner := bufio.NewScanner(contentf) firstHeaderDone := false skipNextLineIfBlank := false lastLineWasBullet := false scanloop: for scanner.Scan() { line := scanner.Text() trimmedline := strings.TrimSpace(line) if skipNextLineIfBlank && len(trimmedline) == 0 { skipNextLineIfBlank = false lastLineWasBullet = false continue } // Special case headers if hmatch := headerregex.FindStringSubmatch(line); hmatch != nil { header := strings.ToLower(hmatch[1]) switch header { case "synopsis": // Ignore this, just go direct to command case "description": // Just skip the header & newline skipNextLineIfBlank = true case "options": out.WriteString("Options:" + "\n") case "see also": // don't include any content after this break scanloop default: out.WriteString(strings.ToUpper(header[:1]) + header[1:] + "\n") out.WriteString(strings.Repeat("-", len(header)) + "\n") } firstHeaderDone = true lastLineWasBullet = false continue } if lmatches := linkregex.FindAllStringSubmatch(line, -1); lmatches != nil { for _, lmatch := range lmatches { linktext := strings.ToLower(lmatch[1]) line = strings.Replace(line, lmatch[0], `"`+strings.ToUpper(linktext[:1])+linktext[1:]+`"`, 1) } } if manmatches := manlinkregex.FindAllStringSubmatch(line, -1); manmatches != nil { for _, manmatch := range manmatches { line = strings.Replace(line, manmatch[0], strings.Join(manmatch[1:], " "), 1) } } // Skip content until after first header if !firstHeaderDone { continue } // OK, content here // remove characters that markdown would render invisible in a text env. for _, invis := range []string{"`", "<br>"} { line = strings.Replace(line, invis, "", -1) } // indent bullets if strings.HasPrefix(line, "*") { lastLineWasBullet = true } else if lastLineWasBullet && !strings.HasPrefix(line, " ") { // indent paragraphs under bullets if not already done line = " " + line } out.WriteString(line + "\n") } out.WriteString("`\n") contentf.Close() count++ } } out.WriteString("}\n") infof(os.Stderr, "Successfully processed %d man pages.\n", count) }
[ "func", "main", "(", ")", "{", "flag", ".", "Parse", "(", ")", "\n\n", "infof", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ")", "\n", "rootDir", ",", "fs", ":=", "readManDir", "(", ")", "\n", "manDir", ":=", "filepath", ".", "Join", "(", ...
// Reads all .ronn files & and converts them to string literals // triggered by "go generate" comment // Literals are inserted into a map using an init function, this means // that there are no compilation errors if 'go generate' hasn't been run, just // blank man files.
[ "Reads", "all", ".", "ronn", "files", "&", "and", "converts", "them", "to", "string", "literals", "triggered", "by", "go", "generate", "comment", "Literals", "are", "inserted", "into", "a", "map", "using", "an", "init", "function", "this", "means", "that", ...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/docs/man/mangen.go#L54-L169
157,371
git-lfs/git-lfs
config/url_config.go
compareHosts
func compareHosts(searchHostname, configHostname string) int { searchHost := strings.Split(searchHostname, ".") configHost := strings.Split(configHostname, ".") if len(searchHost) != len(configHost) { return 0 } score := len(searchHost) + 1 for i, subdomain := range searchHost { if configHost[i] == "*" { score-- continue } if subdomain != configHost[i] { return 0 } } return score }
go
func compareHosts(searchHostname, configHostname string) int { searchHost := strings.Split(searchHostname, ".") configHost := strings.Split(configHostname, ".") if len(searchHost) != len(configHost) { return 0 } score := len(searchHost) + 1 for i, subdomain := range searchHost { if configHost[i] == "*" { score-- continue } if subdomain != configHost[i] { return 0 } } return score }
[ "func", "compareHosts", "(", "searchHostname", ",", "configHostname", "string", ")", "int", "{", "searchHost", ":=", "strings", ".", "Split", "(", "searchHostname", ",", "\"", "\"", ")", "\n", "configHost", ":=", "strings", ".", "Split", "(", "configHostname",...
// compareHosts compares a hostname with a configuration hostname to determine // a match. It returns an integer indicating the strength of the match, or 0 if // the two hostnames did not match.
[ "compareHosts", "compares", "a", "hostname", "with", "a", "configuration", "hostname", "to", "determine", "a", "match", ".", "It", "returns", "an", "integer", "indicating", "the", "strength", "of", "the", "match", "or", "0", "if", "the", "two", "hostnames", ...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/config/url_config.go#L171-L193
157,372
git-lfs/git-lfs
config/url_config.go
comparePaths
func comparePaths(rawSearchPath, rawConfigPath string) int { f := func(c rune) bool { return c == '/' } searchPath := strings.FieldsFunc(rawSearchPath, f) configPath := strings.FieldsFunc(rawConfigPath, f) if len(searchPath) < len(configPath) { return 0 } // Start with a base score of 1, so we return something above 0 for a // zero-length path score := 1 for i, element := range configPath { searchElement := searchPath[i] if element == searchElement { score += 2 continue } if isDefaultLFSUrl(searchElement, searchPath, i+1) { if searchElement[0:len(searchElement)-4] == element { // Since we matched without the `.git` prefix, only add one // point to the score instead of 2 score++ continue } } return 0 } return score }
go
func comparePaths(rawSearchPath, rawConfigPath string) int { f := func(c rune) bool { return c == '/' } searchPath := strings.FieldsFunc(rawSearchPath, f) configPath := strings.FieldsFunc(rawConfigPath, f) if len(searchPath) < len(configPath) { return 0 } // Start with a base score of 1, so we return something above 0 for a // zero-length path score := 1 for i, element := range configPath { searchElement := searchPath[i] if element == searchElement { score += 2 continue } if isDefaultLFSUrl(searchElement, searchPath, i+1) { if searchElement[0:len(searchElement)-4] == element { // Since we matched without the `.git` prefix, only add one // point to the score instead of 2 score++ continue } } return 0 } return score }
[ "func", "comparePaths", "(", "rawSearchPath", ",", "rawConfigPath", "string", ")", "int", "{", "f", ":=", "func", "(", "c", "rune", ")", "bool", "{", "return", "c", "==", "'/'", "\n", "}", "\n", "searchPath", ":=", "strings", ".", "FieldsFunc", "(", "r...
// comparePaths compares a path with a configuration path to determine a match. // It returns an integer indicating the strength of the match, or 0 if the two // paths did not match.
[ "comparePaths", "compares", "a", "path", "with", "a", "configuration", "path", "to", "determine", "a", "match", ".", "It", "returns", "an", "integer", "indicating", "the", "strength", "of", "the", "match", "or", "0", "if", "the", "two", "paths", "did", "no...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/config/url_config.go#L198-L234
157,373
git-lfs/git-lfs
tq/custom.go
sendMessage
func (a *customAdapter) sendMessage(ctx *customAdapterWorkerContext, req interface{}) error { b, err := json.Marshal(req) if err != nil { return err } a.Trace("xfer: Custom adapter worker %d sending message: %v", ctx.workerNum, string(b)) // Line oriented JSON b = append(b, '\n') _, err = ctx.stdin.Write(b) return err }
go
func (a *customAdapter) sendMessage(ctx *customAdapterWorkerContext, req interface{}) error { b, err := json.Marshal(req) if err != nil { return err } a.Trace("xfer: Custom adapter worker %d sending message: %v", ctx.workerNum, string(b)) // Line oriented JSON b = append(b, '\n') _, err = ctx.stdin.Write(b) return err }
[ "func", "(", "a", "*", "customAdapter", ")", "sendMessage", "(", "ctx", "*", "customAdapterWorkerContext", ",", "req", "interface", "{", "}", ")", "error", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "req", ")", "\n", "if", "err", "!=", ...
// sendMessage sends a JSON message to the custom adapter process
[ "sendMessage", "sends", "a", "JSON", "message", "to", "the", "custom", "adapter", "process" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/custom.go#L180-L190
157,374
git-lfs/git-lfs
tq/custom.go
exchangeMessage
func (a *customAdapter) exchangeMessage(ctx *customAdapterWorkerContext, req interface{}) (*customAdapterResponseMessage, error) { err := a.sendMessage(ctx, req) if err != nil { return nil, err } return a.readResponse(ctx) }
go
func (a *customAdapter) exchangeMessage(ctx *customAdapterWorkerContext, req interface{}) (*customAdapterResponseMessage, error) { err := a.sendMessage(ctx, req) if err != nil { return nil, err } return a.readResponse(ctx) }
[ "func", "(", "a", "*", "customAdapter", ")", "exchangeMessage", "(", "ctx", "*", "customAdapterWorkerContext", ",", "req", "interface", "{", "}", ")", "(", "*", "customAdapterResponseMessage", ",", "error", ")", "{", "err", ":=", "a", ".", "sendMessage", "("...
// exchangeMessage sends a message to a process and reads a response if resp != nil // Only fatal errors to communicate return an error, errors may be embedded in reply
[ "exchangeMessage", "sends", "a", "message", "to", "a", "process", "and", "reads", "a", "response", "if", "resp", "!", "=", "nil", "Only", "fatal", "errors", "to", "communicate", "return", "an", "error", "errors", "may", "be", "embedded", "in", "reply" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/custom.go#L205-L211
157,375
git-lfs/git-lfs
tq/custom.go
abortWorkerProcess
func (a *customAdapter) abortWorkerProcess(ctx *customAdapterWorkerContext) { a.Trace("xfer: Aborting worker process: %d", ctx.workerNum) ctx.stdin.Close() ctx.stdout.Close() ctx.cmd.Process.Kill() }
go
func (a *customAdapter) abortWorkerProcess(ctx *customAdapterWorkerContext) { a.Trace("xfer: Aborting worker process: %d", ctx.workerNum) ctx.stdin.Close() ctx.stdout.Close() ctx.cmd.Process.Kill() }
[ "func", "(", "a", "*", "customAdapter", ")", "abortWorkerProcess", "(", "ctx", "*", "customAdapterWorkerContext", ")", "{", "a", ".", "Trace", "(", "\"", "\"", ",", "ctx", ".", "workerNum", ")", "\n", "ctx", ".", "stdin", ".", "Close", "(", ")", "\n", ...
// abortWorkerProcess terminates & aborts untidily, most probably breakdown of comms or internal error
[ "abortWorkerProcess", "terminates", "&", "aborts", "untidily", "most", "probably", "breakdown", "of", "comms", "or", "internal", "error" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/custom.go#L240-L245
157,376
git-lfs/git-lfs
tq/custom.go
configureCustomAdapters
func configureCustomAdapters(git Env, m *Manifest) { pathRegex := regexp.MustCompile(`lfs.customtransfer.([^.]+).path`) for k, _ := range git.All() { match := pathRegex.FindStringSubmatch(k) if match == nil { continue } name := match[1] path, _ := git.Get(k) // retrieve other values args, _ := git.Get(fmt.Sprintf("lfs.customtransfer.%s.args", name)) concurrent := git.Bool(fmt.Sprintf("lfs.customtransfer.%s.concurrent", name), true) direction, _ := git.Get(fmt.Sprintf("lfs.customtransfer.%s.direction", name)) if len(direction) == 0 { direction = "both" } else { direction = strings.ToLower(direction) } // Separate closure for each since we need to capture vars above newfunc := func(name string, dir Direction) Adapter { standalone := m.standaloneTransferAgent != "" return newCustomAdapter(m.fs, name, dir, path, args, concurrent, standalone) } if direction == "download" || direction == "both" { m.RegisterNewAdapterFunc(name, Download, newfunc) } if direction == "upload" || direction == "both" { m.RegisterNewAdapterFunc(name, Upload, newfunc) } } }
go
func configureCustomAdapters(git Env, m *Manifest) { pathRegex := regexp.MustCompile(`lfs.customtransfer.([^.]+).path`) for k, _ := range git.All() { match := pathRegex.FindStringSubmatch(k) if match == nil { continue } name := match[1] path, _ := git.Get(k) // retrieve other values args, _ := git.Get(fmt.Sprintf("lfs.customtransfer.%s.args", name)) concurrent := git.Bool(fmt.Sprintf("lfs.customtransfer.%s.concurrent", name), true) direction, _ := git.Get(fmt.Sprintf("lfs.customtransfer.%s.direction", name)) if len(direction) == 0 { direction = "both" } else { direction = strings.ToLower(direction) } // Separate closure for each since we need to capture vars above newfunc := func(name string, dir Direction) Adapter { standalone := m.standaloneTransferAgent != "" return newCustomAdapter(m.fs, name, dir, path, args, concurrent, standalone) } if direction == "download" || direction == "both" { m.RegisterNewAdapterFunc(name, Download, newfunc) } if direction == "upload" || direction == "both" { m.RegisterNewAdapterFunc(name, Upload, newfunc) } } }
[ "func", "configureCustomAdapters", "(", "git", "Env", ",", "m", "*", "Manifest", ")", "{", "pathRegex", ":=", "regexp", ".", "MustCompile", "(", "`lfs.customtransfer.([^.]+).path`", ")", "\n", "for", "k", ",", "_", ":=", "range", "git", ".", "All", "(", ")...
// Initialise custom adapters based on current config
[ "Initialise", "custom", "adapters", "based", "on", "current", "config" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/custom.go#L352-L385
157,377
git-lfs/git-lfs
tools/filetools.go
FileExistsOfSize
func FileExistsOfSize(path string, sz int64) bool { fi, err := os.Stat(path) if err != nil { return false } return !fi.IsDir() && fi.Size() == sz }
go
func FileExistsOfSize(path string, sz int64) bool { fi, err := os.Stat(path) if err != nil { return false } return !fi.IsDir() && fi.Size() == sz }
[ "func", "FileExistsOfSize", "(", "path", "string", ",", "sz", "int64", ")", "bool", "{", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "return", "!", "fi", ...
// FileExistsOfSize determines if a file exists and is of a specific size.
[ "FileExistsOfSize", "determines", "if", "a", "file", "exists", "and", "is", "of", "a", "specific", "size", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/filetools.go#L46-L54
157,378
git-lfs/git-lfs
tools/filetools.go
ResolveSymlinks
func ResolveSymlinks(path string) string { if len(path) == 0 { return path } if resolved, err := filepath.EvalSymlinks(path); err == nil { return resolved } return path }
go
func ResolveSymlinks(path string) string { if len(path) == 0 { return path } if resolved, err := filepath.EvalSymlinks(path); err == nil { return resolved } return path }
[ "func", "ResolveSymlinks", "(", "path", "string", ")", "string", "{", "if", "len", "(", "path", ")", "==", "0", "{", "return", "path", "\n", "}", "\n\n", "if", "resolved", ",", "err", ":=", "filepath", ".", "EvalSymlinks", "(", "path", ")", ";", "err...
// ResolveSymlinks ensures that if the path supplied is a symlink, it is // resolved to the actual concrete path
[ "ResolveSymlinks", "ensures", "that", "if", "the", "path", "supplied", "is", "a", "symlink", "it", "is", "resolved", "to", "the", "actual", "concrete", "path" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/filetools.go#L58-L67
157,379
git-lfs/git-lfs
tools/filetools.go
RenameFileCopyPermissions
func RenameFileCopyPermissions(srcfile, destfile string) error { info, err := os.Stat(destfile) if os.IsNotExist(err) { // no original file } else if err != nil { return err } else { if err := os.Chmod(srcfile, info.Mode()); err != nil { return fmt.Errorf("can't set filemode on file %q: %v", srcfile, err) } } if err := os.Rename(srcfile, destfile); err != nil { return fmt.Errorf("cannot replace %q with %q: %v", destfile, srcfile, err) } return nil }
go
func RenameFileCopyPermissions(srcfile, destfile string) error { info, err := os.Stat(destfile) if os.IsNotExist(err) { // no original file } else if err != nil { return err } else { if err := os.Chmod(srcfile, info.Mode()); err != nil { return fmt.Errorf("can't set filemode on file %q: %v", srcfile, err) } } if err := os.Rename(srcfile, destfile); err != nil { return fmt.Errorf("cannot replace %q with %q: %v", destfile, srcfile, err) } return nil }
[ "func", "RenameFileCopyPermissions", "(", "srcfile", ",", "destfile", "string", ")", "error", "{", "info", ",", "err", ":=", "os", ".", "Stat", "(", "destfile", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "// no original file", "}", "...
// RenameFileCopyPermissions moves srcfile to destfile, replacing destfile if // necessary and also copying the permissions of destfile if it already exists
[ "RenameFileCopyPermissions", "moves", "srcfile", "to", "destfile", "replacing", "destfile", "if", "necessary", "and", "also", "copying", "the", "permissions", "of", "destfile", "if", "it", "already", "exists" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/filetools.go#L71-L87
157,380
git-lfs/git-lfs
tools/filetools.go
MkdirAll
func MkdirAll(path string, config repositoryPermissionFetcher) error { umask := 0777 & ^config.RepositoryPermissions(true) return doWithUmask(int(umask), func() error { return os.MkdirAll(path, config.RepositoryPermissions(true)) }) }
go
func MkdirAll(path string, config repositoryPermissionFetcher) error { umask := 0777 & ^config.RepositoryPermissions(true) return doWithUmask(int(umask), func() error { return os.MkdirAll(path, config.RepositoryPermissions(true)) }) }
[ "func", "MkdirAll", "(", "path", "string", ",", "config", "repositoryPermissionFetcher", ")", "error", "{", "umask", ":=", "0777", "&", "^", "config", ".", "RepositoryPermissions", "(", "true", ")", "\n", "return", "doWithUmask", "(", "int", "(", "umask", ")...
// MkdirAll makes a directory and any intervening directories with the // permissions specified by the core.sharedRepository setting.
[ "MkdirAll", "makes", "a", "directory", "and", "any", "intervening", "directories", "with", "the", "permissions", "specified", "by", "the", "core", ".", "sharedRepository", "setting", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/filetools.go#L126-L131
157,381
git-lfs/git-lfs
tools/filetools.go
VerifyFileHash
func VerifyFileHash(oid, path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() h := NewLfsContentHash() _, err = io.Copy(h, f) if err != nil { return err } calcOid := hex.EncodeToString(h.Sum(nil)) if calcOid != oid { return fmt.Errorf("File %q has an invalid hash %s, expected %s", path, calcOid, oid) } return nil }
go
func VerifyFileHash(oid, path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() h := NewLfsContentHash() _, err = io.Copy(h, f) if err != nil { return err } calcOid := hex.EncodeToString(h.Sum(nil)) if calcOid != oid { return fmt.Errorf("File %q has an invalid hash %s, expected %s", path, calcOid, oid) } return nil }
[ "func", "VerifyFileHash", "(", "oid", ",", "path", "string", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ...
// VerifyFileHash reads a file and verifies whether the SHA is correct // Returns an error if there is a problem
[ "VerifyFileHash", "reads", "a", "file", "and", "verifies", "whether", "the", "SHA", "is", "correct", "Returns", "an", "error", "if", "there", "is", "a", "problem" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/filetools.go#L218-L237
157,382
git-lfs/git-lfs
tools/filetools.go
loadExcludeFilename
func loadExcludeFilename(filename, workDir string, excludePaths []filepathfilter.Pattern) ([]filepathfilter.Pattern, error) { f, err := os.OpenFile(filename, os.O_RDONLY, 0644) if err != nil { if os.IsNotExist(err) { return excludePaths, nil } return excludePaths, err } defer f.Close() retPaths := excludePaths modified := false scanner := bufio.NewScanner(f) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) // Skip blanks, comments and negations (not supported right now) if len(line) == 0 || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "!") { continue } if !modified { // copy on write retPaths = make([]filepathfilter.Pattern, len(excludePaths)) copy(retPaths, excludePaths) modified = true } path := line // Add pattern in context if exclude has separator, or no wildcard // Allow for both styles of separator at this point if strings.ContainsAny(path, "/\\") || !strings.Contains(path, "*") { path = join(workDir, line) } retPaths = append(retPaths, filepathfilter.NewPattern(path)) } return retPaths, nil }
go
func loadExcludeFilename(filename, workDir string, excludePaths []filepathfilter.Pattern) ([]filepathfilter.Pattern, error) { f, err := os.OpenFile(filename, os.O_RDONLY, 0644) if err != nil { if os.IsNotExist(err) { return excludePaths, nil } return excludePaths, err } defer f.Close() retPaths := excludePaths modified := false scanner := bufio.NewScanner(f) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) // Skip blanks, comments and negations (not supported right now) if len(line) == 0 || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "!") { continue } if !modified { // copy on write retPaths = make([]filepathfilter.Pattern, len(excludePaths)) copy(retPaths, excludePaths) modified = true } path := line // Add pattern in context if exclude has separator, or no wildcard // Allow for both styles of separator at this point if strings.ContainsAny(path, "/\\") || !strings.Contains(path, "*") { path = join(workDir, line) } retPaths = append(retPaths, filepathfilter.NewPattern(path)) } return retPaths, nil }
[ "func", "loadExcludeFilename", "(", "filename", ",", "workDir", "string", ",", "excludePaths", "[", "]", "filepathfilter", ".", "Pattern", ")", "(", "[", "]", "filepathfilter", ".", "Pattern", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Op...
// loadExcludeFilename reads the given file in gitignore format and returns a // revised array of exclude paths if there are any changes. // If any changes are made a copy of the array is taken so the original is not // modified
[ "loadExcludeFilename", "reads", "the", "given", "file", "in", "gitignore", "format", "and", "returns", "a", "revised", "array", "of", "exclude", "paths", "if", "there", "are", "any", "changes", ".", "If", "any", "changes", "are", "made", "a", "copy", "of", ...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/filetools.go#L428-L467
157,383
git-lfs/git-lfs
git/pkt_line_writer.go
Flush
func (w *PktlineWriter) Flush() error { if w == nil { return nil } if _, err := w.flush(); err != nil { return err } if err := w.pl.writeFlush(); err != nil { return err } return nil }
go
func (w *PktlineWriter) Flush() error { if w == nil { return nil } if _, err := w.flush(); err != nil { return err } if err := w.pl.writeFlush(); err != nil { return err } return nil }
[ "func", "(", "w", "*", "PktlineWriter", ")", "Flush", "(", ")", "error", "{", "if", "w", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "w", ".", "flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "...
// Flush empties the internal buffer used to store data temporarily and then // writes the pkt-line's FLUSH packet, to signal that it is done writing this // chunk of data.
[ "Flush", "empties", "the", "internal", "buffer", "used", "to", "store", "data", "temporarily", "and", "then", "writes", "the", "pkt", "-", "line", "s", "FLUSH", "packet", "to", "signal", "that", "it", "is", "done", "writing", "this", "chunk", "of", "data",...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/pkt_line_writer.go#L89-L103
157,384
git-lfs/git-lfs
git/pkt_line_writer.go
flush
func (w *PktlineWriter) flush() (int, error) { var n int for len(w.buf) > 0 { if err := w.pl.writePacket(w.buf); err != nil { return 0, err } m := tools.MinInt(len(w.buf), MaxPacketLength) w.buf = w.buf[m:] n = n + m } return n, nil }
go
func (w *PktlineWriter) flush() (int, error) { var n int for len(w.buf) > 0 { if err := w.pl.writePacket(w.buf); err != nil { return 0, err } m := tools.MinInt(len(w.buf), MaxPacketLength) w.buf = w.buf[m:] n = n + m } return n, nil }
[ "func", "(", "w", "*", "PktlineWriter", ")", "flush", "(", ")", "(", "int", ",", "error", ")", "{", "var", "n", "int", "\n\n", "for", "len", "(", "w", ".", "buf", ")", ">", "0", "{", "if", "err", ":=", "w", ".", "pl", ".", "writePacket", "(",...
// flush writes any data in the internal buffer out to the underlying protocol // stream. If the amount of data in the internal buffer exceeds the // MaxPacketLength, the data will be written in multiple packets to accommodate. // // flush returns the number of bytes written to the underlying packet stream, // and any error that it encountered along the way.
[ "flush", "writes", "any", "data", "in", "the", "internal", "buffer", "out", "to", "the", "underlying", "protocol", "stream", ".", "If", "the", "amount", "of", "data", "in", "the", "internal", "buffer", "exceeds", "the", "MaxPacketLength", "the", "data", "wil...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/pkt_line_writer.go#L111-L127
157,385
git-lfs/git-lfs
tools/humanize/humanize.go
ParseBytes
func ParseBytes(str string) (uint64, error) { var sep int for _, r := range str { if !(unicode.IsDigit(r) || r == '.' || r == ',') { break } sep = sep + 1 } var f float64 if s := strings.Replace(str[:sep], ",", "", -1); len(s) > 0 { var err error f, err = strconv.ParseFloat(s, 64) if err != nil { return 0, err } } m, err := ParseByteUnit(str[sep:]) if err != nil { return 0, err } f = f * float64(m) if f >= math.MaxUint64 { return 0, errors.New("number of bytes too large") } return uint64(f), nil }
go
func ParseBytes(str string) (uint64, error) { var sep int for _, r := range str { if !(unicode.IsDigit(r) || r == '.' || r == ',') { break } sep = sep + 1 } var f float64 if s := strings.Replace(str[:sep], ",", "", -1); len(s) > 0 { var err error f, err = strconv.ParseFloat(s, 64) if err != nil { return 0, err } } m, err := ParseByteUnit(str[sep:]) if err != nil { return 0, err } f = f * float64(m) if f >= math.MaxUint64 { return 0, errors.New("number of bytes too large") } return uint64(f), nil }
[ "func", "ParseBytes", "(", "str", "string", ")", "(", "uint64", ",", "error", ")", "{", "var", "sep", "int", "\n", "for", "_", ",", "r", ":=", "range", "str", "{", "if", "!", "(", "unicode", ".", "IsDigit", "(", "r", ")", "||", "r", "==", "'.'"...
// ParseBytes parses a given human-readable bytes or ibytes string into a number // of bytes, or an error if the string was unable to be parsed.
[ "ParseBytes", "parses", "a", "given", "human", "-", "readable", "bytes", "or", "ibytes", "string", "into", "a", "number", "of", "bytes", "or", "an", "error", "if", "the", "string", "was", "unable", "to", "be", "parsed", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/humanize/humanize.go#L52-L83
157,386
git-lfs/git-lfs
tools/humanize/humanize.go
ParseByteUnit
func ParseByteUnit(str string) (uint64, error) { str = strings.TrimSpace(str) str = strings.ToLower(str) if u, ok := bytesTable[str]; ok { return u, nil } return 0, errors.Errorf("unknown unit: %q", str) }
go
func ParseByteUnit(str string) (uint64, error) { str = strings.TrimSpace(str) str = strings.ToLower(str) if u, ok := bytesTable[str]; ok { return u, nil } return 0, errors.Errorf("unknown unit: %q", str) }
[ "func", "ParseByteUnit", "(", "str", "string", ")", "(", "uint64", ",", "error", ")", "{", "str", "=", "strings", ".", "TrimSpace", "(", "str", ")", "\n", "str", "=", "strings", ".", "ToLower", "(", "str", ")", "\n\n", "if", "u", ",", "ok", ":=", ...
// ParseByteUnit returns the number of bytes in a given unit of storage, or an // error, if that unit is unrecognized.
[ "ParseByteUnit", "returns", "the", "number", "of", "bytes", "in", "a", "given", "unit", "of", "storage", "or", "an", "error", "if", "that", "unit", "is", "unrecognized", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/humanize/humanize.go#L87-L95
157,387
git-lfs/git-lfs
tools/humanize/humanize.go
FormatBytes
func FormatBytes(s uint64) string { var e float64 if s == 0 { e = 0 } else { e = math.Floor(log(float64(s), 1000)) } unit := uint64(math.Pow(1000, e)) suffix := sizes[int(e)] return fmt.Sprintf("%s %s", FormatBytesUnit(s, unit), suffix) }
go
func FormatBytes(s uint64) string { var e float64 if s == 0 { e = 0 } else { e = math.Floor(log(float64(s), 1000)) } unit := uint64(math.Pow(1000, e)) suffix := sizes[int(e)] return fmt.Sprintf("%s %s", FormatBytesUnit(s, unit), suffix) }
[ "func", "FormatBytes", "(", "s", "uint64", ")", "string", "{", "var", "e", "float64", "\n", "if", "s", "==", "0", "{", "e", "=", "0", "\n", "}", "else", "{", "e", "=", "math", ".", "Floor", "(", "log", "(", "float64", "(", "s", ")", ",", "100...
// FormatBytes outputs the given number of bytes "s" as a human-readable string, // rounding to the nearest half within .01.
[ "FormatBytes", "outputs", "the", "given", "number", "of", "bytes", "s", "as", "a", "human", "-", "readable", "string", "rounding", "to", "the", "nearest", "half", "within", ".", "01", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/humanize/humanize.go#L101-L114
157,388
git-lfs/git-lfs
tools/humanize/humanize.go
FormatBytesUnit
func FormatBytesUnit(s, u uint64) string { var rounded float64 if s < 10 { rounded = float64(s) } else { rounded = math.Floor(float64(s)/float64(u)*10+.5) / 10 } format := "%.0f" if rounded < 10 && u > 1 { format = "%.1f" } return fmt.Sprintf(format, rounded) }
go
func FormatBytesUnit(s, u uint64) string { var rounded float64 if s < 10 { rounded = float64(s) } else { rounded = math.Floor(float64(s)/float64(u)*10+.5) / 10 } format := "%.0f" if rounded < 10 && u > 1 { format = "%.1f" } return fmt.Sprintf(format, rounded) }
[ "func", "FormatBytesUnit", "(", "s", ",", "u", "uint64", ")", "string", "{", "var", "rounded", "float64", "\n", "if", "s", "<", "10", "{", "rounded", "=", "float64", "(", "s", ")", "\n", "}", "else", "{", "rounded", "=", "math", ".", "Floor", "(", ...
// FormatBytesUnit outputs the given number of bytes "s" as a quantity of the // given units "u" to the nearest half within .01.
[ "FormatBytesUnit", "outputs", "the", "given", "number", "of", "bytes", "s", "as", "a", "quantity", "of", "the", "given", "units", "u", "to", "the", "nearest", "half", "within", ".", "01", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/humanize/humanize.go#L118-L132
157,389
git-lfs/git-lfs
commands/command_fetch.go
fetchRecent
func fetchRecent(fetchconf lfs.FetchPruneConfig, alreadyFetchedRefs []*git.Ref, filter *filepathfilter.Filter) bool { if fetchconf.FetchRecentRefsDays == 0 && fetchconf.FetchRecentCommitsDays == 0 { return true } ok := true // Make a list of what unique commits we've already fetched for to avoid duplicating work uniqueRefShas := make(map[string]string, len(alreadyFetchedRefs)) for _, ref := range alreadyFetchedRefs { uniqueRefShas[ref.Sha] = ref.Name } // First find any other recent refs if fetchconf.FetchRecentRefsDays > 0 { Print("fetch: Fetching recent branches within %v days", fetchconf.FetchRecentRefsDays) refsSince := time.Now().AddDate(0, 0, -fetchconf.FetchRecentRefsDays) refs, err := git.RecentBranches(refsSince, fetchconf.FetchRecentRefsIncludeRemotes, cfg.Remote()) if err != nil { Panic(err, "Could not scan for recent refs") } for _, ref := range refs { // Don't fetch for the same SHA twice if prevRefName, ok := uniqueRefShas[ref.Sha]; ok { if ref.Name != prevRefName { tracerx.Printf("Skipping fetch for %v, already fetched via %v", ref.Name, prevRefName) } } else { uniqueRefShas[ref.Sha] = ref.Name Print("fetch: Fetching reference %s", ref.Name) k := fetchRef(ref.Sha, filter) ok = ok && k } } } // For every unique commit we've fetched, check recent commits too if fetchconf.FetchRecentCommitsDays > 0 { for commit, refName := range uniqueRefShas { // We measure from the last commit at the ref summ, err := git.GetCommitSummary(commit) if err != nil { Error("Couldn't scan commits at %v: %v", refName, err) continue } Print("fetch: Fetching changes within %v days of %v", fetchconf.FetchRecentCommitsDays, refName) commitsSince := summ.CommitDate.AddDate(0, 0, -fetchconf.FetchRecentCommitsDays) k := fetchPreviousVersions(commit, commitsSince, filter) ok = ok && k } } return ok }
go
func fetchRecent(fetchconf lfs.FetchPruneConfig, alreadyFetchedRefs []*git.Ref, filter *filepathfilter.Filter) bool { if fetchconf.FetchRecentRefsDays == 0 && fetchconf.FetchRecentCommitsDays == 0 { return true } ok := true // Make a list of what unique commits we've already fetched for to avoid duplicating work uniqueRefShas := make(map[string]string, len(alreadyFetchedRefs)) for _, ref := range alreadyFetchedRefs { uniqueRefShas[ref.Sha] = ref.Name } // First find any other recent refs if fetchconf.FetchRecentRefsDays > 0 { Print("fetch: Fetching recent branches within %v days", fetchconf.FetchRecentRefsDays) refsSince := time.Now().AddDate(0, 0, -fetchconf.FetchRecentRefsDays) refs, err := git.RecentBranches(refsSince, fetchconf.FetchRecentRefsIncludeRemotes, cfg.Remote()) if err != nil { Panic(err, "Could not scan for recent refs") } for _, ref := range refs { // Don't fetch for the same SHA twice if prevRefName, ok := uniqueRefShas[ref.Sha]; ok { if ref.Name != prevRefName { tracerx.Printf("Skipping fetch for %v, already fetched via %v", ref.Name, prevRefName) } } else { uniqueRefShas[ref.Sha] = ref.Name Print("fetch: Fetching reference %s", ref.Name) k := fetchRef(ref.Sha, filter) ok = ok && k } } } // For every unique commit we've fetched, check recent commits too if fetchconf.FetchRecentCommitsDays > 0 { for commit, refName := range uniqueRefShas { // We measure from the last commit at the ref summ, err := git.GetCommitSummary(commit) if err != nil { Error("Couldn't scan commits at %v: %v", refName, err) continue } Print("fetch: Fetching changes within %v days of %v", fetchconf.FetchRecentCommitsDays, refName) commitsSince := summ.CommitDate.AddDate(0, 0, -fetchconf.FetchRecentCommitsDays) k := fetchPreviousVersions(commit, commitsSince, filter) ok = ok && k } } return ok }
[ "func", "fetchRecent", "(", "fetchconf", "lfs", ".", "FetchPruneConfig", ",", "alreadyFetchedRefs", "[", "]", "*", "git", ".", "Ref", ",", "filter", "*", "filepathfilter", ".", "Filter", ")", "bool", "{", "if", "fetchconf", ".", "FetchRecentRefsDays", "==", ...
// Fetch recent objects based on config
[ "Fetch", "recent", "objects", "based", "on", "config" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_fetch.go#L170-L220
157,390
git-lfs/git-lfs
git/pkt_line.go
readPacketList
func (p *pktline) readPacketList() ([]string, error) { var list []string for { data, err := p.readPacketText() if err != nil { return nil, err } if len(data) == 0 { break } list = append(list, data) } return list, nil }
go
func (p *pktline) readPacketList() ([]string, error) { var list []string for { data, err := p.readPacketText() if err != nil { return nil, err } if len(data) == 0 { break } list = append(list, data) } return list, nil }
[ "func", "(", "p", "*", "pktline", ")", "readPacketList", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "list", "[", "]", "string", "\n", "for", "{", "data", ",", "err", ":=", "p", ".", "readPacketText", "(", ")", "\n", "if", ...
// readPacketList reads as many packets as possible using the `readPacketText` // function before encountering a flush packet. It returns a slice of all the // packets it read, or an error if one was encountered.
[ "readPacketList", "reads", "as", "many", "packets", "as", "possible", "using", "the", "readPacketText", "function", "before", "encountering", "a", "flush", "packet", ".", "It", "returns", "a", "slice", "of", "all", "the", "packets", "it", "read", "or", "an", ...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/pkt_line.go#L82-L98
157,391
git-lfs/git-lfs
git/pkt_line.go
writeFlush
func (p *pktline) writeFlush() error { if _, err := p.w.WriteString(fmt.Sprintf("%04x", 0)); err != nil { return err } if err := p.w.Flush(); err != nil { return err } return nil }
go
func (p *pktline) writeFlush() error { if _, err := p.w.WriteString(fmt.Sprintf("%04x", 0)); err != nil { return err } if err := p.w.Flush(); err != nil { return err } return nil }
[ "func", "(", "p", "*", "pktline", ")", "writeFlush", "(", ")", "error", "{", "if", "_", ",", "err", ":=", "p", ".", "w", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "0", ")", ")", ";", "err", "!=", "nil", "{", "retur...
// writeFlush writes the terminating "flush" packet and then flushes the // underlying buffered writer. // // If any error was encountered along the way, it will be returned immediately
[ "writeFlush", "writes", "the", "terminating", "flush", "packet", "and", "then", "flushes", "the", "underlying", "buffered", "writer", ".", "If", "any", "error", "was", "encountered", "along", "the", "way", "it", "will", "be", "returned", "immediately" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/pkt_line.go#L129-L139
157,392
git-lfs/git-lfs
git/pkt_line.go
writePacketText
func (p *pktline) writePacketText(data string) error { return p.writePacket([]byte(data + "\n")) }
go
func (p *pktline) writePacketText(data string) error { return p.writePacket([]byte(data + "\n")) }
[ "func", "(", "p", "*", "pktline", ")", "writePacketText", "(", "data", "string", ")", "error", "{", "return", "p", ".", "writePacket", "(", "[", "]", "byte", "(", "data", "+", "\"", "\\n", "\"", ")", ")", "\n", "}" ]
// writePacketText follows the same semantics as `writePacket`, but appends a // trailing "\n" LF character to the end of the data.
[ "writePacketText", "follows", "the", "same", "semantics", "as", "writePacket", "but", "appends", "a", "trailing", "\\", "n", "LF", "character", "to", "the", "end", "of", "the", "data", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/pkt_line.go#L143-L145
157,393
git-lfs/git-lfs
git/pkt_line.go
writePacketList
func (p *pktline) writePacketList(list []string) error { for _, i := range list { if err := p.writePacketText(i); err != nil { return err } } return p.writeFlush() }
go
func (p *pktline) writePacketList(list []string) error { for _, i := range list { if err := p.writePacketText(i); err != nil { return err } } return p.writeFlush() }
[ "func", "(", "p", "*", "pktline", ")", "writePacketList", "(", "list", "[", "]", "string", ")", "error", "{", "for", "_", ",", "i", ":=", "range", "list", "{", "if", "err", ":=", "p", ".", "writePacketText", "(", "i", ")", ";", "err", "!=", "nil"...
// writePacketList writes a slice of strings using the semantics of // and then writes a terminating flush sequence afterwords. // // If any error was encountered, it will be returned immediately.
[ "writePacketList", "writes", "a", "slice", "of", "strings", "using", "the", "semantics", "of", "and", "then", "writes", "a", "terminating", "flush", "sequence", "afterwords", ".", "If", "any", "error", "was", "encountered", "it", "will", "be", "returned", "imm...
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/pkt_line.go#L151-L159
157,394
git-lfs/git-lfs
commands/command_ls_files.go
fileExistsOfSize
func fileExistsOfSize(p *lfs.WrappedPointer) bool { path := cfg.Filesystem().DecodePathname(p.Name) info, err := os.Stat(path) return err == nil && info.Size() == p.Size }
go
func fileExistsOfSize(p *lfs.WrappedPointer) bool { path := cfg.Filesystem().DecodePathname(p.Name) info, err := os.Stat(path) return err == nil && info.Size() == p.Size }
[ "func", "fileExistsOfSize", "(", "p", "*", "lfs", ".", "WrappedPointer", ")", "bool", "{", "path", ":=", "cfg", ".", "Filesystem", "(", ")", ".", "DecodePathname", "(", "p", ".", "Name", ")", "\n", "info", ",", "err", ":=", "os", ".", "Stat", "(", ...
// Returns true if a pointer appears to be properly smudge on checkout
[ "Returns", "true", "if", "a", "pointer", "appears", "to", "be", "properly", "smudge", "on", "checkout" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_ls_files.go#L132-L136
157,395
git-lfs/git-lfs
tools/copycallback.go
Read
func (r *BodyWithCallback) Read(p []byte) (int, error) { n, err := r.ReadSeekCloser.Read(p) if n > 0 { r.readSize += int64(n) if (err == nil || err == io.EOF) && r.c != nil { err = r.c(r.totalSize, r.readSize, n) } } return n, err }
go
func (r *BodyWithCallback) Read(p []byte) (int, error) { n, err := r.ReadSeekCloser.Read(p) if n > 0 { r.readSize += int64(n) if (err == nil || err == io.EOF) && r.c != nil { err = r.c(r.totalSize, r.readSize, n) } } return n, err }
[ "func", "(", "r", "*", "BodyWithCallback", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ",", "err", ":=", "r", ".", "ReadSeekCloser", ".", "Read", "(", "p", ")", "\n\n", "if", "n", ">", "0", "{", "r",...
// Read wraps the underlying Reader's "Read" method. It also captures the number // of bytes read, and calls the callback.
[ "Read", "wraps", "the", "underlying", "Reader", "s", "Read", "method", ".", "It", "also", "captures", "the", "number", "of", "bytes", "read", "and", "calls", "the", "callback", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/copycallback.go#L31-L42
157,396
git-lfs/git-lfs
tools/copycallback.go
Seek
func (r *BodyWithCallback) Seek(offset int64, whence int) (int64, error) { switch whence { case io.SeekStart: r.readSize = offset case io.SeekCurrent: r.readSize += offset case io.SeekEnd: r.readSize = r.totalSize + offset } return r.ReadSeekCloser.Seek(offset, whence) }
go
func (r *BodyWithCallback) Seek(offset int64, whence int) (int64, error) { switch whence { case io.SeekStart: r.readSize = offset case io.SeekCurrent: r.readSize += offset case io.SeekEnd: r.readSize = r.totalSize + offset } return r.ReadSeekCloser.Seek(offset, whence) }
[ "func", "(", "r", "*", "BodyWithCallback", ")", "Seek", "(", "offset", "int64", ",", "whence", "int", ")", "(", "int64", ",", "error", ")", "{", "switch", "whence", "{", "case", "io", ".", "SeekStart", ":", "r", ".", "readSize", "=", "offset", "\n", ...
// Seek wraps the underlying Seeker's "Seek" method, updating the number of // bytes that have been consumed by this reader.
[ "Seek", "wraps", "the", "underlying", "Seeker", "s", "Seek", "method", "updating", "the", "number", "of", "bytes", "that", "have", "been", "consumed", "by", "this", "reader", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/copycallback.go#L46-L57
157,397
git-lfs/git-lfs
tools/copycallback.go
ResetProgress
func (r *BodyWithCallback) ResetProgress() error { return r.c(r.totalSize, r.readSize, -int(r.readSize)) }
go
func (r *BodyWithCallback) ResetProgress() error { return r.c(r.totalSize, r.readSize, -int(r.readSize)) }
[ "func", "(", "r", "*", "BodyWithCallback", ")", "ResetProgress", "(", ")", "error", "{", "return", "r", ".", "c", "(", "r", ".", "totalSize", ",", "r", ".", "readSize", ",", "-", "int", "(", "r", ".", "readSize", ")", ")", "\n", "}" ]
// ResetProgress calls the callback with a negative read size equal to the // total number of bytes read so far, effectively "resetting" the progress.
[ "ResetProgress", "calls", "the", "callback", "with", "a", "negative", "read", "size", "equal", "to", "the", "total", "number", "of", "bytes", "read", "so", "far", "effectively", "resetting", "the", "progress", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/copycallback.go#L61-L63
157,398
git-lfs/git-lfs
lfs/diff_index_scanner.go
String
func (s DiffIndexStatus) String() string { switch s { case StatusAddition: return "addition" case StatusCopy: return "copy" case StatusDeletion: return "deletion" case StatusModification: return "modification" case StatusRename: return "rename" case StatusTypeChange: return "change" case StatusUnmerged: return "unmerged" case StatusUnknown: return "unknown" } return "<unknown>" }
go
func (s DiffIndexStatus) String() string { switch s { case StatusAddition: return "addition" case StatusCopy: return "copy" case StatusDeletion: return "deletion" case StatusModification: return "modification" case StatusRename: return "rename" case StatusTypeChange: return "change" case StatusUnmerged: return "unmerged" case StatusUnknown: return "unknown" } return "<unknown>" }
[ "func", "(", "s", "DiffIndexStatus", ")", "String", "(", ")", "string", "{", "switch", "s", "{", "case", "StatusAddition", ":", "return", "\"", "\"", "\n", "case", "StatusCopy", ":", "return", "\"", "\"", "\n", "case", "StatusDeletion", ":", "return", "\...
// String implements fmt.Stringer by returning a human-readable name for each // status.
[ "String", "implements", "fmt", ".", "Stringer", "by", "returning", "a", "human", "-", "readable", "name", "for", "each", "status", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfs/diff_index_scanner.go#L33-L53
157,399
git-lfs/git-lfs
errors/context.go
SetContext
func SetContext(err error, key string, value interface{}) { if e, ok := err.(withContext); ok { e.Set(key, value) } }
go
func SetContext(err error, key string, value interface{}) { if e, ok := err.(withContext); ok { e.Set(key, value) } }
[ "func", "SetContext", "(", "err", "error", ",", "key", "string", ",", "value", "interface", "{", "}", ")", "{", "if", "e", ",", "ok", ":=", "err", ".", "(", "withContext", ")", ";", "ok", "{", "e", ".", "Set", "(", "key", ",", "value", ")", "\n...
// ErrorSetContext sets a value in the error's context. If the error has not // been wrapped, it does nothing.
[ "ErrorSetContext", "sets", "a", "value", "in", "the", "error", "s", "context", ".", "If", "the", "error", "has", "not", "been", "wrapped", "it", "does", "nothing", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/errors/context.go#L12-L16