Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 53 additions & 63 deletions internal/vm/file.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package vm

import (
"math"
"os"
"os/user"
"path" // always '/'-separated, as Ruby's File is — not path/filepath
Expand Down Expand Up @@ -256,17 +257,20 @@ func (vm *VM) registerFile() {
}
return object.IntValue(fi.Size())
})
// File.mtime returns the file's last-modification Time (whole-second
// resolution, matching the Time class's granularity). A missing file raises
// Errno::ENOENT, as in MRI.
def("mtime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value {
p := pathArg(vm, args[0])
fi, err := os.Stat(p)
if err != nil {
raise("Errno::ENOENT", "No such file or directory @ rb_file_s_stat - %s", p)
}
return unixTime(fi.ModTime().Unix())
})
// File.mtime / .atime / .ctime / .birthtime read the stat struct, as MRI's
// rb_file_s_mtime & co. do, with the nanoseconds and the local zone
// (statTime). atime and ctime used to answer the MODIFICATION time, on the
// belief that Go's portable stat exposes nothing else; statTimestamps has
// read the real st_atime / st_ctime off Sys() for File::Stat all along (#705).
for _, name := range []string{"mtime", "atime", "ctime", "birthtime"} {
def(name, func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value {
checkArgc(args, 1, name)
p := pathArg(vm, args[0])
return statForTime(p, "rb_file_s_"+name).timeOf(name)
})
// rb_define_singleton_method(rb_cFile, "mtime", rb_file_s_mtime, 1).
cFile.smethods[name].argc = declareArgc(1)
}
delete := func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value {
for _, a := range args {
p := pathArg(vm, a)
Expand Down Expand Up @@ -335,7 +339,10 @@ func (vm *VM) registerFile() {
return object.IntValue(int64(len(paths)))
})
def("utime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value {
at, mt := timeArgUnixOrNow(args[0]), timeArgUnixOrNow(args[1])
if len(args) < 2 {
raise("ArgumentError", "wrong number of arguments (given %d, expected 2+)", len(args))
}
at, mt := vm.utimeArgs(args[0], args[1])
paths := args[2:]
for _, a := range paths {
p := pathArg(vm, a)
Expand All @@ -353,7 +360,7 @@ func (vm *VM) registerFile() {
if len(args) < 2 {
raise("ArgumentError", "wrong number of arguments (given %d, expected 2+)", len(args))
}
at, mt := timeArgUnixOrNow(args[0]), timeArgUnixOrNow(args[1])
at, mt := vm.utimeArgs(args[0], args[1])
paths := args[2:]
for _, a := range paths {
p := pathArg(vm, a)
Expand Down Expand Up @@ -519,31 +526,6 @@ func (vm *VM) registerFile() {
return object.Bool(err1 == nil && err2 == nil && os.SameFile(fi1, fi2))
})

// atime / ctime return the file's access / change Time (whole-second, like
// mtime — Go's portable stat exposes only ModTime, so both report it). A missing
// file raises Errno::ENOENT, as MRI does.
modTimeOf := func(vm *VM, args []object.Value) object.Value {
p := pathArg(vm, args[0])
fi, err := os.Stat(p)
if err != nil {
raise("Errno::ENOENT", "No such file or directory @ rb_file_s_stat - %s", p)
}
return unixTime(fi.ModTime().Unix())
}
def("atime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { return modTimeOf(vm, args) })
def("ctime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { return modTimeOf(vm, args) })
// birthtime: unavailable through Go's portable stat surface (and on Linux
// without statx), so — matching MRI on unsupported platforms — it raises
// Errno::ENOENT for a missing path and NotImplementedError otherwise.
def("birthtime", func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value {
p := pathArg(vm, args[0])
if _, err := os.Stat(p); err != nil {
raise("Errno::ENOENT", "No such file or directory @ rb_file_s_birthtime - %s", p)
}
raise("NotImplementedError", "birthtime() function is unimplemented")
return object.NilV
})

// link / symlink create a hard / symbolic link and return 0; an existing target
// raises Errno::EEXIST, a missing source directory Errno::ENOENT (MRI). Both
// require exactly two path arguments.
Expand Down Expand Up @@ -683,9 +665,7 @@ func (vm *VM) num2mode(v object.Value) int64 {
// File.chown as a no-op, so the Windows build returns nil.
var (
fileChmod = os.Chmod
fileChtimes = func(p string, atime, mtime int64) error {
return osChtimes(p, atime, mtime)
}
fileChtimes = os.Chtimes
)

// rubyBasename returns the last component of a '/'-separated path, matching Ruby's
Expand Down Expand Up @@ -1037,13 +1017,6 @@ func expandTildePath(p string) string {
// concurrently-running tests).
var setUmask = osUmask

// osChtimes sets the access and modification times of path from whole-second
// Unix timestamps, via os.Chtimes. It is wrapped (rather than used directly) so
// the seam in fileChtimes takes int64 seconds, matching utime's Time arguments.
func osChtimes(p string, atime, mtime int64) error {
return os.Chtimes(p, stdtime.Unix(atime, 0), stdtime.Unix(mtime, 0))
}

// chownID converts a File.chown id argument to the int the os layer expects: a
// nil id means "leave unchanged" (-1, as POSIX chown interprets it), any other
// value is coerced through intArg.
Expand All @@ -1054,23 +1027,40 @@ func chownID(v object.Value) int {
return clampInt(intArg(v))
}

// timeArgUnix marshals a File.utime time argument (a Time, or an Integer/Float
// seconds-since-epoch) to a whole number of Unix seconds.
func timeArgUnix(v object.Value) int64 {
if t, ok := v.(*Time); ok {
return t.t.Unix()
}
return int64(numFloat(v))
// utimeArg marshals a File.utime time argument (a Time, or an Integer/Float
// seconds-since-epoch) to the instant it names, nanoseconds included, as
// rb_time_timespec does. It used to return whole seconds, so File.utime
// dropped the sub-second part MRI writes (#705).
func (vm *VM) utimeArg(v object.Value) stdtime.Time {
var f float64
switch n := v.(type) {
case *Time:
return n.t
case object.Integer:
return stdtime.Unix(int64(n), 0)
case object.Float:
f = float64(n)
case *object.Rational:
f, _ = n.R.Float64()
default:
raise("TypeError", "can't convert %s into time", vm.objClassName(v))
}
sec := math.Floor(f)
return stdtime.Unix(int64(sec), int64(math.Round((f-sec)*1e9)))
}

// timeArgUnixOrNow is timeArgUnix with MRI's nil handling for File.utime /
// File.lutime: a nil atime/mtime means "use the current time" (file.c
// utime_internal leaves the timespec NULL, which utimensat reads as UTIME_NOW).
func timeArgUnixOrNow(v object.Value) int64 {
if v == object.NilV {
return stdtime.Now().Unix()
}
return timeArgUnix(v)
// utimeArgs is file.c utime_args_init for File.utime / File.lutime: only when
// BOTH times are nil is the timespec left NULL (utimensat's "now"); otherwise
// each goes through rb_time_timespec, atime first, so a lone nil raises
// "can't convert NilClass into time". It used to read each nil as "now" on its
// own, which MRI 4.0.10 refuses.
func (vm *VM) utimeArgs(atime, mtime object.Value) (stdtime.Time, stdtime.Time) {
if atime == object.NilV && mtime == object.NilV {
now := stdtime.Now()
return now, now
}
at := vm.utimeArg(atime)
return at, vm.utimeArg(mtime)
}

// registerErrnoClasses installs the Errno::Exxx hierarchy under the Errno module
Expand Down
5 changes: 3 additions & 2 deletions internal/vm/file_lutime_chroot_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"runtime"
"syscall"
"testing"
"time"
)

// origChrootFn / origLutimesFn capture the platform seams so each test can
Expand Down Expand Up @@ -53,7 +54,7 @@ func TestFileLutime(t *testing.T) {
if got := runFS(t, `p (File.mtime("`+f+`").to_i == 1000000001)`); got != "true\n" {
t.Errorf("lutime mtime: got %q want true", got)
}
// nil atime/mtime means the current time (timeArgUnixOrNow nil branch).
// nil atime/mtime means the current time (utimeArgOrNow nil branch).
if got := runFS(t, `File.lutime(nil, nil, "`+f+`"); p ((Time.now.to_i - File.mtime("`+f+`").to_i).abs < 5)`); got != "true\n" {
t.Errorf("lutime nil: got %q want true", got)
}
Expand All @@ -65,7 +66,7 @@ func TestFileLutime(t *testing.T) {
}

// Error branch: a failing seam maps to Errno::ENOENT.
lutimesFn = func(string, int64, int64) error { return os.ErrNotExist }
lutimesFn = func(string, time.Time, time.Time) error { return os.ErrNotExist }
if got := runFSErr(t, `File.lutime(0, 0, "x")`); got != "Errno::ENOENT" {
t.Errorf("lutime err: got %q want Errno::ENOENT", got)
}
Expand Down
15 changes: 12 additions & 3 deletions internal/vm/file_ops_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"testing"
"time"
)

// TestFileMetaOps covers File.chmod/chown/lchown/utime/umask and the access
Expand All @@ -28,10 +29,18 @@ func TestFileMetaOps(t *testing.T) {
// chmod returns the number of paths; multiple paths sum.
{`p File.chmod(0o600, "` + f + `")`, "1\n"},
// utime returns the count; accepts a Time, and Integer/Float/Rational
// second counts (each coerced to whole Unix seconds).
// second counts (the fractions kept to the nanosecond).
{`p File.utime(Time.now, Time.now, "` + f + `")`, "1\n"},
{`p File.utime(0, 0, "` + f + `")`, "1\n"},
{`p File.utime(Rational(3, 2), 2.0, "` + f + `")`, "1\n"},
// Measured on MRI 4.0.10 (file.c utime_args_init, time.c time_timespec):
// only a nil PAIR means "now"; a lone nil is converted like any other
// argument, atime first, and the message names the argument's class.
{`begin; File.utime(nil, 5, "` + f + `"); rescue TypeError => e; puts e.message; end`, "can't convert NilClass into time\n"},
{`begin; File.utime(Object.new, nil, "` + f + `"); rescue TypeError => e; puts e.message; end`, "can't convert Object into time\n"},
{`begin; File.lutime(5, "x", "` + f + `"); rescue TypeError => e; puts e.message; end`, "can't convert String into time\n"},
{`p File.utime(1, 2)`, "0\n"},
{`begin; File.utime(1); rescue ArgumentError => e; puts e.message; end`, "wrong number of arguments (given 1, expected 2+)\n"},
// chown with nil ids leaves them unchanged and still reports the count.
{`p File.chown(nil, nil, "` + f + `")`, "1\n"},
{`p File.lchown(nil, nil, "` + f + `")`, "1\n"},
Expand All @@ -49,7 +58,7 @@ func TestFileMetaOps(t *testing.T) {
t.Errorf("src=%q got=%q want=%q", c.src, got, c.want)
}
}
// A non-numeric utime second count is a TypeError (numFloat rejects it).
// A non-numeric utime second count is a TypeError (utimeArg rejects it).
if got := runFSErr(t, `File.utime(:bad, 0, "`+f+`")`); got != "TypeError" {
t.Errorf("utime(:bad): got %q want TypeError", got)
}
Expand All @@ -62,7 +71,7 @@ func TestFileMetaOpsErrors(t *testing.T) {
defer restoreFileSeams()
failMode := func(string, os.FileMode) error { return os.ErrNotExist }
failOwn := func(string, int, int) error { return os.ErrNotExist }
failTimes := func(string, int64, int64) error { return os.ErrNotExist }
failTimes := func(string, time.Time, time.Time) error { return os.ErrNotExist }

fileChmod = failMode
fileChown = failOwn
Expand Down
Loading
Loading