diff --git a/internal/vm/dir.go b/internal/vm/dir.go index e50e2fe6..5a555787 100644 --- a/internal/vm/dir.go +++ b/internal/vm/dir.go @@ -1,9 +1,11 @@ package vm import ( + "errors" "os" "os/user" "strings" + "syscall" "github.com/go-embedded-ruby/ruby/internal/object" ) @@ -19,10 +21,17 @@ func (vm *VM) registerDir() { // caught the original object. cDir := newClass("Dir", vm.cObject) vm.consts["Dir"] = cDir + // Dir includes Enumerable (its #each yields the entries) so Enumerable's + // map/select/to_a/… work on an open Dir — MRI asserts Dir.include?(Enumerable). + // The Enumerable module is defined by the prelude, which runs AFTER this + // bootstrap registration, so the mix-in is deferred to includeDirEnumerable + // (called post-prelude); doing it here would silently no-op. def := func(name string, fn NativeFn) { cDir.smethods[name] = &Method{name: name, owner: cDir, native: fn} } def("pwd", dirPwd) - def("getwd", dirPwd) + // getwd is a genuine alias of pwd (one shared Method record), so + // Dir.method(:getwd) == Dir.method(:pwd), as MRI's spec checks. + cDir.smethods["getwd"] = cDir.smethods["pwd"] // Dir.home(user=nil): with no argument (or nil) the current user's home, // reading $HOME first and falling back to the passwd database; with a user // name, that user's home from the passwd database, raising ArgumentError when @@ -38,17 +47,17 @@ func (vm *VM) registerDir() { } return object.NewString(toSlash(dirHomeStr())) }) - def("entries", func(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - names := dirNames(strArg(args[0])) + def("entries", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + names := dirNames(vm.filePathArg(args[0])) elems := []object.Value{object.NewString("."), object.NewString("..")} for _, n := range names { elems = append(elems, object.NewString(n)) } return object.NewArrayFromSlice(elems) }) - def("children", func(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + def("children", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { var elems []object.Value - for _, n := range dirNames(strArg(args[0])) { + for _, n := range dirNames(vm.filePathArg(args[0])) { elems = append(elems, object.NewString(n)) } return object.NewArrayFromSlice(elems) @@ -78,8 +87,8 @@ func (vm *VM) registerDir() { }) def("exist?", dirExist) def("exists?", dirExist) - def("empty?", func(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - p := strArg(args[0]) + def("empty?", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + p := vm.filePathArg(args[0]) fi, err := os.Stat(p) if err != nil { raise("Errno::ENOENT", "No such file or directory @ dir_s_empty_p - %s", p) @@ -106,20 +115,29 @@ func (vm *VM) registerDir() { } return object.IntValue(0) }) - rm := func(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - p := strArg(args[0]) + rm := func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + p := vm.filePathArg(args[0]) + // MRI's dir_s_rmdir enforces rmdir(2) semantics rather than os.Remove's + // unlink-or-rmdir: a non-directory must be Errno::ENOTDIR, never silently + // unlinked. lstat detects that case; every other failure is left to + // os.Remove and classified by raiseRmdirErr (EACCES / ENOTEMPTY / ENOENT). + if fi, err := os.Lstat(p); err == nil && !fi.IsDir() { + raise("Errno::ENOTDIR", "Not a directory @ dir_s_rmdir - %s", p) + } if err := os.Remove(p); err != nil { - raise("Errno::ENOENT", "No such file or directory @ dir_s_rmdir - %s", p) + raiseRmdirErr(err, p) } return object.IntValue(0) } - def("rmdir", rm) def("delete", rm) - def("unlink", rm) + // rmdir and unlink are genuine aliases of delete (shared Method records), so + // Dir.method(:rmdir) == Dir.method(:delete), as MRI's specs check. + cDir.smethods["rmdir"] = cDir.smethods["delete"] + cDir.smethods["unlink"] = cDir.smethods["delete"] def("chdir", func(vm *VM, _ object.Value, args []object.Value, blk *Proc) object.Value { var target string if len(args) > 0 { - target = strArg(args[0]) + target = vm.filePathArg(args[0]) } else { target = dirHomeStr() } @@ -133,16 +151,27 @@ func (vm *VM) registerDir() { } return object.IntValue(0) }) + // Dir.each_child(path) yields each child name (no "." / ".."); Dir.foreach(path) + // yields every entry including "." and "..". Both return nil after a block and, + // with no block, an Enumerator over the snapshot names (MRI dir.c) — whose #size + // is nil, and whose iteration re-yields the names. The block-less form must not + // dereference a nil block (the previous version crashed there). def("each_child", func(vm *VM, _ object.Value, args []object.Value, blk *Proc) object.Value { - for _, n := range dirNames(strArg(args[0])) { + names := dirNames(vm.filePathArg(args[0])) + if blk == nil { + return dirEnumerator(names) + } + for _, n := range names { vm.callBlock(blk, []object.Value{object.NewString(n)}) } return object.NilV }) def("foreach", func(vm *VM, _ object.Value, args []object.Value, blk *Proc) object.Value { - vm.callBlock(blk, []object.Value{object.NewString(".")}) - vm.callBlock(blk, []object.Value{object.NewString("..")}) - for _, n := range dirNames(strArg(args[0])) { + names := append([]string{".", ".."}, dirNames(vm.filePathArg(args[0]))...) + if blk == nil { + return dirEnumerator(names) + } + for _, n := range names { vm.callBlock(blk, []object.Value{object.NewString(n)}) } return object.NilV @@ -255,7 +284,9 @@ func (vm *VM) registerDirInstance(cDir *RClass) { dir := self(v) checkOpen(dir) if blk == nil { - return enumFor(dir, "each") + // A block-less #each returns an Enumerator whose #size is nil (MRI does + // not pre-count a directory), backed by the current entry snapshot. + return dirEnumerator(dir.entries) } for _, n := range dir.entries { vm.callBlock(blk, []object.Value{object.NewString(n)}) @@ -267,7 +298,7 @@ func (vm *VM) registerDirInstance(cDir *RClass) { dir := self(v) checkOpen(dir) if blk == nil { - return enumFor(dir, "each_child") + return dirEnumerator(dirChildNames(dir.entries)) } for _, n := range dir.entries { if n == "." || n == ".." { @@ -277,6 +308,36 @@ func (vm *VM) registerDirInstance(cDir *RClass) { } return dir }) + // Dir#children returns the entry names of the open handle minus "." and ".." + // (Ruby 2.5+ dir.c dir_collect_children). It reads the snapshot, so repeated + // calls return the same result regardless of the read cursor. + d("children", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { + dir := self(v) + checkOpen(dir) + names := dirChildNames(dir.entries) + elems := make([]object.Value, len(names)) + for i, n := range names { + elems[i] = object.NewString(n) + } + return object.NewArrayFromSlice(elems) + }) + // Dir#chdir changes the process working directory to the handle's path, + // returning 0 (or the block's value for the block form, which restores the + // previous directory afterwards and — unlike Dir.chdir — yields nil rather + // than the path). Ruby 3.5+ (dir.c dir_chdir0 / fdopendir path). + d("chdir", func(vm *VM, v object.Value, _ []object.Value, blk *Proc) object.Value { + dir := self(v) + checkOpen(dir) + old, _ := os.Getwd() + if err := os.Chdir(dir.path); err != nil { + raise("Errno::ENOENT", "No such file or directory @ dir_chdir - %s", dir.path) + } + if blk != nil { + defer os.Chdir(old) + return vm.callBlock(blk, []object.Value{object.NilV}) + } + return object.IntValue(0) + }) } // osUserHomeDir is a seam over os.UserHomeDir so the no-HOME error path is @@ -329,11 +390,63 @@ func dirPwd(_ *VM, _ object.Value, _ []object.Value, _ *Proc) object.Value { return object.NewString(toSlash(wd)) } -func dirExist(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - fi, err := os.Stat(strArg(args[0])) +// includeDirEnumerable mixes the prelude-defined Enumerable module into Dir. It +// runs post-prelude (registerDir itself runs before the prelude, so the module +// does not exist yet there), driven from registerFileStat which also runs after +// the prelude. Both constants always exist by then, matching the unguarded +// mix-ins elsewhere (see registerActiveSupport / includeMySQLEnumerable). +func (vm *VM) includeDirEnumerable() { + cDir := vm.consts["Dir"].(*RClass) + en := vm.consts["Enumerable"].(*RClass) + cDir.includes = append(cDir.includes, en) +} + +func dirExist(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + fi, err := os.Stat(vm.filePathArg(args[0])) return object.Bool(err == nil && fi.IsDir()) } +// dirEnumerator wraps a snapshot of directory entry names as the block-less +// Enumerator MRI's Dir.foreach / Dir.each_child return: iterating it re-yields +// the names, and its #size is nil (MRI does not pre-count a directory +// enumerator). It is backed by an Array's #each so materialisation is a plain +// array walk rather than a re-entrant directory read. +// dirChildNames returns the entry names with "." and ".." removed — the +// child-name view shared by Dir#children and the block-less Dir#each_child +// enumerator. +func dirChildNames(entries []string) []string { + var out []string + for _, n := range entries { + if n != "." && n != ".." { + out = append(out, n) + } + } + return out +} + +func dirEnumerator(names []string) *Enumerator { + elems := make([]object.Value, len(names)) + for i, n := range names { + elems[i] = object.NewString(n) + } + return enumForSized(object.NewArrayFromSlice(elems), "each", + func(*VM) object.Value { return object.NilV }) +} + +// raiseRmdirErr maps an os.Remove failure on a directory to the MRI errno +// Dir.delete/rmdir raises: a permission failure is Errno::EACCES, a non-empty +// directory Errno::ENOTEMPTY, and anything else Errno::ENOENT. +func raiseRmdirErr(err error, path string) { + switch { + case os.IsPermission(err): + raise("Errno::EACCES", "Permission denied @ dir_s_rmdir - %s", path) + case errors.Is(err, syscall.ENOTEMPTY): + raise("Errno::ENOTEMPTY", "Directory not empty @ dir_s_rmdir - %s", path) + default: + raise("Errno::ENOENT", "No such file or directory @ dir_s_rmdir - %s", path) + } +} + // dirNames returns the directory's entry names (sorted, no "." / ".."), raising // Errno::ENOENT when the path is not a readable directory. func dirNames(p string) []string { diff --git a/internal/vm/file.go b/internal/vm/file.go index 0114d750..32caec07 100644 --- a/internal/vm/file.go +++ b/internal/vm/file.go @@ -1,11 +1,13 @@ package vm import ( + "errors" "os" "os/user" "path" // always '/'-separated, as Ruby's File is — not path/filepath "path/filepath" // OS-native, only for symlink resolution (File.realpath) "strings" + "syscall" stdtime "time" "github.com/go-embedded-ruby/ruby/internal/object" @@ -63,6 +65,9 @@ func (vm *VM) registerFile() { // is the null device. These let path-handling code branch on File::SEPARATOR // etc. without a runtime error. cFile.consts["SEPARATOR"] = object.NewString("/") + // File::Separator is MRI's mixed-case alias of File::SEPARATOR (both "/"); a + // separate String object is fine since the spec only checks its value. + cFile.consts["Separator"] = object.NewString("/") cFile.consts["ALT_SEPARATOR"] = object.NilV cFile.consts["PATH_SEPARATOR"] = object.NewString(":") cFile.consts["NULL"] = object.NewString("/dev/null") @@ -202,10 +207,12 @@ func (vm *VM) registerFile() { }) def("exist?", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + oneArg(args) _, err := os.Stat(pathArg(vm, args[0])) return object.Bool(err == nil) }) def("file?", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + oneArg(args) fi, err := os.Stat(pathArg(vm, args[0])) return object.Bool(err == nil && fi.Mode().IsRegular()) }) @@ -220,6 +227,21 @@ func (vm *VM) registerFile() { fi, err := os.Lstat(pathArg(vm, args[0])) return object.Bool(err == nil && fi.Mode()&os.ModeSymlink != 0) }) + // File.ftype(path) returns the MRI file-type string ("file"/"directory"/ + // "link"/"characterSpecial"/…). Like MRI it lstats the path (so a symlink is + // "link", not its target), takes exactly one #to_path argument, and raises + // Errno::ENOENT for a missing path (ruby/ruby v3_4_0 file.c rb_file_s_ftype). + def("ftype", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + if len(args) != 1 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 1)", len(args)) + } + p := vm.filePathArg(args[0]) + fi, err := osLstat(p) + if err != nil { + raise("Errno::ENOENT", "No such file or directory @ rb_file_s_ftype - %s", p) + } + return object.NewString(newFileStat(fi, p).ftype()) + }) // File.realpath returns the canonical absolute path with every symlink // resolved; the path (and each component) must exist, otherwise — as in MRI — // Errno::ENOENT is raised. An optional second argument is the base directory @@ -228,7 +250,7 @@ func (vm *VM) registerFile() { p := vm.fileExpand(vm.filePathArg(args[0]), args[1:], true) resolved, err := filepath.EvalSymlinks(p) if err != nil { - raise("Errno::ENOENT", "No such file or directory @ realpath_rec - %s", p) + raiseRealpathErr(p) } return object.NewString(toSlash(resolved)) }) @@ -264,13 +286,17 @@ func (vm *VM) registerFile() { return object.IntValue(int64(len(args))) } def("delete", delete) - def("unlink", delete) + // unlink is a genuine alias of delete (one shared Method record), so + // File.method(:unlink) == File.method(:delete), as MRI's spec checks. + cFile.smethods["unlink"] = cFile.smethods["delete"] // rename(old, new) atomically moves a file, returning 0 (MRI). Puppet's // FileSystem#replace_file renames its written temp file over the target, so // state.yaml / last_run_summary.yaml are written atomically. def("rename", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - from, to := pathArg(vm, args[0]), pathArg(vm, args[1]) + // MRI's rb_file_s_rename checks the two-argument arity before coercing the + // paths, so File.rename("a") raises ArgumentError rather than a TypeError. + from, to := twoPaths(vm, args) if err := os.Rename(from, to); err != nil { raise("Errno::ENOENT", "No such file or directory @ rb_file_s_rename - %s or %s", from, to) } @@ -282,7 +308,7 @@ func (vm *VM) registerFile() { // a leading mode/owner/time argument followed by one or more paths, returning // the count of paths affected (MRI semantics). def("chmod", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - mode := os.FileMode(intArg(args[0]) & 0o7777) + mode := os.FileMode(vm.num2mode(args[0]) & 0o7777) paths := args[1:] for _, a := range paths { p := pathArg(vm, a) @@ -331,13 +357,16 @@ func (vm *VM) registerFile() { // File.umask([mask]) reads (and optionally sets) the process umask, returning // the previous value — the bracket Puppet::Util.withumask uses. With no // argument it reports the current umask without changing it. - def("umask", func(_ *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + def("umask", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + if len(args) > 1 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 0..1)", len(args)) + } if len(args) == 0 { cur := setUmask(0) setUmask(cur) // restore: a no-arg umask is a pure read return object.IntValue(int64(cur)) } - return object.IntValue(int64(setUmask(int(intArg(args[0]))))) + return object.IntValue(int64(setUmask(int(vm.num2mode(args[0]))))) }) // Access predicates: readable?/writable?/executable? for the current effective // user, plus executable_real? — thin File.stat-and-test wrappers that return @@ -387,7 +416,9 @@ func (vm *VM) registerFile() { return object.Bool(err == nil && fi.Size() == 0) } def("zero?", zero) - def("empty?", zero) + // empty? is a genuine alias of zero? (shared Method record), matching MRI's + // File.method(:zero?) == File.method(:empty?). + cFile.smethods["empty?"] = cFile.smethods["zero?"] // Type predicates that delegate to a following stat and degrade to false for a // missing path (MRI's File.pipe?/socket?/…). statTest wraps the stat-and-test. @@ -437,6 +468,9 @@ func (vm *VM) registerFile() { // identical? reports whether two paths refer to the same file (same device and // inode), following symlinks; false when either path is missing. def("identical?", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + if len(args) != 2 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 2)", len(args)) + } fi1, err1 := os.Stat(pathArg(vm, args[0])) fi2, err2 := os.Stat(pathArg(vm, args[1])) return object.Bool(err1 == nil && err2 == nil && os.SameFile(fi1, fi2)) @@ -502,6 +536,11 @@ func (vm *VM) registerFile() { def("truncate", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { p := pathArg(vm, args[0]) if err := os.Truncate(p, intArg(args[1])); err != nil { + // A negative (invalid) length is Errno::EINVAL; a missing path is + // Errno::ENOENT — matching truncate(2) and MRI's rb_file_s_truncate. + if errors.Is(err, syscall.EINVAL) { + raise("Errno::EINVAL", "Invalid argument @ rb_file_s_truncate - %s", p) + } raise("Errno::ENOENT", "No such file or directory @ rb_file_s_truncate - %s", p) } return object.IntValue(0) @@ -543,9 +582,15 @@ func raiseLinkErr(err error, marker, src string) { // parent directory is resolved and the leaf re-joined. A missing parent raises // Errno::ENOENT. func realdirpath(p string) string { - if resolved, err := filepath.EvalSymlinks(filepath.FromSlash(p)); err == nil { + resolved, err := filepath.EvalSymlinks(filepath.FromSlash(p)) + if err == nil { return toSlash(resolved) } + // A symlink loop is Errno::ELOOP even though realdirpath tolerates an absent + // leaf — the loop is a hard resolution failure, not a missing final component. + if isSymlinkLoop(p) { + raise("Errno::ELOOP", "Too many levels of symbolic links @ realpath_rec - %s", p) + } dir, base := rubyDirname(p), rubyBasename(p) resolvedDir, err := filepath.EvalSymlinks(filepath.FromSlash(dir)) if err != nil { @@ -554,6 +599,57 @@ func realdirpath(p string) string { return toSlash(filepath.Join(resolvedDir, base)) } +// isSymlinkLoop reports whether resolving p fails with ELOOP (a symlink cycle). +// filepath.EvalSymlinks returns a bare "too many links" error that does NOT wrap +// syscall.ELOOP, so the real errno is recovered by re-stating the path (os.Stat +// follows the link and surfaces the kernel's ELOOP). +func isSymlinkLoop(p string) bool { + _, err := osStat(filepath.FromSlash(p)) + return errors.Is(err, syscall.ELOOP) +} + +// raiseRealpathErr maps a File.realpath EvalSymlinks failure to the MRI errno: a +// symbolic-link loop is Errno::ELOOP, anything else (a missing component) is +// Errno::ENOENT. +func raiseRealpathErr(p string) { + if isSymlinkLoop(p) { + raise("Errno::ELOOP", "Too many levels of symbolic links @ realpath_rec - %s", p) + } + raise("Errno::ENOENT", "No such file or directory @ realpath_rec - %s", p) +} + +// oneArg enforces the single-argument arity MRI's one-path File predicates check +// before touching the filesystem (File.exist?/file?/…), raising the ArgumentError +// MRI raises for any other count. +func oneArg(args []object.Value) { + if len(args) != 1 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 1)", len(args)) + } +} + +// num2mode coerces a File.chmod / File.umask mode argument the way MRI's +// NUM2MODET (rb_num2int) does: an Integer is taken directly, a Bignum that does +// not fit a C long raises RangeError, and any other value is coerced through +// #to_int (so a mock that answers #to_int is accepted rather than a TypeError). +// It is the mode-coercing counterpart of coerceInt, which lacks the Bignum range +// check the chmod/umask specs exercise. +func (vm *VM) num2mode(v object.Value) int64 { + switch n := v.(type) { + case object.Integer: + return int64(n) + case *object.Bignum: + if n.I.IsInt64() { + return n.I.Int64() + } + raise("RangeError", "bignum too big to convert into 'unsigned long'") + } + if vm.respondsTo(v, "to_int") { + return vm.num2mode(vm.send(v, "to_int", nil, nil)) + } + raise("TypeError", "no implicit conversion of %s into Integer", vm.classOf(v).name) + return 0 +} + // fileChmod / fileChown / fileLchown / fileChtimes are seams over the os package // so the error branches are reachable identically on every platform (a test // swaps in a failing stub rather than relying on real OS behaviour, which diff --git a/internal/vm/filestat.go b/internal/vm/filestat.go index af95f05d..467f3669 100644 --- a/internal/vm/filestat.go +++ b/internal/vm/filestat.go @@ -446,6 +446,10 @@ func (vm *VM) registerFileStat() { }} vm.registerFileTest() + + // Dir includes Enumerable — deferred here because registerDir runs before the + // prelude that defines the module, and registerFileStat runs after it. + vm.includeDirEnumerable() } // registerFileTest installs the FileTest module — the predicate surface Puppet diff --git a/internal/vm/wave19_filedir_internal_test.go b/internal/vm/wave19_filedir_internal_test.go new file mode 100644 index 00000000..7d1361c9 --- /dev/null +++ b/internal/vm/wave19_filedir_internal_test.go @@ -0,0 +1,521 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "bytes" + "math/big" + "os" + "path/filepath" + "runtime" + "strconv" + "syscall" + "testing" + + "github.com/go-embedded-ruby/ruby/internal/object" +) + +// rq renders an OS path as a Ruby double-quoted string literal (paths here are +// plain ASCII temp dirs, so Go's quoting matches Ruby's). +func rq(p string) string { return strconv.Quote(slash(p)) } + +// TestRaiseRmdirErrClassification covers every branch of raiseRmdirErr with +// synthetic os errors (independent of the running user's privileges). It reuses +// the shared expectRaise helper, which returns the raised RubyError's class. +func TestRaiseRmdirErrClassification(t *testing.T) { + cases := []struct { + errno syscall.Errno + want string + }{ + {syscall.EACCES, "Errno::EACCES"}, + {syscall.ENOTEMPTY, "Errno::ENOTEMPTY"}, + {syscall.ENOENT, "Errno::ENOENT"}, + } + for _, c := range cases { + err := &os.PathError{Op: "remove", Path: "x", Err: c.errno} + if got := expectRaise(t, func() { raiseRmdirErr(err, "x") }); got != c.want { + t.Errorf("raiseRmdirErr(%v) raised %q, want %q", c.errno, got, c.want) + } + } +} + +// TestRaiseRealpathErrClassification covers raiseRealpathErr and isSymlinkLoop by +// stubbing the osStat seam to surface a synthetic ELOOP / ENOENT, so both +// branches are exercised without creating a real symlink cycle. +func TestRaiseRealpathErrClassification(t *testing.T) { + old := osStat + defer func() { osStat = old }() + + osStat = func(string) (os.FileInfo, error) { return nil, &os.PathError{Err: syscall.ELOOP} } + if got := expectRaise(t, func() { raiseRealpathErr("x") }); got != "Errno::ELOOP" { + t.Errorf("realpath loop raised %q, want Errno::ELOOP", got) + } + osStat = func(string) (os.FileInfo, error) { return nil, &os.PathError{Err: syscall.ENOENT} } + if got := expectRaise(t, func() { raiseRealpathErr("x") }); got != "Errno::ENOENT" { + t.Errorf("realpath missing raised %q, want Errno::ENOENT", got) + } +} + +// --- File.ftype ----------------------------------------------------------- + +// TestFileFtype covers File.ftype's arity guard, ENOENT branch and the type +// strings for a regular file, a directory and a symlink, against MRI 4.0.5. +func TestFileFtype(t *testing.T) { + dir := t.TempDir() + reg := filepath.Join(dir, "reg") + if err := os.WriteFile(reg, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if got := runFS(t, `p File.ftype(`+rq(reg)+`)`); got != "\"file\"\n" { + t.Errorf("ftype(file) = %q", got) + } + if got := runFS(t, `p File.ftype(`+rq(dir)+`)`); got != "\"directory\"\n" { + t.Errorf("ftype(dir) = %q", got) + } + // #to_path argument is accepted (rb_get_path). + if got := runFS(t, `class P;def to_path;`+rq(reg)+`;end;end; p File.ftype(P.new)`); got != "\"file\"\n" { + t.Errorf("ftype(to_path) = %q", got) + } + // Arity: zero and two arguments both raise ArgumentError. + if got := runFSErr(t, `File.ftype`); got != "ArgumentError" { + t.Errorf("ftype() err = %q", got) + } + if got := runFSErr(t, `File.ftype("a","b")`); got != "ArgumentError" { + t.Errorf("ftype(2) err = %q", got) + } + // Missing path raises Errno::ENOENT. + if got := runFSErr(t, `File.ftype(`+rq(filepath.Join(dir, "nope"))+`)`); got != "Errno::ENOENT" { + t.Errorf("ftype(missing) err = %q", got) + } + if runtime.GOOS == "windows" { + return + } + link := filepath.Join(dir, "lnk") + if err := os.Symlink(reg, link); err != nil { + t.Skipf("symlink unsupported: %v", err) + } + if got := runFS(t, `p File.ftype(`+rq(link)+`)`); got != "\"link\"\n" { + t.Errorf("ftype(symlink) = %q", got) + } +} + +// --- File::Separator + aliases ------------------------------------------- + +// TestFileSeparatorAndAliases covers the File::Separator constant and the +// shared-Method aliases (File.unlink==delete, File.empty?==zero?), matching MRI. +func TestFileSeparatorAndAliases(t *testing.T) { + cases := []struct{ src, want string }{ + {`p File::Separator`, "\"/\"\n"}, + {`p File.method(:unlink) == File.method(:delete)`, "true\n"}, + {`p File.method(:empty?) == File.method(:zero?)`, "true\n"}, + } + for _, c := range cases { + if got := runFS(t, c.src); got != c.want { + t.Errorf("%s = %q, want %q", c.src, got, c.want) + } + } +} + +// --- num2mode (File.chmod / File.umask coercion) ------------------------- + +// TestNum2ModeBranches covers every path of num2mode: a plain Integer, a Bignum +// that fits a long, a Bignum that overflows (RangeError), a #to_int coercion and +// a value with no integer conversion (TypeError). +func TestNum2ModeBranches(t *testing.T) { + dir := t.TempDir() + f := filepath.Join(dir, "m") + if err := os.WriteFile(f, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + // Integer path: File.chmod returns the count of paths (1). + if got := runFS(t, `p File.chmod(0o600, `+rq(f)+`)`); got != "1\n" { + t.Errorf("chmod(int) = %q", got) + } + // #to_int path. + if got := runFS(t, `class TI;def to_int;0o644;end;end; p File.chmod(TI.new, `+rq(f)+`)`); got != "1\n" { + t.Errorf("chmod(to_int) = %q", got) + } + // Bignum that overflows a long -> RangeError. + if got := runFSErr(t, `File.chmod(2**64, `+rq(f)+`)`); got != "RangeError" { + t.Errorf("chmod(bignum) err = %q", got) + } + // No integer conversion -> TypeError. + if got := runFSErr(t, `File.chmod(:sym, `+rq(f)+`)`); got != "TypeError" { + t.Errorf("chmod(sym) err = %q", got) + } + // Bignum that DOES fit a long: exercised directly (a fitting Bignum is hard to + // obtain from Ruby source, which normalises to a Fixnum). + vm := New(&bytes.Buffer{}) + if got := vm.num2mode(&object.Bignum{I: big.NewInt(0o600)}); got != 0o600 { + t.Errorf("num2mode(fitting bignum) = %o, want 600", got) + } +} + +// TestFileUmaskArityAndCoerce covers File.umask's arity guard (>1 argument) and +// its argument-coercing branch, driven through the setUmask seam so the process +// umask is not perturbed. +func TestFileUmaskArityAndCoerce(t *testing.T) { + if got := runFSErr(t, `File.umask(1, 2)`); got != "ArgumentError" { + t.Errorf("umask(1,2) err = %q", got) + } + old := setUmask + var set int = -1 + setUmask = func(m int) int { set = m; return 0o22 } + defer func() { setUmask = old }() + if got := runFS(t, `p File.umask(0o27)`); got != "18\n" { // returns the previous (0o22 == 18) + t.Errorf("umask(0o27) = %q", got) + } + if set != 0o27 { + t.Errorf("setUmask received %o, want 27", set) + } +} + +// --- oneArg / identical? / rename arity ---------------------------------- + +// TestPredicateArity covers the single-argument guard (File.exist?/file?) and +// File.identical?'s two-argument guard and success/one-missing branches. +func TestPredicateArity(t *testing.T) { + dir := t.TempDir() + f := filepath.Join(dir, "a") + if err := os.WriteFile(f, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if got := runFS(t, `p File.exist?(`+rq(f)+`)`); got != "true\n" { + t.Errorf("exist?(f) = %q", got) + } + if got := runFS(t, `p File.file?(`+rq(f)+`)`); got != "true\n" { + t.Errorf("file?(f) = %q", got) + } + for _, src := range []string{`File.exist?`, `File.exist?("a","b")`, `File.file?`, `File.file?("a","b")`} { + if got := runFSErr(t, src); got != "ArgumentError" { + t.Errorf("%s err = %q, want ArgumentError", src, got) + } + } + // identical?: success, one-missing (false), and arity. + if got := runFS(t, `p File.identical?(`+rq(f)+`, `+rq(f)+`)`); got != "true\n" { + t.Errorf("identical?(f,f) = %q", got) + } + if got := runFS(t, `p File.identical?(`+rq(f)+`, `+rq(filepath.Join(dir, "nope"))+`)`); got != "false\n" { + t.Errorf("identical?(f,missing) = %q", got) + } + if got := runFSErr(t, `File.identical?(`+rq(f)+`)`); got != "ArgumentError" { + t.Errorf("identical?(1) err = %q", got) + } +} + +// TestFileRenameArity covers File.rename's two-argument arity guard (twoPaths) +// and a successful rename. +func TestFileRenameArity(t *testing.T) { + dir := t.TempDir() + from := filepath.Join(dir, "from") + to := filepath.Join(dir, "to") + if err := os.WriteFile(from, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if got := runFS(t, `p File.rename(`+rq(from)+`, `+rq(to)+`)`); got != "0\n" { + t.Errorf("rename = %q", got) + } + if got := runFSErr(t, `File.rename("only-one")`); got != "ArgumentError" { + t.Errorf("rename(1) err = %q", got) + } +} + +// --- File.truncate -------------------------------------------------------- + +// TestFileTruncateErrno covers File.truncate's success, Errno::EINVAL (negative +// length) and Errno::ENOENT (missing path) branches. +func TestFileTruncateErrno(t *testing.T) { + dir := t.TempDir() + f := filepath.Join(dir, "t") + if err := os.WriteFile(f, []byte("hello"), 0o644); err != nil { + t.Fatal(err) + } + if got := runFS(t, `File.truncate(`+rq(f)+`, 3); p File.size(`+rq(f)+`)`); got != "3\n" { + t.Errorf("truncate(3) size = %q", got) + } + // A negative length is EINVAL on POSIX; Windows reports it differently + // (ENOENT), and the coverage gate runs on the POSIX lanes only. + if runtime.GOOS != "windows" { + if got := runFSErr(t, `File.truncate(`+rq(f)+`, -1)`); got != "Errno::EINVAL" { + t.Errorf("truncate(-1) err = %q", got) + } + } + if got := runFSErr(t, `File.truncate(`+rq(filepath.Join(dir, "nope"))+`, 0)`); got != "Errno::ENOENT" { + t.Errorf("truncate(missing) err = %q", got) + } +} + +// --- realpath / realdirpath ELOOP ---------------------------------------- + +// TestRealpathELOOP covers raiseRealpathErr (Errno::ELOOP for a symlink loop, +// Errno::ENOENT otherwise) and the realdirpath ELOOP / absent-leaf / ENOENT +// branches. +func TestRealpathELOOP(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink loops need POSIX symlinks") + } + dir := t.TempDir() + // realpath of a present file resolves (success branch). + reg := filepath.Join(dir, "reg") + if err := os.WriteFile(reg, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if got := runFS(t, `p File.realpath(`+rq(reg)+`) == File.realpath(`+rq(reg)+`)`); got != "true\n" { + t.Errorf("realpath(reg) = %q", got) + } + // realpath of a missing path -> ENOENT. + if got := runFSErr(t, `File.realpath(`+rq(filepath.Join(dir, "missing"))+`)`); got != "Errno::ENOENT" { + t.Errorf("realpath(missing) err = %q", got) + } + loop := filepath.Join(dir, "loop") + if err := os.Symlink(loop, loop); err != nil { + t.Skipf("symlink unsupported: %v", err) + } + if got := runFSErr(t, `File.realpath(`+rq(loop)+`)`); got != "Errno::ELOOP" { + t.Errorf("realpath(loop) err = %q", got) + } + if got := runFSErr(t, `File.realdirpath(`+rq(loop)+`)`); got != "Errno::ELOOP" { + t.Errorf("realdirpath(loop) err = %q", got) + } + // realdirpath tolerates an absent leaf (success) and raises ENOENT for a + // missing intermediate directory. + if got := runFS(t, `p File.realdirpath(`+rq(filepath.Join(dir, "absent"))+`).end_with?("absent")`); got != "true\n" { + t.Errorf("realdirpath(absent leaf) = %q", got) + } + if got := runFSErr(t, `File.realdirpath("/no/such/deep/leaf")`); got != "Errno::ENOENT" { + t.Errorf("realdirpath(missing dir) err = %q", got) + } +} + +// --- Dir path coercion + Enumerable -------------------------------------- + +// TestDirPathCoercionAndEnumerable covers the rb_get_path coercion of Dir's +// path-taking singletons and the post-prelude Enumerable mix-in. +func TestDirPathCoercionAndEnumerable(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "f"), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + // #to_path arguments are accepted rather than raising a TypeError. + tp := `class P;def to_path;` + rq(dir) + `;end;end;` + if got := runFS(t, tp+`p Dir.entries(P.new).sort`); got != "[\".\", \"..\", \"f\"]\n" { + t.Errorf("Dir.entries(to_path) = %q", got) + } + if got := runFS(t, tp+`p Dir.children(P.new)`); got != "[\"f\"]\n" { + t.Errorf("Dir.children(to_path) = %q", got) + } + if got := runFS(t, tp+`p Dir.exist?(P.new)`); got != "true\n" { + t.Errorf("Dir.exist?(to_path) = %q", got) + } + // Dir includes Enumerable, so Enumerable methods work on an open Dir. + if got := runFS(t, `p Dir.include?(Enumerable)`); got != "true\n" { + t.Errorf("Dir.include?(Enumerable) = %q", got) + } + if got := runFS(t, `p Dir.open(`+rq(dir)+`) { |d| d.to_a.sort }`); got != "[\".\", \"..\", \"f\"]\n" { + t.Errorf("Dir#to_a = %q", got) + } +} + +// TestDirEmptyBranches covers Dir.empty?: an empty directory (true), a +// non-directory (false) and a missing path (Errno::ENOENT). +func TestDirEmptyBranches(t *testing.T) { + dir := t.TempDir() + empty := filepath.Join(dir, "empty") + if err := os.Mkdir(empty, 0o755); err != nil { + t.Fatal(err) + } + f := filepath.Join(dir, "f") + if err := os.WriteFile(f, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if got := runFS(t, `p Dir.empty?(`+rq(empty)+`)`); got != "true\n" { + t.Errorf("empty?(empty) = %q", got) + } + if got := runFS(t, `p Dir.empty?(`+rq(f)+`)`); got != "false\n" { + t.Errorf("empty?(file) = %q", got) + } + if got := runFSErr(t, `Dir.empty?(`+rq(filepath.Join(dir, "nope"))+`)`); got != "Errno::ENOENT" { + t.Errorf("empty?(missing) err = %q", got) + } +} + +// --- Dir.delete errno mapping -------------------------------------------- + +// TestDirDeleteErrno covers raiseRmdirErr and the ENOTDIR guard: a successful +// rmdir, Errno::ENOTDIR (non-directory), Errno::ENOTEMPTY (non-empty) and +// Errno::ENOENT (missing). +func TestDirDeleteErrno(t *testing.T) { + dir := t.TempDir() + empty := filepath.Join(dir, "empty") + if err := os.Mkdir(empty, 0o755); err != nil { + t.Fatal(err) + } + if got := runFS(t, `p Dir.delete(`+rq(empty)+`)`); got != "0\n" { + t.Errorf("delete(empty) = %q", got) + } + f := filepath.Join(dir, "file") + if err := os.WriteFile(f, []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + if got := runFSErr(t, `Dir.delete(`+rq(f)+`)`); got != "Errno::ENOTDIR" { + t.Errorf("delete(file) err = %q", got) + } + nonempty := filepath.Join(dir, "ne") + if err := os.MkdirAll(filepath.Join(nonempty, "child"), 0o755); err != nil { + t.Fatal(err) + } + // A non-empty directory is ENOTEMPTY on POSIX; Windows reports ENOENT here, + // and the coverage gate runs on the POSIX lanes only. + if runtime.GOOS != "windows" { + if got := runFSErr(t, `Dir.delete(`+rq(nonempty)+`)`); got != "Errno::ENOTEMPTY" { + t.Errorf("delete(nonempty) err = %q", got) + } + } + if got := runFSErr(t, `Dir.delete(`+rq(filepath.Join(dir, "nope"))+`)`); got != "Errno::ENOENT" { + t.Errorf("delete(missing) err = %q", got) + } +} + +// TestDirDeleteEACCES covers the Errno::EACCES branch of raiseRmdirErr: rmdir of +// a directory under an unsearchable parent. Skipped on Windows (chmod 0 does not +// remove permissions) and as root (which bypasses the permission check). +func TestDirDeleteEACCES(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX permission semantics only") + } + if os.Geteuid() == 0 { + t.Skip("root bypasses directory permission checks") + } + parent := t.TempDir() + child := filepath.Join(parent, "child") + if err := os.Mkdir(child, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(parent, 0); err != nil { + t.Fatal(err) + } + defer os.Chmod(parent, 0o755) // restore so t.TempDir cleanup succeeds + if got := runFSErr(t, `Dir.delete(`+rq(child)+`)`); got != "Errno::EACCES" { + t.Errorf("delete(noperm child) err = %q, want Errno::EACCES", got) + } +} + +// --- Dir.each_child / Dir.foreach class enumerators ---------------------- + +// TestDirClassIterators covers Dir.each_child / Dir.foreach in both the block +// form and the block-less Enumerator form (whose #size is nil), the previous +// nil-block crash site. +func TestDirClassIterators(t *testing.T) { + dir := t.TempDir() + for _, n := range []string{"a", "b"} { + if err := os.WriteFile(filepath.Join(dir, n), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + } + if got := runFS(t, `a=[]; Dir.each_child(`+rq(dir)+`){|x|a<