1//go:build !go1.21
2
3package fmtdirent
4
5import "io/fs"
6
7// Backport fs.FormatDirEntry from go1.21
8
9// FormatDirEntry returns a formatted version of dir for human readability.
10// Implementations of [DirEntry] can call this from a String method.
11// The outputs for a directory named subdir and a file named hello.go are:
12//
13// d subdir/
14// - hello.go
15func FormatDirEntry(dir fs.DirEntry) string {
16 name := dir.Name()
17 b := make([]byte, 0, 5+len(name))
18
19 // The Type method does not return any permission bits,
20 // so strip them from the string.
21 mode := dir.Type().String()
22 mode = mode[:len(mode)-9]
23
24 b = append(b, mode...)
25 b = append(b, ' ')
26 b = append(b, name...)
27 if dir.IsDir() {
28 b = append(b, '/')
29 }
30 return string(b)
31}