locate go source

方便定位 go 源码内容, 比如

1
go build -gcflags -m 2>&1 | grep escapes | codeloc

  • main.go
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    package main

    import (
    "bufio"
    "bytes"
    "fmt"
    "io"
    "io/ioutil"
    "os"
    "strconv"
    "strings"
    )

    var filecaches = map[string][]byte{}

    func getfiledata(file string) []byte {
    data := filecaches[file]
    if data == nil {
    var err error
    data, err = ioutil.ReadFile(file)
    if err != nil {
    return nil
    }
    filecaches[file] = data
    }
    return data
    }

    func main() {
    cin := bufio.NewReader(os.Stdin)
    for {
    s, err := cin.ReadString('\n')
    s = strings.TrimSpace(s)
    if s == "" && err != nil {
    if err == io.EOF {
    break
    }
    os.Exit(1)
    }

    info := strings.SplitN(s, ":", 3)
    if len(info) != 3 {
    continue
    }
    ln, err := strconv.Atoi(info[1])
    if err != nil {
    continue
    }
    data := getfiledata(info[0])
    if data == nil {
    continue
    }

    // locate line
    fail := false
    p := 0
    n := 1
    for n < ln {
    nln := bytes.IndexByte(data[p:], '\n')
    if nln == -1 {
    fail = true
    break
    }
    p = p + nln + 1
    n++
    }
    if fail {
    fmt.Fprintf(os.Stderr, "%s:%d: no such line\n", info[0], ln)
    continue
    }

    nln := bytes.IndexByte(data[p:], '\n')
    if nln == -1 {
    nln = len(data) - p
    }
    code := string(data[p : p+nln])

    // replace indent
    tabs := 0
    for i := 0; i < len(code); i++ {
    if code[i] == '\t' {
    tabs++
    } else {
    break
    }
    }
    code = code[tabs:]
    fmt.Printf("%s\n%s\n\n", s, strings.Repeat(" ", tabs)+code)
    }
    }