1
0
mirror of https://github.com/golang/go synced 2024-11-18 23:05:06 -07:00
go/internal/lsp/cache/file.go
Ian Cottrell 69a2705782 internal/lsp: remove error return values from interface "field" accessors
we don't really use them, only generate them in cases where the failure is way more fundamental, and then also fail
to remember them for the next call to the same accessor. Better to not have them.

Change-Id: I0e8abeda688f5cc2a932ed95a80d89225c399f93
Reviewed-on: https://go-review.googlesource.com/c/162399
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-02-13 21:58:50 +00:00

88 lines
1.7 KiB
Go

// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cache
import (
"go/ast"
"go/token"
"io/ioutil"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/internal/lsp/source"
)
// File holds all the information we know about a file.
type File struct {
URI source.URI
view *View
active bool
content []byte
ast *ast.File
token *token.File
pkg *packages.Package
}
// Read returns the contents of the file, reading it from file system if needed.
func (f *File) Read() ([]byte, error) {
f.view.mu.Lock()
defer f.view.mu.Unlock()
return f.read()
}
func (f *File) GetFileSet() *token.FileSet {
return f.view.Config.Fset
}
func (f *File) GetToken() *token.File {
f.view.mu.Lock()
defer f.view.mu.Unlock()
if f.token == nil {
if err := f.view.parse(f.URI); err != nil {
return nil
}
}
return f.token
}
func (f *File) GetAST() *ast.File {
f.view.mu.Lock()
defer f.view.mu.Unlock()
if f.ast == nil {
if err := f.view.parse(f.URI); err != nil {
return nil
}
}
return f.ast
}
func (f *File) GetPackage() *packages.Package {
f.view.mu.Lock()
defer f.view.mu.Unlock()
if f.pkg == nil {
if err := f.view.parse(f.URI); err != nil {
return nil
}
}
return f.pkg
}
// read is the internal part of Read that presumes the lock is already held
func (f *File) read() ([]byte, error) {
if f.content != nil {
return f.content, nil
}
// we don't know the content yet, so read it
filename, err := f.URI.Filename()
if err != nil {
return nil, err
}
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
f.content = content
return f.content, nil
}