Beispiel #1
0
func ExampleWalkFiles() {
	var fs http.FileSystem = httpfs.New(mapfs.New(map[string]string{
		"zzz-last-file.txt":   "It should be visited last.",
		"a-file.txt":          "It has stuff.",
		"another-file.txt":    "Also stuff.",
		"folderA/entry-A.txt": "Alpha.",
		"folderA/entry-B.txt": "Beta.",
	}))

	walkFn := func(path string, fi os.FileInfo, r io.ReadSeeker, err error) error {
		if err != nil {
			log.Printf("can't stat file %s: %v\n", path, err)
			return nil
		}
		fmt.Println(path)
		if !fi.IsDir() {
			b, err := ioutil.ReadAll(r)
			if err != nil {
				log.Printf("can't read file %s: %v\n", path, err)
				return nil
			}
			fmt.Printf("%q\n", b)
		}
		return nil
	}

	err := vfsutil.WalkFiles(fs, "/", walkFn)
	if err != nil {
		panic(err)
	}

	// Output:
	// /
	// /a-file.txt
	// "It has stuff."
	// /another-file.txt
	// "Also stuff."
	// /folderA
	// /folderA/entry-A.txt
	// "Alpha."
	// /folderA/entry-B.txt
	// "Beta."
	// /zzz-last-file.txt
	// "It should be visited last."
}
Beispiel #2
0
// findAndWriteFiles recursively finds all the file paths in the given directory tree.
// They are added to the given map as keys. Values will be safe function names
// for each file, which will be used when generating the output code.
func findAndWriteFiles(f *os.File, fs http.FileSystem, toc *toc) error {
	walkFn := func(path string, fi os.FileInfo, r io.ReadSeeker, err error) error {
		if err != nil {
			log.Printf("can't stat file %q: %v\n", path, err)
			return nil
		}

		switch fi.IsDir() {
		case false:
			file := &fileInfo{
				Path:             path,
				Name:             pathpkg.Base(path),
				ModTime:          fi.ModTime().UTC(),
				UncompressedSize: fi.Size(),
			}

			marker, err := f.Seek(0, os.SEEK_CUR)
			if err != nil {
				return err
			}

			// Write _vfsgen_compressedFileInfo.
			err = writeCompressedFileInfo(f, file, r)
			switch err {
			default:
				return err
			case nil:
				toc.HasCompressedFile = true
			// If compressed file is not smaller than original, revert and write original file.
			case errCompressedNotSmaller:
				_, err = r.Seek(0, os.SEEK_SET)
				if err != nil {
					return err
				}

				_, err = f.Seek(marker, os.SEEK_SET)
				if err != nil {
					return err
				}

				// Write _vfsgen_fileInfo.
				err = writeFileInfo(f, file, r)
				if err != nil {
					return err
				}
				toc.HasFile = true
			}
		case true:
			entries, err := readDirPaths(fs, path)
			if err != nil {
				return err
			}

			dir := &dirInfo{
				Path:    path,
				Name:    pathpkg.Base(path),
				ModTime: fi.ModTime().UTC(),
				Entries: entries,
			}

			toc.dirs = append(toc.dirs, dir)

			// Write _vfsgen_dirInfo.
			err = t.ExecuteTemplate(f, "DirInfo", dir)
			if err != nil {
				return err
			}
		}

		return nil
	}

	err := vfsutil.WalkFiles(fs, "/", walkFn)
	if err != nil {
		return err
	}

	return nil
}