Skip to content

Instantly share code, notes, and snippets.

@egonelbre
Created October 5, 2018 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egonelbre/6b0e3048bb28423d52a62ed1633e693d to your computer and use it in GitHub Desktop.
Save egonelbre/6b0e3048bb28423d52a62ed1633e693d to your computer and use it in GitHub Desktop.
Converts Go profile from package paths to filepaths
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"sort"
"strings"
"golang.org/x/tools/go/packages"
)
func main() {
var input io.Reader = os.Stdin
if len(os.Args) > 1 {
var err error
input, err = os.Open(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
coverFile, err := ioutil.ReadAll(input)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
coveredPackages := map[string]struct{}{}
scanner := bufio.NewScanner(bytes.NewReader(coverFile))
for scanner.Scan() {
line := scanner.Text()
tokens := strings.SplitN(line, ":", 2)
if len(tokens) <= 1 {
continue
}
if tokens[0] == "mode" {
continue
}
coveredPackages[path.Dir(tokens[0])] = struct{}{}
}
sortedPackages := []string{}
for coveredPackage := range coveredPackages {
sortedPackages = append(sortedPackages, coveredPackage)
}
sort.Strings(sortedPackages)
loadedPackages, err := packages.Load(&packages.Config{
Mode: packages.LoadFiles,
Tests: true,
}, sortedPackages...)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to load packages: %v", err)
}
packagePath := map[string]string{}
for _, pkg := range loadedPackages {
if len(pkg.GoFiles) > 0 {
packagePath[pkg.ID] = filepath.Dir(pkg.GoFiles[0])
}
}
scanner = bufio.NewScanner(bytes.NewReader(coverFile))
for scanner.Scan() {
line := scanner.Text()
tokens := strings.SplitN(line, ":", 2)
if len(tokens) <= 1 {
fmt.Println(line)
continue
}
if tokens[0] == "mode" {
fmt.Println(line)
continue
}
pkgname := path.Dir(tokens[0])
file := path.Base(tokens[0])
pkgpath, ok := packagePath[pkgname]
if !ok {
fmt.Println(line)
continue
}
fmt.Println(filepath.Join(pkgpath, file) + ":" + tokens[1])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment