Creating, listing, copying, moving and removing directories.
import fs.dir
The fs.dir package covers everything you do with directories: create them, list them, walk a tree, measure it, copy, move and delete it. It is built on the folder functions of os and adds two things: when a function fails it records the detail (an IOError with the operation and the path) in os.error, and Move works across disks. For files use fs, and to build the paths fs.path.
Listing functions return bare names; Walk returns full paths. Functions that change the disk return 0 or -1.
What people get wrong:
•
Using Exists for files. Here it is true only for a directory; for files use fs.Exists.
•
Expecting Copy and Move to refuse an existing target. Both merge into it: files with the same name are replaced and other files stay.
•
Pointing RemoveAll, Walk, Size or Copy at a tree with symbolic links. They follow a link to a folder as if it were part of the tree, so RemoveAll deletes the contents of the link's target and a link loop never ends.
Create a project layout
MkdirAll creates every missing parent and succeeds when the folder is already there, so it is the safe choice for setting up a layout that may partly exist. List, ListDirs and ListFiles return bare names, not full paths, in whatever order the file system keeps them, and that order differs between systems. Sort them with sort.Sort before you show or compare them.
fs-dir-guide-skeleton.salam
import fs.dir
import fs
import sort
funcmain:
each d in ["shop/src/models", "shop/src/views", "shop/tests", "shop/docs"]:
dir.MkdirAll(d)
end
fs.WriteText("shop/main.salam", "func main:\nend\n")
fs.WriteText("shop/README.md", "# Shop\n")
fs.WriteText("shop/src/models/order.salam", "")
top := dir.ListDirs("shop")
sort.Sort(top)
println"folders:", top
files := dir.ListFiles("shop")
sort.Sort(files)
println"files: ", files
println"src has", dir.ListDirs("shop/src").Len(), "folders"
dir.RemoveAll("shop")
end
Walk returns the path of every file below a directory, already joined to the directory you passed in, so each one can go straight to an fs function. Directories themselves are not in the list, and like the listing functions it has no fixed order. This example counts files by extension and adds up their sizes, which is what Size does in one call.
fs-dir-guide-walk.salam
import fs.dir
import fs
import fs.path
funcmain:
dir.MkdirAll("site/pages/blog")
dir.MkdirAll("site/assets/img")
fs.WriteText("site/pages/index.html", "<h1>Home</h1>")
fs.WriteText("site/pages/blog/first.html", "<p>First post</p>")
fs.WriteText("site/assets/style.css", "body { margin: 0 }")
fs.WriteText("site/assets/img/logo.svg", "<svg/>")
counts := HashMap {} asHashMap<str, int>
mut bytes := 0asi64each p in dir.Walk("site"):
ext := path.Ext(p)
if counts.Has(ext): counts.Put(ext, counts.Get(ext) + 1) else:
counts.Put(ext, 1)
end
bytes += fs.Size(p)
endeach ext in [".html", ".css", ".svg"]:
println ext, counts.Get(ext)
endprintln"total:", bytes, "bytes, same as dir.Size:", bytes == dir.Size("site")
dir.RemoveAll("site")
end
Output
.html 2
.css 1
.svg 1
total: 54 bytes, same as dir.Size: true
Keep rotating backups
Copy copies a tree with everything in it (file contents only; permissions are not kept), and Move renames one, falling back to copy and delete when the rename fails, for example because the target is on another disk. Together they make a simple rotation: drop the oldest backup, shift the others up by one, and copy the live folder to .bak1. The oldest is removed first so that its name is free before anything moves onto it.
fs-dir-guide-backup.salam
import fs.dir
import fs
importstrfuncbackup(src: str, keep: int):
dir.RemoveAll(src.Concat(".bak").Concat(str.FromInt(keep)))
mut n := keep - 1until n >= 1:
from := src.Concat(".bak").Concat(str.FromInt(n))
if dir.Exists(from): dir.Move(from, src.Concat(".bak").Concat(str.FromInt(n + 1))) end
n--
end
dir.Copy(src, src.Concat(".bak1"))
endfuncmain:
dir.MkdirAll("notes")
repeat1to4in day:
fs.WriteText("notes/today.txt", "day ".Concat(str.FromInt(day)))
backup("notes", 3)
endrepeat1to3in n:
name := "notes.bak".Concat(str.FromInt(n))
println name, fs.ReadText(name.Concat("/today.txt"))
endprintln"notes.bak4 exists:", dir.Exists("notes.bak4")
each d in ["notes", "notes.bak1", "notes.bak2", "notes.bak3"]: dir.RemoveAll(d) endend
Output
notes.bak1 day 4
notes.bak2 day 3
notes.bak3 day 2
notes.bak4 exists: false
Errors and pitfalls
Every function that changes the disk returns 0 or -1, and on failure it leaves a short message in os.error. The message names the operation that failed, not the reason, so when the reason matters, check the likely causes yourself: the folder already exists, its parent is missing, or it is not empty.
fs-dir-guide-errors.salam
import fs.dir
import fs
import os.error
funcreport(what: str, rc: int):
if rc == 0:
println what, "ok"else:
println what, "failed:", error.LastMessage()
endendfuncmain:
report("mkdir data", dir.Mkdir("data"))
report("mkdir data again", dir.Mkdir("data"))
report("mkdir a/b/c", dir.Mkdir("a/b/c"))
fs.WriteText("data/x.txt", "x")
report("remove data", dir.Remove("data"))
println"data/x.txt is a dir:", dir.Exists("data/x.txt"), "is a file:", fs.Exists("data/x.txt")
report("remove all data", dir.RemoveAll("data"))
println"listing a missing dir:", dir.List("data").Len()
end
Output
mkdir data ok
mkdir data again failed: mkdir failed
mkdir a/b/c failed: mkdir failed
remove data failed: rmdir failed
data/x.txt is a dir: false is a file: true
remove all data ok
listing a missing dir: 0
•
Mkdir fails when the folder exists or its parent is missing; MkdirAll handles both.
•
Remove only removes an empty folder. RemoveAll deletes everything inside without asking, so build its argument carefully and never pass it a path straight from user input; path.IsSafe checks that a path stays inside a base folder.
•
Exists is false for a file, and List on a missing folder gives an empty vector rather than an error.
Removes a directory with everything in it; a missing path counts as success. It follows symbolic links to folders and deletes what is inside their targets.
The example for this item is shown with the ones above: fs-dir-List.salam
The paths of every file in a directory and its subdirectories, each starting with the path you passed; directories are not listed. The same as os.Walk.
The example for this item is shown with the ones above: fs-dir-List.salam
Moves a directory. When the rename fails, across two disks for instance, it copies into the target (merging with an existing one) and then removes the original.
The example for this item is shown with the ones above: fs-dir-List.salam
The files and folders that match a pattern such as src/**/*.c or /etc/*.conf, sorted. Every part between slashes is matched against the entries of the folder before it; ** as a whole part stands for any number of folders, including none. Hidden files are matched like others. No match gives an empty vector, which the caller frees.
fs-dir-Glob.salam
import fs.dir
import fs
import os
import os.temp
funcshow(title: str, items: Vector<str>, root: str):
println title
each item in items:
println" " + item.Substr(root.Len() + 1, item.Len() - root.Len() - 1)
end
items.Free()
endfuncmain:
root := temp.Directory()
defer temp.RemoveDir(root)
os.MkdirAll(root + "/src/deep")
each name in ["src/a.c", "src/b.h", "src/deep/c.c", "top.c"]:
fs.WriteText(root + "/" + name, "x")
endshow("src/*.c", dir.Glob(root + "/src/*.c"), root)
show("**/*.c", dir.Glob(root + "/**/*.c"), root)
show("walk *.h", dir.WalkMatch(root, "*.h"), root)
show("walk src/**/*.c", dir.WalkMatch(root, "src/**/*.c"), root)
end
Output
src/*.c
src/a.c
**/*.c
src/a.c
src/deep/c.c
top.c
walk *.h
src/b.h
walk src/**/*.c
src/a.c
src/deep/c.c
Every file below root, at any depth, whose path relative to root matches the pattern, sorted and joined to root. A pattern without a slash (*.c) is matched against the file name alone. The caller frees the vector.
The example for this item is shown with the ones above: fs-dir-Glob.salam