-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile.go
86 lines (75 loc) · 1.9 KB
/
file.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
// Copyright (c) 2017 Opsidian Ltd.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package text
import (
"bytes"
"fmt"
"os"
"sort"
"github.com/conflowio/parsley/parsley"
)
// File contains the contents of a file and the line offsets for quick line+column lookup
type File struct {
filename string
data []byte
lines []int
len int
offset int
}
// NewFile creates a new file object
func NewFile(filename string, data []byte) *File {
f := &File{
filename: filename,
data: bytes.Replace(data, []byte("\r\n"), []byte("\n"), -1),
offset: 1,
}
f.len = len(f.data)
return f
}
// ReadFile reads a file and creates a File object
func ReadFile(filename string) (*File, error) {
data, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("can not read %s", filename)
}
return NewFile(filename, data), nil
}
// SetLinesForContent sets the line offsets
func (f *File) setLines() {
f.lines = []int{0}
for offset, b := range f.data {
if b == '\n' {
f.lines = append(f.lines, offset+1)
}
}
}
// Len returns with the length of the file in bytes
func (f *File) Len() int {
return f.len
}
// SetOffset set the offset of this file related to a file set
func (f *File) SetOffset(offset int) {
f.offset = offset
}
// Position returns with a Position object for the given offset
func (f *File) Position(pos int) parsley.Position {
if pos > f.len {
return parsley.NilPosition
}
if f.lines == nil {
f.setLines()
}
i := sort.Search(len(f.lines), func(i int) bool { return f.lines[i] > pos }) - 1
return &Position{
Filename: f.filename,
Line: i + 1,
Column: pos - f.lines[i] + 1,
}
}
// Pos returns with a global offset in a file set
func (f *File) Pos(pos int) parsley.Pos {
return parsley.Pos(f.offset + pos)
}