github.com/getgauge/gauge@v1.6.9/api/lang/file.go (about)

     1  /*----------------------------------------------------------------
     2   *  Copyright (c) ThoughtWorks, Inc.
     3   *  Licensed under the Apache License, Version 2.0
     4   *  See LICENSE in the project root for license information.
     5   *----------------------------------------------------------------*/
     6  
     7  package lang
     8  
     9  import (
    10  	"strings"
    11  
    12  	"sync"
    13  
    14  	"github.com/getgauge/gauge/util"
    15  	"github.com/sourcegraph/go-langserver/pkg/lsp"
    16  )
    17  
    18  type files struct {
    19  	cache map[lsp.DocumentURI][]string
    20  	sync.Mutex
    21  }
    22  
    23  func (file *files) add(uri lsp.DocumentURI, text string) {
    24  	file.Lock()
    25  	defer file.Unlock()
    26  	file.cache[uri] = util.GetLinesFromText(text)
    27  }
    28  
    29  func (file *files) remove(uri lsp.DocumentURI) {
    30  	file.Lock()
    31  	defer file.Unlock()
    32  	delete(file.cache, uri)
    33  }
    34  
    35  func (file *files) line(uri lsp.DocumentURI, lineNo int) string {
    36  	if !file.exists(uri) || len(file.content(uri)) <= lineNo {
    37  		return ""
    38  	}
    39  	file.Lock()
    40  	defer file.Unlock()
    41  	return file.cache[uri][lineNo]
    42  }
    43  
    44  func (file *files) content(uri lsp.DocumentURI) []string {
    45  	file.Lock()
    46  	defer file.Unlock()
    47  	return file.cache[uri]
    48  }
    49  
    50  func (file *files) exists(uri lsp.DocumentURI) bool {
    51  	file.Lock()
    52  	defer file.Unlock()
    53  	_, ok := file.cache[uri]
    54  	return ok
    55  }
    56  
    57  var openFilesCache = &files{cache: make(map[lsp.DocumentURI][]string)}
    58  
    59  func openFile(params lsp.DidOpenTextDocumentParams) {
    60  	openFilesCache.add(params.TextDocument.URI, params.TextDocument.Text)
    61  }
    62  
    63  func closeFile(params lsp.DidCloseTextDocumentParams) {
    64  	openFilesCache.remove(params.TextDocument.URI)
    65  }
    66  
    67  func changeFile(params lsp.DidChangeTextDocumentParams) {
    68  	openFilesCache.add(params.TextDocument.URI, params.ContentChanges[0].Text)
    69  }
    70  
    71  func getLine(uri lsp.DocumentURI, line int) string {
    72  	return openFilesCache.line(uri, line)
    73  }
    74  
    75  func getContent(uri lsp.DocumentURI) string {
    76  	return strings.Join(openFilesCache.content(uri), "\n")
    77  }
    78  
    79  func isOpen(uri lsp.DocumentURI) bool {
    80  	return openFilesCache.exists(uri)
    81  }