forked from google/zoekt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
indexbuilder.go
422 lines (348 loc) · 10.5 KB
/
indexbuilder.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package zoekt
import (
"bytes"
"encoding/binary"
"fmt"
"hash/crc64"
"html/template"
"log"
"path/filepath"
"sort"
"unicode/utf8"
)
var _ = log.Println
const ngramSize = 3
type searchableString struct {
data []byte
}
// Filled by the linker (see build-deploy.sh)
var Version string
// Store character (unicode codepoint) offset (in bytes) this often.
const runeOffsetFrequency = 100
type postingsBuilder struct {
postings map[ngram][]byte
lastOffsets map[ngram]uint32
// To support UTF-8 searching, we must map back runes to byte
// offsets. As a first attempt, we sample regularly. The
// precise offset can be found by walking from the recorded
// offset to the desired rune.
runeOffsets []uint32
runeCount uint32
isPlainASCII bool
endRunes []uint32
endByte uint32
}
func newPostingsBuilder() *postingsBuilder {
return &postingsBuilder{
postings: map[ngram][]byte{},
lastOffsets: map[ngram]uint32{},
isPlainASCII: true,
}
}
// Store trigram offsets for the given UTF-8 data. The
// DocumentSections must correspond to rune boundaries in the UTF-8
// data.
func (s *postingsBuilder) newSearchableString(data []byte, byteSections []DocumentSection) (*searchableString, []DocumentSection, error) {
dest := searchableString{
data: data,
}
var buf [8]byte
var runeGram [3]rune
var runeIndex uint32
byteCount := 0
dataSz := uint32(len(data))
byteSectionBoundaries := make([]uint32, 0, 2*len(byteSections))
for _, s := range byteSections {
byteSectionBoundaries = append(byteSectionBoundaries, s.Start, s.End)
}
var runeSectionBoundaries []uint32
endRune := s.runeCount
for ; len(data) > 0; runeIndex++ {
c, sz := utf8.DecodeRune(data)
if sz > 1 {
s.isPlainASCII = false
}
data = data[sz:]
runeGram[0], runeGram[1], runeGram[2] = runeGram[1], runeGram[2], c
if idx := s.runeCount + runeIndex; idx%runeOffsetFrequency == 0 {
s.runeOffsets = append(s.runeOffsets, s.endByte+uint32(byteCount))
}
for len(byteSectionBoundaries) > 0 && byteSectionBoundaries[0] == uint32(byteCount) {
runeSectionBoundaries = append(runeSectionBoundaries,
endRune+uint32(runeIndex))
byteSectionBoundaries = byteSectionBoundaries[1:]
}
byteCount += sz
if runeIndex < 2 {
continue
}
ng := runesToNGram(runeGram)
lastOff := s.lastOffsets[ng]
newOff := endRune + uint32(runeIndex) - 2
m := binary.PutUvarint(buf[:], uint64(newOff-lastOff))
s.postings[ng] = append(s.postings[ng], buf[:m]...)
s.lastOffsets[ng] = newOff
}
s.runeCount += runeIndex
for len(byteSectionBoundaries) > 0 && byteSectionBoundaries[0] < uint32(byteCount) {
return nil, nil, fmt.Errorf("no rune for section boundary at byte %d", byteSectionBoundaries[0])
}
// Handle symbol definition that ends at file end. This can
// happen for labels at the end of .bat files.
for len(byteSectionBoundaries) > 0 && byteSectionBoundaries[0] == uint32(byteCount) {
runeSectionBoundaries = append(runeSectionBoundaries,
endRune+runeIndex)
byteSectionBoundaries = byteSectionBoundaries[1:]
}
runeSecs := make([]DocumentSection, 0, len(byteSections))
for i := 0; i < len(runeSectionBoundaries); i += 2 {
runeSecs = append(runeSecs, DocumentSection{
Start: runeSectionBoundaries[i],
End: runeSectionBoundaries[i+1],
})
}
s.endRunes = append(s.endRunes, s.runeCount)
s.endByte += dataSz
return &dest, runeSecs, nil
}
// IndexBuilder builds a single index shard.
type IndexBuilder struct {
contentStrings []*searchableString
nameStrings []*searchableString
docSections [][]DocumentSection
runeDocSections []DocumentSection
checksums []byte
branchMasks []uint64
subRepos []uint32
contentPostings *postingsBuilder
namePostings *postingsBuilder
// root repository
repo Repository
// name to index.
subRepoIndices map[string]uint32
// language => language code
languageMap map[string]byte
// languages codes
languages []byte
}
func (d *Repository) verify() error {
for _, t := range []string{d.FileURLTemplate, d.LineFragmentTemplate, d.CommitURLTemplate} {
if _, err := template.New("").Parse(t); err != nil {
return err
}
}
return nil
}
// ContentSize returns the number of content bytes so far ingested.
func (b *IndexBuilder) ContentSize() uint32 {
// Add the name too so we don't skip building index if we have
// lots of empty files.
return b.contentPostings.endByte + b.namePostings.endByte
}
// NewIndexBuilder creates a fresh IndexBuilder. The passed in
// Repository contains repo metadata, and may be set to nil.
func NewIndexBuilder(r *Repository) (*IndexBuilder, error) {
b := &IndexBuilder{
contentPostings: newPostingsBuilder(),
namePostings: newPostingsBuilder(),
languageMap: map[string]byte{},
}
if r == nil {
r = &Repository{}
}
if err := b.setRepository(r); err != nil {
return nil, err
}
return b, nil
}
func (b *IndexBuilder) setRepository(desc *Repository) error {
if len(b.contentStrings) > 0 {
return fmt.Errorf("setRepository called after adding files")
}
if err := desc.verify(); err != nil {
return err
}
for _, subrepo := range desc.SubRepoMap {
branchEqual := len(subrepo.Branches) == len(desc.Branches)
if branchEqual {
for i, b := range subrepo.Branches {
branchEqual = branchEqual && (b.Name == desc.Branches[i].Name)
}
}
}
if len(desc.Branches) > 64 {
return fmt.Errorf("too many branches")
}
b.repo = *desc
repoCopy := *desc
repoCopy.SubRepoMap = nil
if b.repo.SubRepoMap == nil {
b.repo.SubRepoMap = map[string]*Repository{}
}
b.repo.SubRepoMap[""] = &repoCopy
b.populateSubRepoIndices()
return nil
}
type DocumentSection struct {
Start, End uint32
}
// Document holds a document (file) to index.
type Document struct {
Name string
Content []byte
Branches []string
SubRepositoryPath string
Language string
// If set, something is wrong with the file contents, and this
// is the reason it wasn't indexed.
SkipReason string
// Document sections for symbols. Offsets should use bytes.
Symbols []DocumentSection
}
type docSectionSlice []DocumentSection
func (m docSectionSlice) Len() int { return len(m) }
func (m docSectionSlice) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m docSectionSlice) Less(i, j int) bool { return m[i].Start < m[j].Start }
// AddFile is a convenience wrapper for Add
func (b *IndexBuilder) AddFile(name string, content []byte) error {
return b.Add(Document{Name: name, Content: content})
}
// CheckText returns a reason why the given contents are probably not source texts.
func CheckText(content []byte, maxTrigramCount int) error {
if len(content) == 0 {
return nil
}
if len(content) < ngramSize {
return fmt.Errorf("file size smaller than %d", ngramSize)
}
trigrams := map[ngram]struct{}{}
var cur [3]rune
byteCount := 0
for len(content) > 0 {
if content[0] == 0 {
return fmt.Errorf("binary data at byte offset %d", byteCount)
}
r, sz := utf8.DecodeRune(content)
content = content[sz:]
byteCount += sz
cur[0], cur[1], cur[2] = cur[1], cur[2], r
if cur[0] == 0 {
// start of file.
continue
}
trigrams[runesToNGram(cur)] = struct{}{}
if len(trigrams) > maxTrigramCount {
// probably not text.
return fmt.Errorf("number of trigrams exceeds %d", maxTrigramCount)
}
}
return nil
}
func (b *IndexBuilder) populateSubRepoIndices() {
if b.subRepoIndices != nil {
return
}
var paths []string
for k := range b.repo.SubRepoMap {
paths = append(paths, k)
}
sort.Strings(paths)
b.subRepoIndices = make(map[string]uint32, len(paths))
for i, p := range paths {
b.subRepoIndices[p] = uint32(i)
}
}
const notIndexedMarker = "NOT-INDEXED: "
// Add a file which only occurs in certain branches.
func (b *IndexBuilder) Add(doc Document) error {
hasher := crc64.New(crc64.MakeTable(crc64.ISO))
if idx := bytes.IndexByte(doc.Content, 0); idx >= 0 {
doc.SkipReason = fmt.Sprintf("binary content at byte offset %d", idx)
doc.Language = "binary"
}
if doc.SkipReason != "" {
doc.Content = []byte(notIndexedMarker + doc.SkipReason)
doc.Symbols = nil
if doc.Language == "" {
doc.Language = "skipped"
}
}
sort.Sort(docSectionSlice(doc.Symbols))
var last DocumentSection
for i, s := range doc.Symbols {
if i > 0 {
if last.End > s.Start {
return fmt.Errorf("sections overlap")
}
}
last = s
}
if last.End > uint32(len(doc.Content)) {
return fmt.Errorf("section goes past end of content")
}
if doc.SubRepositoryPath != "" {
rel, err := filepath.Rel(doc.SubRepositoryPath, doc.Name)
if err != nil || rel == doc.Name {
return fmt.Errorf("path %q must start subrepo path %q", doc.Name, doc.SubRepositoryPath)
}
}
docStr, runeSecs, err := b.contentPostings.newSearchableString(doc.Content, doc.Symbols)
if err != nil {
return err
}
nameStr, _, err := b.namePostings.newSearchableString([]byte(doc.Name), nil)
if err != nil {
return err
}
subRepoIdx, ok := b.subRepoIndices[doc.SubRepositoryPath]
if !ok {
return fmt.Errorf("unknown subrepo path %q", doc.SubRepositoryPath)
}
var mask uint64
for _, br := range doc.Branches {
m := b.branchMask(br)
if m == 0 {
return fmt.Errorf("no branch found for %s", br)
}
mask |= m
}
b.subRepos = append(b.subRepos, subRepoIdx)
hasher.Write(doc.Content)
b.contentStrings = append(b.contentStrings, docStr)
b.runeDocSections = append(b.runeDocSections, runeSecs...)
b.nameStrings = append(b.nameStrings, nameStr)
b.docSections = append(b.docSections, doc.Symbols)
b.branchMasks = append(b.branchMasks, mask)
b.checksums = append(b.checksums, hasher.Sum(nil)...)
langCode, ok := b.languageMap[doc.Language]
if !ok {
if len(b.languageMap) >= 255 {
return fmt.Errorf("too many languages")
}
langCode = byte(len(b.languageMap))
b.languageMap[doc.Language] = langCode
}
b.languages = append(b.languages, langCode)
return nil
}
func (b *IndexBuilder) branchMask(br string) uint64 {
for i, b := range b.repo.Branches {
if b.Name == br {
return uint64(1) << uint(i)
}
}
return 0
}