Forum: Ruby Linux mode bits

Posted by Rob Marshall (rjmarshall17)
on 2013-01-29 23:06
Hi,

Is there a class available for handling the Linux mode bits? i.e.
Assuming I have the access mode of a file as a number, e.g. 33188
(octal: 0100644), can I test the mode bits? In Python I can use the
'stat' module which has all of the bits defined as well as tests like:
S_ISREG(). Is there something analogous in Ruby?

Thanks,

Rob
Posted by tamouse mailing lists (Guest)
on 2013-01-30 02:32
(Received via mailing list)
On Tue, Jan 29, 2013 at 4:06 PM, Rob Marshall <lists@ruby-forum.com> 
wrote:
> Is there a class available for handling the Linux mode bits? i.e.
> Assuming I have the access mode of a file as a number, e.g. 33188
> (octal: 0100644), can I test the mode bits? In Python I can use the
> 'stat' module which has all of the bits defined as well as tests like:
> S_ISREG(). Is there something analogous in Ruby?

minimally, FIle.stat(filename).mode will give the file's mode bits as a 
Fixnum:

1.9.3-head :007 > "%o" % File.stat('.emacs').mode
 => "100644"
Posted by Sam Duncan (Guest)
on 2013-01-30 02:53
(Received via mailing list)
On 01/30/2013 11:06 AM, Rob Marshall wrote:
> Rob
>
Sadly the symbolic constants are not exposed (afaik). You can define
your own which should be relatively stable if you are just working in a
linux environment. For instance (but obviously not complete)

# ruby, why you no expose these for my platform?!!
# ---
S_IFMT   = 0170000  # bit mask for the file type bit fields
S_IFDIR  = 0040000  # directory

S_ISUID  = 0004000  # set UID bit
S_ISGID  = 0002000  # set-group-ID bit
S_ISVTX  = 0001000  # sticky bit

S_IRUSR  = 00400    # owner has read permission
S_IWUSR  = 00200    # owner has write permission
S_IXUSR  = 00100    # owner has execute permission

S_IRGRP  = 00040    # group has read permission
S_IWGRP  = 00020    # group has write permission
S_IXGRP  = 00010    # group has execute permission

S_IROTH  = 00004    # others have read permission
S_IWOTH  = 00002    # others have write permission
S_IXOTH  = 00001    # others have execute permission

S_IMODE = 07777     # mask for user adjustable mode bits


File.lstat('foo').mode & S_IFMT == S_IFDIR
File.lstat('foo').mode & S_IMODE == 
S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP

You could wrap it up in a nice module or class if you wanted.
Posted by Rob Marshall (rjmarshall17)
on 2013-01-30 05:18
OK. That's what I had assumed.

Thanks,

Rob
Posted by Rob Marshall (rjmarshall17)
on 2013-01-30 06:54
Attachment: FileStat.rb (3,43 KB)
OK, so I've attached what I have...I think it works correctly :-)

enjoy,

Rob
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.