summaryrefslogtreecommitdiff
path: root/Touch.hsc
blob: 4e1052b94ac09c029a0614d85c52ed29c32c4186 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
{- More control over touching a file.
 -
 - Copyright 2011 Joey Hess <joey@kitenet.net>
 -
 - Licensed under the GNU GPL version 3 or higher.
 -}

{-# LANGUAGE ForeignFunctionInterface #-}

module Touch (
	TimeSpec(..),
	now,
	omit,
	touchBoth,
	touch
) where

import Foreign
import Foreign.C

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

data TimeSpec = TimeSpec CTime CLong

instance Storable TimeSpec where
	-- use the larger alignment of the two types in the struct
	alignment _ = max sec_alignment nsec_alignment
		where
			sec_alignment = alignment $ undefined::CTime
			nsec_alignment = alignment $ undefined::CLong
	sizeOf _ = #{size struct timespec}
	peek ptr = do
		sec <- #{peek struct timespec, tv_sec} ptr
		nsec <- #{peek struct timespec, tv_nsec} ptr
		return $ TimeSpec sec nsec
	poke ptr (TimeSpec sec nsec) = do
		#{poke struct timespec, tv_sec} ptr sec
		#{poke struct timespec, tv_nsec} ptr nsec

{- special timespecs -}
omit :: TimeSpec
omit = TimeSpec 0 #const UTIME_OMIT
now :: TimeSpec
now = TimeSpec 0 #const UTIME_NOW

{- While its interface is beastly, utimensat is in recent
   POSIX standards, unlike futimes. -}
foreign import ccall "utimensat" 
	c_utimensat :: CInt -> CString -> Ptr TimeSpec -> CInt -> IO CInt

{- Changes the access and/or modification times of a file.
   Can follow symlinks, or not. -}
touchBoth :: FilePath -> TimeSpec -> TimeSpec -> Bool -> IO Bool
touchBoth file atime mtime follow = 
	allocaArray 2 $ \ptr ->
	withCString file $ \f -> do
		pokeArray ptr [atime, mtime]
		r <- c_utimensat at_fdcwd f ptr flags
		return (r == 0)
	where
		at_fdcwd = #const AT_FDCWD
		at_symlink_nofollow = #const AT_SYMLINK_NOFOLLOW

		flags = if follow
			then 0
			else at_symlink_nofollow 

touch :: FilePath -> TimeSpec -> Bool -> IO Bool
touch file mtime follow = touchBoth file omit mtime follow