Format a path in utf8, quoting it if necessary.
761558
def format_path(p, quote_spaces=False):
    """"""
    if b'\n' in p:
        p = re.sub(b'\n', b'\\n', p)
        quote = True
    else:
        quote = p[0] == b'"' or (quote_spaces and b' ' in p)
    if quote:
        extra = GIT_FAST_IMPORT_NEEDS_EXTRA_SPACE_AFTER_QUOTE and b' ' or b''
        p = b'"' + p + b'"' + extra
    return p
271872
private static String fileAsString(String path) throws Exception {
        StringBuffer buffer = new StringBuffer();
        InputStream fis = new FileInputStream(path);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        Reader in = new BufferedReader(isr);
        int ch;
        while ((ch = in.read()) > -1) {
            buffer.append((char) ch);
        }
        in.close();
        return buffer.toString();
    }
580710
def valid_path(value):
    ""
    # Generate UnicodeDecodeError if path can't store as ASCII.
    value.encode("ascii")
    # Cookies without leading slash will likely be ignored, raise ASAP.
    if not (value and value[0] == "/"):
        return False
    if not Definitions.PATH_RE.match(value):
        return False
    return True
64754
def translate_path(self, path):
        
        # abandon query parameters
        path = path.split('?', 1)[0]
        path = path.split('#', 1)[0]
        # Don't forget explicit trailing slash when normalizing. Issue17324
        trailing_slash = path.rstrip().endswith('/')
        path = posixpath.normpath(urllib.parse.unquote(path))
        words = path.split('/')
        words = [_f for _f in words if _f]
        path = self.base_path
        for word in words:
            _, word = os.path.splitdrive(word)
            _, word = os.path.split(word)
            if word in (os.curdir, os.pardir):
                continue
            path = os.path.join(path, word)
        if trailing_slash:
            path += '/'
        return path
688088
def display_path(path):
    # type: (Union[str, Text]) -> str
    """"""
    path = os.path.normcase(os.path.abspath(path))
    if sys.version_info[0] == 2:
        path = path.decode(sys.getfilesystemencoding(), 'replace')
        path = path.encode(sys.getdefaultencoding(), 'replace')
    if path.startswith(os.getcwd() + os.path.sep):
        path = '.' + path[len(os.getcwd()):]
    return path
685142
private boolean isInvalidEncodedPath(String path) {
		if (path.contains("%")) {
			try {
				// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8
				// chars
				String decodedPath = URLDecoder.decode(path, "UTF-8");
				if (isInvalidPath(decodedPath)) {
					return true;
				}
				decodedPath = processPath(decodedPath);
				if (isInvalidPath(decodedPath)) {
					return true;
				}
			}
			catch (IllegalArgumentException | UnsupportedEncodingException ex) {
				// Should never happen...
			}
		}
		return false;
	}
12204
def encodePathElement(element):
    """"""
    return urllib.parse.quote(
        (
            element.encode('utf-8')
            if isinstance(element, str)
            else str(element)
            if isinstance(element, int)
            else element
        ),
        safe=d1_common.const.URL_PATHELEMENT_SAFE_CHARS,
    )
1148590
def _path_pair(self, s):
        """"""
        # TODO: handle a space in the first path
        if s.startswith(b'"'):
            parts = s[1:].split(b'" ', 1)
        else:
            parts = s.split(b' ', 1)
        if len(parts) != 2:
            self.abort(errors.BadFormat, '?', '?', s)
        elif parts[1].startswith(b'"') and parts[1].endswith(b'"'):
            parts[1] = parts[1][1:-1]
        elif parts[1].startswith(b'"') or parts[1].endswith(b'"'):
            self.abort(errors.BadFormat, '?', '?', s)
        return [_unquote_c_string(s) for s in parts]
390149
def normalize_path(path, encoding='utf-8'):
    '''
    '''
    if not path.startswith('/'):
        path = '/' + path
    path = percent_encode(flatten_path(path, flatten_slashes=True), encoding=encoding)
    return uppercase_percent_encoding(path)
445885
def quote(s, unsafe='/'):
    """"""
    res = s.replace('%', '%25')
    for c in unsafe:
        res = res.replace(c, '%' + (hex(ord(c)).upper())[2:])
    return res
200841
def html_encode(path):
    
    if sys.version_info > (3, 2, 0):
        return urllib.parse.quote(utils.ensure_string(path))
    else:
        return urllib.quote(utils.ensure_string(path))
859547
def translate_path(self, path):
        
        # abandon query parameters
        path = path.split('?', 1)[0]
        path = path.split('#', 1)[0]
        # Don't forget explicit trailing slash when normalizing. Issue17324
        trailing_slash = path.rstrip().endswith('/')
        path = posixpath.normpath(urllib.unquote(path))
        # remove url_prefix
        #print "PATH 1: ", path, self._url_prefix
        path = path.replace(self._url_prefix, '/', 1)
        #print "PATH 2: ", path
        words = path.split('/')
        words = filter(None, words)
        # This the new way to NOT only work in CWD
        path = self._root
        for word in words:
            if os.path.dirname(word) or word in (os.curdir, os.pardir):
                # Ignore components that are not a simple file/directory name
                continue
            path = os.path.join(path, word)
        if trailing_slash:
            path += '/'
        #print "PATH: ", path
        #print "URL_PREFIX", self._url_prefix
        #print "PREFIX", self.prefix
        return path
821492
function encodePath(path) {
    const replaced = path.replace(/\//g, SEP_PATH_POSIX).replace(/\\\\/g, SEP_PATH_WINDOWS);
    const formatted = encodeURIComponent(replaced);
    return formatted
        .split(SEP_PATH_WINDOWS)
        .join("\\\\")
        .split(SEP_PATH_POSIX)
        .join("/");
}
19488
def read(path, encoding="UTF-8"):
    """"""
    with OPEN_FUNC(path, 'rb') as _file:
        cont = _file.read()
        return cont.decode(encoding)
1358852
private function formatDataPath(string $path): string
    {
        if ('data' !== $this->scheme) {
            return $path;
        }

        if ('' == $path) {
            return 'text/plain;charset=us-ascii,';
        }

        if (false === mb_detect_encoding($path, 'US-ASCII', true) || false === strpos($path, ',')) {
            throw new SyntaxError(sprintf('The path `%s` is invalid according to RFC2937', $path));
        }

        $parts = explode(',', $path, 2) + [1 => null];
        $mediatype = explode(';', (string) $parts[0], 2) + [1 => null];
        $data = (string) $parts[1];
        $mimetype = $mediatype[0];
        if (null === $mimetype || '' === $mimetype) {
            $mimetype = 'text/plain';
        }

        $parameters = $mediatype[1];
        if (null === $parameters || '' === $parameters) {
            $parameters = 'charset=us-ascii';
        }

        $this->assertValidPath($mimetype, $parameters, $data);

        return $mimetype.';'.$parameters.','.$data;
    }
335487
def _escape_path(key):
    '''
    
    '''
    return _tobytes(key).replace(b'$', b'$_').replace(b'/', b'$+').replace(b'\\', b'$$')
784344
def escape(s):
    """"""
    if not isinstance(s, bytes):
        s = s.encode('utf-8')
    return quote(s, safe='~')