/
show.go
85 lines (77 loc) · 2.6 KB
/
show.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
// vim:ts=4:sw=4:noexpandtab
package show
import (
"context"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/Debian/dcs/cmd/dcs-web/common"
"github.com/Debian/dcs/cmd/dcs-web/health"
"github.com/Debian/dcs/internal/proto/sourcebackendpb"
"github.com/Debian/dcs/shardmapping"
)
func Show(w http.ResponseWriter, r *http.Request) {
query := r.URL
filename := query.Query().Get("file")
line64, err := strconv.ParseInt(query.Query().Get("line"), 10, 0)
if err != nil {
log.Printf("%v\n", err)
return
}
line := int(line64)
log.Printf("Showing file %s, line %d\n", filename, line)
if *common.UseSourcesDebianNet && health.IsHealthy("sources.debian.org") {
u, _ := url.Parse("https://sources.debian.org/")
u.Path = "/src/" + strings.Replace(filename, "_", "/", 1)
q := u.Query()
q.Set("hl", strconv.Itoa(line))
u.RawQuery = q.Encode()
u.Fragment = "L" + strconv.Itoa(line)
destination := u.String()
log.Printf("SDN is healthy. Redirecting to %s\n", destination)
http.Redirect(w, r, destination, 302)
return
}
idx := strings.Index(filename, "/")
if idx == -1 {
http.Error(w, "Filename does not contain a package", http.StatusInternalServerError)
return
}
pkg := filename[:idx]
shard := common.SourceBackendStubs[shardmapping.TaskIdxForPackage(pkg, len(common.SourceBackendStubs))]
resp, err := shard.File(context.Background(), &sourcebackendpb.FileRequest{
Path: filename,
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// NB: contents is untrusted as it can contain the contents of any file
// within any Debian package. Converting it to string is not a problem,
// though, see http://golang.org/ref/spec#Conversions, "Conversions to and
// from a string type": "Converting a slice of bytes to a string type
// yields a string whose successive bytes are the elements of the slice.".
// We don’t iterate over this string, we just pass it directly to the
// user’s browser, which can then deal with the bytes :-).
lines := strings.Split(string(resp.Contents), "\n")
highestLineNr := fmt.Sprintf("%d", len(lines))
// Since Go templates don’t offer any way to use {{$idx+1}}, we need to
// pre-calculate line numbers starting from 1 here.
lineNumbers := make([]int, len(lines))
for idx, _ := range lines {
lineNumbers[idx] = idx + 1
}
err = common.Templates.ExecuteTemplate(w, "show.html", map[string]interface{}{
"line": line,
"lines": lines,
"numbers": lineNumbers,
"lnrwidth": len(highestLineNr),
"filename": filename,
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}