Debian Codegraph @

common/paths/url.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package paths
15
16 import (
17 "fmt"
18 "net/url"
19 "path"
20 "path/filepath"
21 "runtime"
22 "strings"
23 )
24
25 type pathBridge struct{}
26
27 func (pathBridge) Base(in string) string {
28 return path.Base(in)
29 }
30
31 func (pathBridge) Clean(in string) string {
32 return path.Clean(in)
33 }
34
35 func (pathBridge) Dir(in string) string {
36 return path.Dir(in)
37 }
38
39 func (pathBridge) Ext(in string) string {
40 return path.Ext(in)
41 }
42
43 func (pathBridge) Join(elem ...string) string {
44 return path.Join(elem...)
45 }
46
47 func (pathBridge) Separator() string {
48 return "/"
49 }
50
51 var pb pathBridge
52
53 // MakePermalink combines base URL with content path to create full URL paths.
54 // Example
55 //
56 // base: http://spf13.com/
57 // path: post/how-i-blog
58 // result: http://spf13.com/post/how-i-blog
59 func MakePermalink(host, plink string) *url.URL {
60 base, err := url.Parse(host)
61 if err != nil {
62 panic(err)
63 }
64
65 p, err := url.Parse(plink)
66 if err != nil {
67 panic(err)
68 }
69
70 if p.Host != "" {
71 panic(fmt.Errorf("can't make permalink from absolute link %q", plink))
72 }
73
74 base.Path = path.Join(base.Path, p.Path)
75 base.Fragment = p.Fragment
76 base.RawQuery = p.RawQuery
77
78 // path.Join will strip off the last /, so put it back if it was there.
79 hadTrailingSlash := (plink == "" && strings.HasSuffix(host, "/")) || strings.HasSuffix(p.Path, "/")
80 if hadTrailingSlash && !strings.HasSuffix(base.Path, "/") {
81 base.Path = base.Path + "/"
82 }
83
84 return base
85 }
86
87 // AddContextRoot adds the context root to an URL if it's not already set.
88 // For relative URL entries on sites with a base url with a context root set (i.e. http://example.com/mysite),
89 // relative URLs must not include the context root if canonifyURLs is enabled. But if it's disabled, it must be set.
90 func AddContextRoot(baseURL, relativePath string) string {
91 url, err := url.Parse(baseURL)
92 if err != nil {
93 panic(err)
94 }
95
96 newPath := path.Join(url.Path, relativePath)
97
98 // path strips trailing slash, ignore root path.
99 if newPath != "/" && strings.HasSuffix(relativePath, "/") {
100 newPath += "/"
101 }
102 return newPath
103 }
104
105 // URLEscape escapes unicode letters.
106 func URLEscape(uri string) string {
107 // escape unicode letters
108 u, err := url.Parse(uri)
109 if err != nil {
110 panic(err)
111 }
112 return u.String()
113 }
114
115 // TrimExt trims the extension from a path..
116 func TrimExt(in string) string {
117 return strings.TrimSuffix(in, path.Ext(in))
118 }
119
120 // From https://github.com/golang/go/blob/e0c76d95abfc1621259864adb3d101cf6f1f90fc/src/cmd/go/internal/web/url.go#L45
121 func UrlFromFilename(filename string) (*url.URL, error) {
122 if !filepath.IsAbs(filename) {
123 return nil, fmt.Errorf("filepath must be absolute")
124 }
125
126 // If filename has a Windows volume name, convert the volume to a host and prefix
127 // per https://blogs.msdn.microsoft.com/ie/2006/12/06/file-uris-in-windows/.
128 if vol := filepath.VolumeName(filename); vol != "" {
129 if strings.HasPrefix(vol, `\\`) {
130 filename = filepath.ToSlash(filename[2:])
131 i := strings.IndexByte(filename, '/')
132
133 if i < 0 {
134 // A degenerate case.
135 // \\host.example.com (without a share name)
136 // becomes
137 // file://host.example.com/
138 return &url.URL{
139 Scheme: "file",
140 Host: filename,
141 Path: "/",
142 }, nil
143 }
144
145 // \\host.example.com\Share\path\to\file
146 // becomes
147 // file://host.example.com/Share/path/to/file
148 return &url.URL{
149 Scheme: "file",
150 Host: filename[:i],
151 Path: filepath.ToSlash(filename[i:]),
152 }, nil
153 }
154
155 // C:\path\to\file
156 // becomes
157 // file:///C:/path/to/file
158 return &url.URL{
159 Scheme: "file",
160 Path: "/" + filepath.ToSlash(filename),
161 }, nil
162 }
163
164 // /path/to/file
165 // becomes
166 // file:///path/to/file
167 return &url.URL{
168 Scheme: "file",
169 Path: filepath.ToSlash(filename),
170 }, nil
171 }
172
173 // UrlStringToFilename converts the URL s to a filename.
174 // If ParseRequestURI fails, the input is just converted to OS specific slashes and returned.
175 func UrlStringToFilename(s string) (string, bool) {
176 u, err := url.ParseRequestURI(s)
177 if err != nil {
178 return filepath.FromSlash(s), false
179 }
180
181 p := u.Path
182
183 if p == "" {
184 p, _ = url.QueryUnescape(u.Opaque)
185 return filepath.FromSlash(p), false
186 }
187
188 if runtime.GOOS != "windows" {
189 return p, true
190 }
191
192 if len(p) == 0 || p[0] != '/' {
193 return filepath.FromSlash(p), false
194 }
195
196 p = filepath.FromSlash(p)
197
198 if len(u.Host) == 1 {
199 // file://c/Users/...
200 return strings.ToUpper(u.Host) + ":" + p, true
201 }
202
203 if u.Host != "" && u.Host != "localhost" {
204 if filepath.VolumeName(u.Host) != "" {
205 return "", false
206 }
207 return `\\` + u.Host + p, true
208 }
209
210 if vol := filepath.VolumeName(p[1:]); vol == "" || strings.HasPrefix(vol, `\\`) {
211 return "", false
212 }
213
214 return p[1:], true
215 }