// Read from standard input
550708
func main() {
	g := generator.New()

	data, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		failWithError(err, "reading input")
	}

	if err := proto.Unmarshal(data, g.Request); err != nil {
		failWithError(err, "parsing input proto")
	}

	if len(g.Request.FileToGenerate) == 0 {
		fail("no files to generate")
	}

	g.CommandLineParameters(g.Request.GetParameter())

	if val, ok := g.Param["logtostderr"]; ok && val == "true" {
		logtostderr = true
	}

	tree := buildTree(g.Request.GetProtoFile())

	packageLocations := make(map[string]string)
	for _, file := range g.Request.GetProtoFile() {
		loc := file.GetName()[:strings.LastIndex(file.GetName(), "/")]
		packageLocations[file.GetPackage()] = loc
	}

	selectedServices := make(map[string]string)
	for k, v := range g.Param {
		switch {
		case k == "logtostderr":
			if v == "true" {
				logtostderr = true
			}
		case strings.HasPrefix(k, "."):
			selectedServices[k] = v
		}
	}

	for serviceKey := range selectedServices {
		service, ok := tree.services[serviceKey]
		if !ok {
			fail("Service", serviceKey, "unknown")
		}

		usedMessages := make(map[string]*message)
		usedEnums := make(map[string]*enum)

		content := new(bytes.Buffer)

		fmt.Fprintf(content, "# %s API Reference\n\n", service.GetName())
		if service.comment != "" {
			fmt.Fprintf(content, "%s\n\n", service.comment)
		}

		if len(service.methods) > 0 {
			fmt.Fprint(content, "## Methods\n\n")

			for _, method := range service.methods {
				fmt.Fprintf(content, "### `%s`\n\n", method.GetName())
				if method.comment != "" {
					fmt.Fprintf(content, "%s\n\n", method.comment)
				}
				if method.inputStream {
					fmt.Fprintf(content, "- Client stream of [`%s`](#%s)\n", method.input.GetName(), heading(method.input.key))
				} else {
					fmt.Fprintf(content, "- Request: [`%s`](#%s)\n", method.input.GetName(), heading(method.input.key))
				}
				useMessage(tree, method.input, usedMessages, usedEnums)
				if method.outputStream {
					fmt.Fprintf(content, "- Server stream of [`%s`](#%s)\n", method.output.GetName(), heading(method.input.key))
				} else {
					fmt.Fprintf(content, "- Response: [`%s`](#%s)\n", method.output.GetName(), heading(method.input.key))
				}
				useMessage(tree, method.output, usedMessages, usedEnums)

				fmt.Fprintln(content)

				if len(method.endpoints) != 0 {
					if len(method.endpoints) == 1 {
						fmt.Fprint(content, "#### HTTP Endpoint\n\n")
					} else {
						fmt.Fprint(content, "#### HTTP Endpoints\n\n")
					}
					for _, endpoint := range method.endpoints {
						fmt.Fprintf(content, "- `%s` `%s`", endpoint.method, endpoint.url)
						var params []string
						for _, match := range regexp.MustCompile(`\{([a-z_]+)\}`).FindAllStringSubmatch(endpoint.url, -1) {
							if match != nil && len(match) == 2 && match[1] != "" {
								params = append(params, fmt.Sprintf("`%s`", match[1]))
							}
						}
						if len(params) > 0 {
							fmt.Fprintf(content, "(%s can be left out of the request body)", strings.Join(params, ", "))
						}
						fmt.Fprintln(content)
					}
					fmt.Fprintln(content)

					fmt.Fprint(content, "#### JSON Request Format\n\n")
					fmt.Fprintf(content, "```json\n%s\n```\n\n", method.input.JSONExample(tree))

					fmt.Fprint(content, "#### JSON Response Format\n\n")
					fmt.Fprintf(content, "```json\n%s\n```\n\n", method.output.JSONExample(tree))
				}
			}
		}

		if len(usedMessages) > 0 {
			fmt.Fprint(content, "## Messages\n\n")

			var messageKeys []string
			for key := range usedMessages {
				messageKeys = append(messageKeys, key)
			}
			sort.Strings(messageKeys)

			for _, messageKey := range messageKeys {
				message := usedMessages[messageKey]
				fmt.Fprintf(content, "### `%s`\n\n", message.key)
				if strings.HasPrefix(messageKey, ".google") {
					fmt.Fprintf(content, "%s\n\n", strings.SplitAfter(message.comment, ".")[0])
				} else if message.comment != "" {
					fmt.Fprintf(content, "%s\n\n", message.comment)
				}
				if len(message.fields) > 0 {
					fmt.Fprintln(content, "| Field Name | Type | Description |")
					fmt.Fprintln(content, "| ---------- | ---- | ----------- |")
					for idx, field := range message.fields {
						if field.isOneOf {
							if idx == 0 || !message.fields[idx-1].isOneOf || message.fields[idx-1].GetOneofIndex() != field.GetOneofIndex() {
								oneof := message.GetOneof(field.GetOneofIndex())
								if len(oneof.fields) > 1 {
									fmt.Fprintf(content, "| **%s** | **oneof %d** | one of the following %d |\n", oneof.GetName(), len(oneof.fields), len(oneof.fields))
								}
							}
						} else {
							if idx > 0 && message.fields[idx-1].isOneOf {
								oneof := message.GetOneof(message.fields[idx-1].GetOneofIndex())
								if len(oneof.fields) > 1 {
									fmt.Fprintf(content, "| **%s** | **end oneof %d** |  |\n", oneof.GetName(), len(oneof.fields))
								}
							}
						}

						var fieldType string
						if field.repeated {
							fieldType += "_repeated_ "
						}
						typ := strings.ToLower(strings.TrimPrefix(field.GetType().String(), "TYPE_"))
						switch typ {
						case "message":
							friendlyType := field.GetTypeName()[strings.LastIndex(field.GetTypeName(), ".")+1:]
							fieldType += fmt.Sprintf("[`%s`](#%s)", friendlyType, heading(field.GetTypeName()))
						case "enum":
							// TODO(htdvisser): test this
							if enum, ok := tree.enums[field.GetTypeName()]; ok {
								usedEnums[field.GetTypeName()] = enum
							}
							friendlyType := field.GetTypeName()[strings.LastIndex(field.GetTypeName(), ".")+1:]
							fieldType += fmt.Sprintf("[`%s`](#%s)", friendlyType, heading(field.GetTypeName()))
						default:
							fieldType += fmt.Sprintf("`%s`", typ)
						}
						fmt.Fprintf(content, "| `%s` | %s | %s |\n", field.GetName(), fieldType, strings.Replace(field.comment, "\n", " ", -1))
					}
					fmt.Fprintln(content)
				}
			}
		}

		if len(usedEnums) > 0 {
			fmt.Fprint(content, "## Used Enums\n\n")

			var enumKeys []string
			for key := range usedEnums {
				enumKeys = append(enumKeys, key)
			}
			sort.Strings(enumKeys)

			for _, enumKey := range enumKeys {
				enum := usedEnums[enumKey]

				fmt.Fprintf(content, "### `%s`\n\n", enum.key)
				if enum.comment != "" {
					fmt.Fprintf(content, "%s\n\n", enum.comment)
				}

				if len(enum.values) > 0 {
					fmt.Fprintln(content, "| Value | Description |")
					fmt.Fprintln(content, "| ----- | ----------- |")
					for _, value := range enum.values {
						fmt.Fprintf(content, "| `%s` | %s |\n", value.GetName(), strings.Replace(value.comment, "\n", " ", -1))
					}
					fmt.Fprintln(content)
				}
			}
		}

		packageService := strings.TrimPrefix(service.key, ".")
		packageName := packageService[:strings.Index(packageService, ".")]
		location, ok := packageLocations[packageName]
		if !ok {
			fail("Could not find location of package", packageName)
		}
		fileName := path.Join(location, service.GetName()+".md")
		contentString := content.String()
		g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
			Name:    &fileName,
			Content: &contentString,
		})
	}

	// Send back the results.
	data, err = proto.Marshal(g.Response)
	if err != nil {
		failWithError(err, "failed to marshal output proto")
	}
	_, err = os.Stdout.Write(data)
	if err != nil {
		failWithError(err, "failed to write output proto")
	}
}
1229325
func (term *Terminal) read(in *bufio.Reader) (int, rune, error) {
	char, _, err := in.ReadRune()
	if err != nil {
		return 0, 0, err
	}

	switch char {
	default:
		// Standard chars.
		return evChar, char, nil
	case tabKey, ctrlA, ctrlB, ctrlE, ctrlF, ctrlG, ctrlH, ctrlJ, ctrlK, ctrlN,
		ctrlO, ctrlP, ctrlQ, ctrlR, ctrlS, ctrlT, ctrlU, ctrlV, ctrlW, ctrlX,
		ctrlY, ctrlZ:
		// Skip.
		return evSkip, char, nil
	case returnKey:
		// End of line.
		return evReturn, char, nil
	case ctrlD:
		// End of file.
		return evEOF, char, nil
	case ctrlC:
		// End of line, interrupted.
		return evCtrlC, char, nil
	case backKey:
		// Backspace.
		return evBack, char, nil
	case ctrlL:
		// Clear screen.
		return evClear, char, nil
	case escKey:
		// Functions like arrows, home, etc.
		esc := make([]byte, 2)
		_, err = in.Read(esc)
		if err != nil {
			return -1, char, err
		}

		// Home, end.
		if esc[0] == 'O' {
			switch esc[1] {
			case 'H':
				// Home.
				return evHome, char, nil
			case 'F':
				// End.
				return evEnd, char, nil
			}

			return evSkip, char, nil
		}

		// Arrows, delete, pgup, pgdown, insert.
		if esc[0] == '[' {
			switch esc[1] {
			case 'A':
				// Up.
				return evUp, char, nil
			case 'B':
				// Down.
				return evDown, char, nil
			case 'C':
				// Right.
				return evRight, char, nil
			case 'D':
				// Left.
				return evLeft, char, nil
			}

			// Delete, pgup, pgdown, insert.
			if esc[1] > '0' && esc[1] < '7' {
				extEsc := make([]byte, 3)
				_, err = in.Read(extEsc)
				if err != nil {
					return -1, char, err
				}

				if extEsc[0] == '~' {
					switch esc[1] {
					case '2', '5', '6':
						// Insert, pgup, pgdown.
						return evSkip, char, err
					case '3':
						// Delete.
						return evDel, char, err
					}
				}
			}
		}
	}

	return evSkip, char, nil
}
1004068
func (lr LineReader) Read(p []byte) (int, error) {
	return lr.r.Read(p)
}
442354
func (r *Reader) Read(p []byte) (n int, err error) {
	// Deviations from RFC 2045:
	// 1. in addition to "=\r\n", "=\n" is also treated as soft line break.
	// 2. it will pass through a '\r' or '\n' not preceded by '=', consistent
	//    with other broken QP encoders & decoders.
	for len(p) > 0 {
		if len(r.line) == 0 {
			if r.rerr != nil {
				return n, r.rerr
			}
			r.line, r.rerr = r.br.ReadSlice('\n')

			// Does the line end in CRLF instead of just LF?
			hasLF := bytes.HasSuffix(r.line, lf)
			hasCR := bytes.HasSuffix(r.line, crlf)
			wholeLine := r.line
			r.line = bytes.TrimRightFunc(wholeLine, isQPDiscardWhitespace)
			if bytes.HasSuffix(r.line, softSuffix) {
				rightStripped := wholeLine[len(r.line):]
				r.line = r.line[:len(r.line)-1]
				if !bytes.HasPrefix(rightStripped, lf) && !bytes.HasPrefix(rightStripped, crlf) {
					r.rerr = fmt.Errorf("quotedprintable: invalid bytes after =: %q", rightStripped)
				}
			} else if hasLF {
				if hasCR {
					r.line = append(r.line, '\r', '\n')
				} else {
					r.line = append(r.line, '\n')
				}
			}
			continue
		}
		b := r.line[0]

		switch {
		case b == '=':
			if len(r.line[1:]) < 2 {
				return n, io.ErrUnexpectedEOF
			}
			b, err = readHexByte(r.line[1], r.line[2])
			if err != nil {
				return n, err
			}
			r.line = r.line[2:] // 2 of the 3; other 1 is done below
		case b == '\t' || b == '\r' || b == '\n':
			break
		case b < ' ' || b > '~':
			return n, fmt.Errorf("quotedprintable: invalid unescaped byte 0x%02x in body", b)
		}
		p[0] = b
		p = p[1:]
		r.line = r.line[1:]
		n++
	}
	return n, nil
}
431569
func (s *syntheticByteStream) Read(p []byte) (int, error) {
	s.mu.Lock()
	defer s.mu.Unlock()

	start := s.offset
	end := start + int64(len(p))
	var err error
	if end >= s.size {
		err = io.EOF
		end = s.size
	}

	for idx := start; idx < end; idx++ {
		p[idx-start] = s.factory(idx)
	}

	s.offset = end

	return int(end - start), err
}
680404
func (rwops *RWops) Read(buf []byte) (n int, err error) {
	return rwops.Read2(buf, 1, uint(len(buf)))
}
53872
func (r *reader) read() error {
	n, err := r.r.Read(r.b)
	if err != nil {
		return trace.Wrap(err)
	}
	if n < 1 {
		return trace.Errorf("unexpected error, read 0 bytes")
	}

	switch r.b[0] {
	case OKByte:
		return nil
	case WarnByte, ErrByte:
		r.s.Scan()
		if err := r.s.Err(); err != nil {
			return trace.Wrap(err)
		}
		return trace.Errorf(r.s.Text())
	}
	return trace.Errorf("unrecognized command: %#v", r.b)
}
724529
func (r *buffer) Read(b []byte) (int, error) {
	if r.off >= r.size {
		return 0, io.EOF
	}
	if n := r.size - r.off; len(b) > n {
		b = b[:n]
	}
	n := copy(b, r.data[r.off:])
	r.off += n
	return n, nil
}
661460
func (b *Buffer) Read(p []byte) (int, error) {
	version := b.preOp()
	n, err := b.buf.Read(p)
	b.postOp(version)
	return n, err
}
227814
func (l *lexer) read() (rune, Error) {
	var _r rune
	var _err error

	// do we have any unread runes to read?
	_length := len(l._unread)
	if _length > 0 {
		_r = l._unread[_length-1]
		l._unread = l._unread[:_length-1]

		// otherwise, attempt to read a new rune
	} else {
		_r, _, _err = l._r.ReadRune()
		if _err == io.EOF {
			return _EOF, nil
		}
	}

	// increment the offset and column counts
	l._offset++
	l._column++

	return _r, l.err(_err)
}
487365
func (d *Decoder) Read(dst interface{}) error {
	return binary.Read(d.r, binary.BigEndian, dst)
}
579641
func Read(r *bufio.Reader) Value {
	res, _ := ReadValue(r)
	return res
}
550085
func (r Reader) Read(data []byte) (n int, err error) {
	if r.reader == nil {
		return os.Stdin.Read(data)
	}
	return r.reader.Read(data)
}
501459
func (r *Reader) Read(b []byte) (int, error) {
	// if we have data in the buffer, just
	// return that.
	if r.buffered() != 0 {
		x := copy(b, r.data[r.n:])
		r.n += x
		return x, nil
	}
	var n int
	// we have no buffered data; determine
	// whether or not to buffer or call
	// the underlying reader directly
	if len(b) >= cap(r.data) {
		n, r.state = r.r.Read(b)
	} else {
		r.more()
		n = copy(b, r.data)
		r.n = n
	}
	if n == 0 {
		return 0, r.err()
	}
	return n, nil
}
440587
func (ar *AnsiReader) Read(b []byte) (int, error) {
	if len(b) == 0 {
		return 0, nil
	}

	if len(ar.buf) == 0 {
		var runes []rune
		var read uint32
		rec := new(inputRecord)

		for runes == nil {
			ret, _, err := readConsoleInput.Call(ar.fd, uintptr(unsafe.Pointer(rec)),
				1, uintptr(unsafe.Pointer(&read)))
			if ret == 0 {
				return 0, err
			}

			if rec.eventType != keyEventType {
				continue
			}

			ke := (*keyEventRecord)(unsafe.Pointer(&rec.event))
			if ke.keyDown == 0 {
				continue
			}

			shift := false
			if ke.controlKeyState&shiftKey != 0 {
				shift = true
			}

			ctrl := false
			if ke.controlKeyState&leftCtrlKey != 0 || ke.controlKeyState&rightCtrlKey != 0 {
				ctrl = true
			}

			alt := false
			if ke.controlKeyState&leftAltKey != 0 || ke.controlKeyState&rightAltKey != 0 {
				alt = true
			}

			// Backspace, Return, Space.
			if ke.char == ctrlH || ke.char == returnKey || ke.char == spaceKey {
				code := string(returnKey)
				if ke.char == ctrlH {
					code = string(backKey)
				} else if ke.char == spaceKey {
					code = string(spaceKey)
				}

				if alt {
					code = string(escKey) + code
				}

				runes = []rune(code)
				break
			}

			// Generate runes for the chars and key codes.
			if ke.char > 0 {
				runes = []rune{rune(ke.char)}
			} else {
				code := string(escKey)

				switch ke.virtualKeyCode {
				case f1Key:
					if ctrl {
						continue
					}

					code += ar.shortFunction("P", shift, ctrl, alt)
				case f2Key:
					code += ar.shortFunction("Q", shift, ctrl, alt)
				case f3Key:
					code += ar.shortFunction("R", shift, ctrl, alt)
				case f4Key:
					code += ar.shortFunction("S", shift, ctrl, alt)
				case f5Key:
					code += ar.longFunction("15", shift, ctrl, alt)
				case f6Key:
					code += ar.longFunction("17", shift, ctrl, alt)
				case f7Key:
					code += ar.longFunction("18", shift, ctrl, alt)
				case f8Key:
					code += ar.longFunction("19", shift, ctrl, alt)
				case f9Key:
					code += ar.longFunction("20", shift, ctrl, alt)
				case f10Key:
					code += ar.longFunction("21", shift, ctrl, alt)
				case f11Key:
					code += ar.longFunction("23", shift, ctrl, alt)
				case f12Key:
					code += ar.longFunction("24", shift, ctrl, alt)
				case insertKey:
					if shift || ctrl {
						continue
					}

					code += ar.longFunction("2", shift, ctrl, alt)
				case deleteKey:
					code += ar.longFunction("3", shift, ctrl, alt)
				case homeKey:
					code += "OH"
				case endKey:
					code += "OF"
				case pgupKey:
					if shift {
						continue
					}

					code += ar.longFunction("5", shift, ctrl, alt)
				case pgdownKey:
					if shift {
						continue
					}

					code += ar.longFunction("6", shift, ctrl, alt)
				case upKey:
					code += ar.arrow("A", shift, ctrl, alt)
				case downKey:
					code += ar.arrow("B", shift, ctrl, alt)
				case leftKey:
					code += ar.arrow("D", shift, ctrl, alt)
				case rightKey:
					code += ar.arrow("C", shift, ctrl, alt)
				default:
					continue
				}

				runes = []rune(code)
			}
		}

		ar.buf = runes
	}

	// Get items from the buffer.
	var n int
	for i, r := range ar.buf {
		if utf8.RuneLen(r) > len(b) {
			ar.buf = ar.buf[i:]
			return n, nil
		}

		nr := utf8.EncodeRune(b, r)
		b = b[nr:]
		n += nr
	}

	ar.buf = nil
	return n, nil
}
964092
func (r *Reader) Read(b []byte) (n int, err error) {
	if len(b) == 0 {
		return 0, nil
	}
	if r.pos >= len(r.buf) {
		return 0, io.EOF
	}
	n = copy(b, r.buf[r.pos:])
	r.pos += n
	return
}
727846
func (d Decoder) read() (*bytes.Buffer, error) {
	output := &bytes.Buffer{}
	for {
		lengthBytes := make([]byte, 2)
		if numRead, err := io.ReadFull(d.r, lengthBytes); numRead != 2 {
			return nil, errors.Wrap(err, "Couldn't read expected bytes for message length. Read: %d Expected: 2.", numRead)
		}

		// Chunk header contains length of current message
		messageLen := binary.BigEndian.Uint16(lengthBytes)
		if messageLen == 0 {
			// If the length is 0, the chunk is done.
			return output, nil
		}

		data, err := d.readData(messageLen)
		if err != nil {
			return output, errors.Wrap(err, "An error occurred reading message data")
		}

		numWritten, err := output.Write(data)
		if numWritten < len(data) {
			return output, errors.New("Didn't write full data on output. Expected: %d Wrote: %d", len(data), numWritten)
		} else if err != nil {
			return output, errors.Wrap(err, "Error writing data to output")
		}
	}
}