Source file src/embed/embed.go
1 // Copyright 2020 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package embed provides access to files embedded in the running Go program. 6 // 7 // Go source files that import "embed" can use the //go:embed directive 8 // to initialize a variable of type string, []byte, or FS with the contents of 9 // files read from the package directory or subdirectories at compile time. 10 // 11 // For example, here are three ways to embed a file named hello.txt 12 // and then print its contents at run time. 13 // 14 // Embedding one file into a string: 15 // 16 // import _ "embed" 17 // 18 // //go:embed hello.txt 19 // var s string 20 // print(s) 21 // 22 // Embedding one file into a slice of bytes: 23 // 24 // import _ "embed" 25 // 26 // //go:embed hello.txt 27 // var b []byte 28 // print(string(b)) 29 // 30 // Embedded one or more files into a file system: 31 // 32 // import "embed" 33 // 34 // //go:embed hello.txt 35 // var f embed.FS 36 // data, _ := f.ReadFile("hello.txt") 37 // print(string(data)) 38 // 39 // Directives 40 // 41 // A //go:embed directive above a variable declaration specifies which files to embed, 42 // using one or more path.Match patterns. 43 // 44 // The directive must immediately precede a line containing the declaration of a single variable. 45 // Only blank lines and ‘//’ line comments are permitted between the directive and the declaration. 46 // 47 // The type of the variable must be a string type, or a slice of a byte type, 48 // or FS (or an alias of FS). 49 // 50 // For example: 51 // 52 // package server 53 // 54 // import "embed" 55 // 56 // // content holds our static web server content. 57 // //go:embed image/* template/* 58 // //go:embed html/index.html 59 // var content embed.FS 60 // 61 // The Go build system will recognize the directives and arrange for the declared variable 62 // (in the example above, content) to be populated with the matching files from the file system. 63 // 64 // The //go:embed directive accepts multiple space-separated patterns for 65 // brevity, but it can also be repeated, to avoid very long lines when there are 66 // many patterns. The patterns are interpreted relative to the package directory 67 // containing the source file. The path separator is a forward slash, even on 68 // Windows systems. Patterns may not contain ‘.’ or ‘..’ or empty path elements, 69 // nor may they begin or end with a slash. To match everything in the current 70 // directory, use ‘*’ instead of ‘.’. To allow for naming files with spaces in 71 // their names, patterns can be written as Go double-quoted or back-quoted 72 // string literals. 73 // 74 // If a pattern names a directory, all files in the subtree rooted at that directory are 75 // embedded (recursively), except that files with names beginning with ‘.’ or ‘_’ 76 // are excluded. So the variable in the above example is almost equivalent to: 77 // 78 // // content is our static web server content. 79 // //go:embed image template html/index.html 80 // var content embed.FS 81 // 82 // The difference is that ‘image/*’ embeds ‘image/.tempfile’ while ‘image’ does not. 83 // Neither embeds ‘image/dir/.tempfile’. 84 // 85 // If a pattern begins with the prefix ‘all:’, then the rule for walking directories is changed 86 // to include those files beginning with ‘.’ or ‘_’. For example, ‘all:image’ embeds 87 // both ‘image/.tempfile’ and ‘image/dir/.tempfile’. 88 // 89 // The //go:embed directive can be used with both exported and unexported variables, 90 // depending on whether the package wants to make the data available to other packages. 91 // It can only be used with variables at package scope, not with local variables. 92 // 93 // Patterns must not match files outside the package's module, such as ‘.git/*’ or symbolic links. 94 // Matches for empty directories are ignored. After that, each pattern in a //go:embed line 95 // must match at least one file or non-empty directory. 96 // 97 // If any patterns are invalid or have invalid matches, the build will fail. 98 // 99 // Strings and Bytes 100 // 101 // The //go:embed line for a variable of type string or []byte can have only a single pattern, 102 // and that pattern can match only a single file. The string or []byte is initialized with 103 // the contents of that file. 104 // 105 // The //go:embed directive requires importing "embed", even when using a string or []byte. 106 // In source files that don't refer to embed.FS, use a blank import (import _ "embed"). 107 // 108 // File Systems 109 // 110 // For embedding a single file, a variable of type string or []byte is often best. 111 // The FS type enables embedding a tree of files, such as a directory of static 112 // web server content, as in the example above. 113 // 114 // FS implements the io/fs package's FS interface, so it can be used with any package that 115 // understands file systems, including net/http, text/template, and html/template. 116 // 117 // For example, given the content variable in the example above, we can write: 118 // 119 // http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(content)))) 120 // 121 // template.ParseFS(content, "*.tmpl") 122 // 123 // Tools 124 // 125 // To support tools that analyze Go packages, the patterns found in //go:embed lines 126 // are available in “go list” output. See the EmbedPatterns, TestEmbedPatterns, 127 // and XTestEmbedPatterns fields in the “go help list” output. 128 // 129 package embed 130 131 import ( 132 "errors" 133 "io" 134 "io/fs" 135 "time" 136 ) 137 138 // An FS is a read-only collection of files, usually initialized with a //go:embed directive. 139 // When declared without a //go:embed directive, an FS is an empty file system. 140 // 141 // An FS is a read-only value, so it is safe to use from multiple goroutines 142 // simultaneously and also safe to assign values of type FS to each other. 143 // 144 // FS implements fs.FS, so it can be used with any package that understands 145 // file system interfaces, including net/http, text/template, and html/template. 146 // 147 // See the package documentation for more details about initializing an FS. 148 type FS struct { 149 // The compiler knows the layout of this struct. 150 // See cmd/compile/internal/staticdata's WriteEmbed. 151 // 152 // The files list is sorted by name but not by simple string comparison. 153 // Instead, each file's name takes the form "dir/elem" or "dir/elem/". 154 // The optional trailing slash indicates that the file is itself a directory. 155 // The files list is sorted first by dir (if dir is missing, it is taken to be ".") 156 // and then by base, so this list of files: 157 // 158 // p 159 // q/ 160 // q/r 161 // q/s/ 162 // q/s/t 163 // q/s/u 164 // q/v 165 // w 166 // 167 // is actually sorted as: 168 // 169 // p # dir=. elem=p 170 // q/ # dir=. elem=q 171 // w/ # dir=. elem=w 172 // q/r # dir=q elem=r 173 // q/s/ # dir=q elem=s 174 // q/v # dir=q elem=v 175 // q/s/t # dir=q/s elem=t 176 // q/s/u # dir=q/s elem=u 177 // 178 // This order brings directory contents together in contiguous sections 179 // of the list, allowing a directory read to use binary search to find 180 // the relevant sequence of entries. 181 files *[]file 182 } 183 184 // split splits the name into dir and elem as described in the 185 // comment in the FS struct above. isDir reports whether the 186 // final trailing slash was present, indicating that name is a directory. 187 func split(name string) (dir, elem string, isDir bool) { 188 if name[len(name)-1] == '/' { 189 isDir = true 190 name = name[:len(name)-1] 191 } 192 i := len(name) - 1 193 for i >= 0 && name[i] != '/' { 194 i-- 195 } 196 if i < 0 { 197 return ".", name, isDir 198 } 199 return name[:i], name[i+1:], isDir 200 } 201 202 // trimSlash trims a trailing slash from name, if present, 203 // returning the possibly shortened name. 204 func trimSlash(name string) string { 205 if len(name) > 0 && name[len(name)-1] == '/' { 206 return name[:len(name)-1] 207 } 208 return name 209 } 210 211 var ( 212 _ fs.ReadDirFS = FS{} 213 _ fs.ReadFileFS = FS{} 214 ) 215 216 // A file is a single file in the FS. 217 // It implements fs.FileInfo and fs.DirEntry. 218 type file struct { 219 // The compiler knows the layout of this struct. 220 // See cmd/compile/internal/staticdata's WriteEmbed. 221 name string 222 data string 223 hash [16]byte // truncated SHA256 hash 224 } 225 226 var ( 227 _ fs.FileInfo = (*file)(nil) 228 _ fs.DirEntry = (*file)(nil) 229 ) 230 231 func (f *file) Name() string { _, elem, _ := split(f.name); return elem } 232 func (f *file) Size() int64 { return int64(len(f.data)) } 233 func (f *file) ModTime() time.Time { return time.Time{} } 234 func (f *file) IsDir() bool { _, _, isDir := split(f.name); return isDir } 235 func (f *file) Sys() any { return nil } 236 func (f *file) Type() fs.FileMode { return f.Mode().Type() } 237 func (f *file) Info() (fs.FileInfo, error) { return f, nil } 238 239 func (f *file) Mode() fs.FileMode { 240 if f.IsDir() { 241 return fs.ModeDir | 0555 242 } 243 return 0444 244 } 245 246 // dotFile is a file for the root directory, 247 // which is omitted from the files list in a FS. 248 var dotFile = &file{name: "./"} 249 250 // lookup returns the named file, or nil if it is not present. 251 func (f FS) lookup(name string) *file { 252 if !fs.ValidPath(name) { 253 // The compiler should never emit a file with an invalid name, 254 // so this check is not strictly necessary (if name is invalid, 255 // we shouldn't find a match below), but it's a good backstop anyway. 256 return nil 257 } 258 if name == "." { 259 return dotFile 260 } 261 if f.files == nil { 262 return nil 263 } 264 265 // Binary search to find where name would be in the list, 266 // and then check if name is at that position. 267 dir, elem, _ := split(name) 268 files := *f.files 269 i := sortSearch(len(files), func(i int) bool { 270 idir, ielem, _ := split(files[i].name) 271 return idir > dir || idir == dir && ielem >= elem 272 }) 273 if i < len(files) && trimSlash(files[i].name) == name { 274 return &files[i] 275 } 276 return nil 277 } 278 279 // readDir returns the list of files corresponding to the directory dir. 280 func (f FS) readDir(dir string) []file { 281 if f.files == nil { 282 return nil 283 } 284 // Binary search to find where dir starts and ends in the list 285 // and then return that slice of the list. 286 files := *f.files 287 i := sortSearch(len(files), func(i int) bool { 288 idir, _, _ := split(files[i].name) 289 return idir >= dir 290 }) 291 j := sortSearch(len(files), func(j int) bool { 292 jdir, _, _ := split(files[j].name) 293 return jdir > dir 294 }) 295 return files[i:j] 296 } 297 298 // Open opens the named file for reading and returns it as an fs.File. 299 // 300 // The returned file implements io.Seeker when the file is not a directory. 301 func (f FS) Open(name string) (fs.File, error) { 302 file := f.lookup(name) 303 if file == nil { 304 return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist} 305 } 306 if file.IsDir() { 307 return &openDir{file, f.readDir(name), 0}, nil 308 } 309 return &openFile{file, 0}, nil 310 } 311 312 // ReadDir reads and returns the entire named directory. 313 func (f FS) ReadDir(name string) ([]fs.DirEntry, error) { 314 file, err := f.Open(name) 315 if err != nil { 316 return nil, err 317 } 318 dir, ok := file.(*openDir) 319 if !ok { 320 return nil, &fs.PathError{Op: "read", Path: name, Err: errors.New("not a directory")} 321 } 322 list := make([]fs.DirEntry, len(dir.files)) 323 for i := range list { 324 list[i] = &dir.files[i] 325 } 326 return list, nil 327 } 328 329 // ReadFile reads and returns the content of the named file. 330 func (f FS) ReadFile(name string) ([]byte, error) { 331 file, err := f.Open(name) 332 if err != nil { 333 return nil, err 334 } 335 ofile, ok := file.(*openFile) 336 if !ok { 337 return nil, &fs.PathError{Op: "read", Path: name, Err: errors.New("is a directory")} 338 } 339 return []byte(ofile.f.data), nil 340 } 341 342 // An openFile is a regular file open for reading. 343 type openFile struct { 344 f *file // the file itself 345 offset int64 // current read offset 346 } 347 348 var ( 349 _ io.Seeker = (*openFile)(nil) 350 ) 351 352 func (f *openFile) Close() error { return nil } 353 func (f *openFile) Stat() (fs.FileInfo, error) { return f.f, nil } 354 355 func (f *openFile) Read(b []byte) (int, error) { 356 if f.offset >= int64(len(f.f.data)) { 357 return 0, io.EOF 358 } 359 if f.offset < 0 { 360 return 0, &fs.PathError{Op: "read", Path: f.f.name, Err: fs.ErrInvalid} 361 } 362 n := copy(b, f.f.data[f.offset:]) 363 f.offset += int64(n) 364 return n, nil 365 } 366 367 func (f *openFile) Seek(offset int64, whence int) (int64, error) { 368 switch whence { 369 case 0: 370 // offset += 0 371 case 1: 372 offset += f.offset 373 case 2: 374 offset += int64(len(f.f.data)) 375 } 376 if offset < 0 || offset > int64(len(f.f.data)) { 377 return 0, &fs.PathError{Op: "seek", Path: f.f.name, Err: fs.ErrInvalid} 378 } 379 f.offset = offset 380 return offset, nil 381 } 382 383 // An openDir is a directory open for reading. 384 type openDir struct { 385 f *file // the directory file itself 386 files []file // the directory contents 387 offset int // the read offset, an index into the files slice 388 } 389 390 func (d *openDir) Close() error { return nil } 391 func (d *openDir) Stat() (fs.FileInfo, error) { return d.f, nil } 392 393 func (d *openDir) Read([]byte) (int, error) { 394 return 0, &fs.PathError{Op: "read", Path: d.f.name, Err: errors.New("is a directory")} 395 } 396 397 func (d *openDir) ReadDir(count int) ([]fs.DirEntry, error) { 398 n := len(d.files) - d.offset 399 if n == 0 { 400 if count <= 0 { 401 return nil, nil 402 } 403 return nil, io.EOF 404 } 405 if count > 0 && n > count { 406 n = count 407 } 408 list := make([]fs.DirEntry, n) 409 for i := range list { 410 list[i] = &d.files[d.offset+i] 411 } 412 d.offset += n 413 return list, nil 414 } 415 416 // sortSearch is like sort.Search, avoiding an import. 417 func sortSearch(n int, f func(int) bool) int { 418 // Define f(-1) == false and f(n) == true. 419 // Invariant: f(i-1) == false, f(j) == true. 420 i, j := 0, n 421 for i < j { 422 h := int(uint(i+j) >> 1) // avoid overflow when computing h 423 // i ≤ h < j 424 if !f(h) { 425 i = h + 1 // preserves f(i-1) == false 426 } else { 427 j = h // preserves f(j) == true 428 } 429 } 430 // i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i. 431 return i 432 } 433