github.com/getgauge/gauge@v1.6.9/util/uriUtils.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 util
     8  
     9  import (
    10  	"net/url"
    11  	"strings"
    12  
    13  	"github.com/sourcegraph/go-langserver/pkg/lsp"
    14  )
    15  
    16  const (
    17  	uriPrefix      = "file://"
    18  	UnixSep        = "/"
    19  	windowColonRep = "%3A"
    20  	colon          = ":"
    21  	WindowsSep     = "\\"
    22  )
    23  
    24  // ConvertURItoFilePath - converts file uri (eg: file://example.spec) to OS specific file paths.
    25  func ConvertURItoFilePath(uri lsp.DocumentURI) string {
    26  	if IsWindows() {
    27  		return convertURIToWindowsPath(string(uri))
    28  	}
    29  	return convertURIToUnixPath(string(uri))
    30  }
    31  
    32  func convertURIToWindowsPath(uri string) string {
    33  	uri = strings.TrimPrefix(uri, uriPrefix+UnixSep)
    34  	uri = strings.Replace(uri, windowColonRep, colon, -1)
    35  	path, _ := url.PathUnescape(strings.Replace(uri, UnixSep, WindowsSep, -1))
    36  	return path
    37  }
    38  
    39  func convertURIToUnixPath(uri string) string {
    40  	path, _ := url.PathUnescape(uri)
    41  	return strings.TrimPrefix(path, uriPrefix)
    42  }
    43  
    44  // ConvertPathToURI - converts OS specific file paths to file uri (eg: file://example.spec).
    45  func ConvertPathToURI(path string) lsp.DocumentURI {
    46  	if IsWindows() {
    47  		return lsp.DocumentURI(convertWindowsPathToURI(path))
    48  	}
    49  	return lsp.DocumentURI(convertUnixPathToURI(path))
    50  }
    51  
    52  func convertWindowsPathToURI(path string) string {
    53  	path = strings.Replace(path, WindowsSep, UnixSep, -1)
    54  	encodedPath := url.URL{Path: path}
    55  	path = strings.Replace(strings.TrimPrefix(encodedPath.String(), "./"), colon, windowColonRep, -1)
    56  	return uriPrefix + UnixSep + path
    57  }
    58  
    59  func convertUnixPathToURI(path string) string {
    60  	encodedPath := url.URL{Path: path}
    61  	return uriPrefix + encodedPath.String()
    62  }