# [user@host ~]$ ls -l blah
# -rwxr--r-- 1 user users 0 2008-11-06 15:20 foo
def convert(file)
output = [""]
File.stat(file).mode.to_s(8).slice(-3..-1).split('').each do |m|
case m.to_i
when 1 then output << ["-","-","x"]
when 2 then output << ["-","w","-"]
when 3 then output << ["-","w","x"]
when 4 then output << ["r","-","-"]
when 5 then output << ["r","-","x"]
when 6 then output << ["r","w","-"]
when 7 then output << ["r","w","x"]
end
end
output.flatten!
if File.directory?(file) then output[0] = "d"; end
if File.file?(file) then output[0] = "-"; end
if File.symlink?(file) then output[0] = "l"; end
if File.setuid?(file) then output[3] = "s"; end
if File.setgid?(file) then output[6] = "s"; end
if File.sticky?(file)
if output[3] && output[6] == "-"
output[9] = "T"
else
output[9] = "t"
end
end
puts output.flatten.to_s
end
convert('poop')
Refactorings
No refactoring yet !
Elij
November 7, 2008, November 07, 2008 00:08, permalink
Not much difference -- but what the hey!
def convert(file)
output = [""]
File.stat(file).mode.to_s(8).slice(-3..-1).split('').each do |m|
permbit = m.to_i
output << genflag(permbit, 4, "r")
output << genflag(permbit, 2, "w")
output << genflag(permbit, 1, "x")
end
output.flatten!
if File.directory?(file) then output[0] = "d"; end
if File.file?(file) then output[0] = "-"; end
if File.symlink?(file) then output[0] = "l"; end
if File.setuid?(file) then output[3] = "s"; end
if File.setgid?(file) then output[6] = "s"; end
if File.sticky?(file)
if output[3] && output[6] == "-"
output[9] = "T"
else
output[9] = "t"
end
end
puts output.flatten.to_s
end
def genflag(permbit, bit, perm)
if ((permbit & bit) == bit)
then [perm]
else ["-"]
end
end
convert('poop')
Adam
November 7, 2008, November 07, 2008 03:12, permalink
require 'filemode' File.stat(ARGV[0]).to_s # => "-rw-r--r--"
require 'mkmf' extension_name = 'filemode' dir_config(extension_name) create_makefile(extension_name)
#include <ruby.h>
// Using filemode from GNU coreutils
#include "filemode.h"
static VALUE file_stat_to_s(VALUE self)
{
char mode_string_value[11];
VALUE mode = rb_funcall(self, rb_intern("mode"), 0);
mode_string(NUM2INT(mode), mode_string_value);
return rb_str_new2(mode_string_value);
}
void Init_filemode()
{
VALUE file = rb_define_class("File", rb_cIO);
VALUE stat = rb_define_class_under(file, "Stat", rb_cObject);
rb_define_method(stat, "to_s", file_stat_to_s, 0);
}
This snippet is designed to match the permission bits output of an ls -l command for a shell replacement written in Ruby.