How to adjust file modification times?

How do I change the modification time of a file to a prespecified time other than by going something like run(touch ....) ? I know there is a touch command in Julia, but it only sets it to the current time.

Seems like we could use a Julia API for uv_fs_utime, which is probably the function you want to call.

(You could call it yourself with ccall of course, but requires a bit of understanding of how Julia interacts with libuv.)

1 Like

This should work:

import Dates
import Base: _sizeof_uv_fs, uv_error

function setmtime(path::AbstractString, mtime::Real, atime::Real=mtime; follow_symlinks::Bool=true)
    req = Libc.malloc(_sizeof_uv_fs)
    try
        if follow_symlinks
            ret = ccall(:uv_fs_utime, Cint,
                (Ptr{Cvoid}, Ptr{Cvoid}, Cstring, Cdouble, Cdouble, Ptr{Cvoid}),
                C_NULL, req, path, atime, mtime, C_NULL)
        else
            ret = ccall(:uv_fs_lutime, Cint,
                (Ptr{Cvoid}, Ptr{Cvoid}, Cstring, Cdouble, Cdouble, Ptr{Cvoid}),
                C_NULL, req, path, atime, mtime, C_NULL)
        end
        ccall(:uv_fs_req_cleanup, Cvoid, (Ptr{Cvoid},), req)
        ret < 0 && uv_error("utime($(repr(path)))", ret)
    finally
        Libc.free(req)
    end
end

setmtime(path::AbstractString, mtime::Dates.AbstractDateTime, atime::Dates.AbstractDateTime=mtime; follow_symlinks::Bool=true) =
    setmtime(path, Dates.datetime2unix(mtime), Dates.datetime2unix(atime); follow_symlinks=follow_symlinks)

Might make a good PR if someone wanted to put together some documentation and a test.

3 Likes

Awesome, thank you. I’ll be happy to give the PR a go after Christmas.