Checking version of file in Ruby on Windows - ruby

Is there a way in Ruby to find the version of a file, specifically a .dll file?

For Windows EXE's and DLL's:
require "Win32API"
FILENAME = "c:/ruby/bin/ruby.exe" #your filename here
s=""
vsize=Win32API.new('version.dll', 'GetFileVersionInfoSize',
['P', 'P'], 'L').call(FILENAME, s)
p vsize
if (vsize > 0)
result = ' '*vsize
Win32API.new('version.dll', 'GetFileVersionInfo',
['P', 'L', 'L', 'P'], 'L').call(FILENAME, 0, vsize, result)
rstring = result.unpack('v*').map{|s| s.chr if s<256}*''
r = /FileVersion..(.*?)\000/.match(rstring)
puts "FileVersion = #{r ? r[1] : '??' }"
else
puts "No Version Info"
end
The 'unpack'+regexp part is a hack, the "proper" way is the VerQueryValue API, but this should work for most files. (probably fails miserably on extended character sets.)

What if you want to get the version info with ruby, but the ruby code isn't running on Windows?
The following does just that (heeding the same extended charset warning):
#!/usr/bin/ruby
s = File.read(ARGV[0])
x = s.match(/F\0i\0l\0e\0V\0e\0r\0s\0i\0o\0n\0*(.*?)\0\0\0/)
if x.class == MatchData
ver=x[1].gsub(/\0/,"")
else
ver="No version"
end
puts ver

As of Ruby 2.0, the DL module is deprecated. Here is an updated version of AShelly's answer, using Fiddle:
version_dll = Fiddle.dlopen('version.dll')
s=''
vsize = Fiddle::Function.new(version_dll['GetFileVersionInfoSize'],
[Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP],
Fiddle::TYPE_LONG).call(filename, s)
raise 'Unable to determine the version number' unless vsize > 0
result = ' '*vsize
Fiddle::Function.new(version_dll['GetFileVersionInfo'],
[Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG,
Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP],
Fiddle::TYPE_VOIDP).call(filename, 0, vsize, result)
rstring = result.unpack('v*').map{|s| s.chr if s<256}*''
r = /FileVersion..(.*?)\000/.match(rstring)
puts r[1]

If you are working on the Microsoft platform, you should be able to use the Win32 API in Ruby to call GetFileVersionInfo(), which will return the information you're looking for.
http://msdn.microsoft.com/en-us/library/ms647003.aspx

For any file, you'd need to discover what format the file is in, and then open the file and read the necessary bytes to find out what version the file is. There is no API or common method to determine a file version in Ruby.
Note that it would be easier if the file version were in the file name.

Related

Where is the ruby function 'powershell' defined?

I am using the msutter DSC module for puppet. While reading through the source code, I come across code like this (in dsc_configuration_provider.rb):
def create
Puppet.debug "\n" + ps_script_content('set')
output = powershell(ps_script_content('set'))
Puppet.debug output
end
What file defines the powershell function or method? Is it a ruby builtin? A puppet builtin? Inherited from a class? I know that it is being used to send text to powershell as a command and gathering results, but I need to see the source code to understand how to improve its error logging for my purposes, because certain powershell errors are being swallowed and no warnings are being printed to the Puppet log.
These lines in file dsc_provider_helpers.rb may be relevant:
provider.commands :powershell =>
if File.exists?("#{ENV['SYSTEMROOT']}\\sysnative\\WindowsPowershell\\v1.0\\powershell.exe")
"#{ENV['SYSTEMROOT']}\\sysnative\\WindowsPowershell\\v1.0\\powershell.exe"
elsif File.exists?("#{ENV['SYSTEMROOT']}\\system32\\WindowsPowershell\\v1.0\\powershell.exe")
"#{ENV['SYSTEMROOT']}\\system32\\WindowsPowershell\\v1.0\\powershell.exe"
else
'powershell.exe'
end
Surely this defines where the Powershell executable is located, but gives no indication how it is called and how its return value is derived. Are stdout and stderr combined? Am I given the text output or just the error code? etc.
This is core Puppet logic. When a provider has a command, like
commands :powershell => some binary
That is hooked up as a function powershell(*args).
You can see it with other providers like Chocolatey:
commands :chocolatey => chocolatey_command
def self.chocolatey_command
if Puppet::Util::Platform.windows?
# must determine how to get to params in ruby
#default_location = $chocolatey::params::install_location || ENV['ALLUSERSPROFILE'] + '\chocolatey'
chocopath = ENV['ChocolateyInstall'] ||
('C:\Chocolatey' if File.directory?('C:\Chocolatey')) ||
('C:\ProgramData\chocolatey' if File.directory?('C:\ProgramData\chocolatey')) ||
"#{ENV['ALLUSERSPROFILE']}\chocolatey"
chocopath += '\bin\choco.exe'
else
chocopath = 'choco.exe'
end
chocopath
end
Then other locations can just call chocolatey like a function with args:
chocolatey(*args)

How to stop ImageMagick in Ruby (Rmagick) evaluating an # sign in text annotation

In an app I recently built for a client the following code resulted in the variable #nameText being evaluated, and then resulting in an error 'no text' (since the variable doesn't exist).
To get around this I used gsub, as per the example below. Is there a way to tell Magick not to evaluate the string at all?
require 'RMagick'
#image = Magick::Image.read( '/path/to/image.jpg' ).first
#nameText = '#SomeTwitterUser'
#text = Magick::Draw.new
#text.font_family = 'Futura'
#text.pointsize = 22
#text.font_weight = Magick::BoldWeight
# Causes error 'no text'...
# #text.annotate( #image, 0,0,200,54, #nameText )
#text.annotate( #image, 0,0,200,54, #nameText.gsub('#', '\#') )
This is the C code from RMagick that is returning the error:
// Translate & store in Draw structure
draw->info->text = InterpretImageProperties(NULL, image, StringValuePtr(text));
if (!draw->info->text)
{
rb_raise(rb_eArgError, "no text");
}
It is the call to InterpretImageProperties that is modifying the input text - but it is not Ruby, or a Ruby instance variable that it is trying to reference. The function is defined here in the Image Magick core library: http://www.imagemagick.org/api/MagickCore/property_8c_source.html#l02966
Look a bit further down, and you can see the code:
/* handle a '#' replace string from file */
if (*p == '#') {
p++;
if (*p != '-' && (IsPathAccessible(p) == MagickFalse) ) {
(void) ThrowMagickException(&image->exception,GetMagickModule(),
OptionError,"UnableToAccessPath","%s",p);
return((char *) NULL);
}
return(FileToString(p,~0,&image->exception));
}
In summary, this is a core library feature which will attempt to load text from file (named SomeTwitterUser in your case, I have confirmed this -try it!), and your work-around is probably the best you can do.
For efficiency, and minimal changes to input strings, you could rely on the selectivity of the library code and only modify the string if it starts with #:
#text.annotate( #image, 0,0,200,54, #name_string.gsub( /^#/, '\#') )

How do I remove "hidden" characters when reading a line of text in Ruby?

I am using a custom Ruby function in Puppet to read a string of text from a file. I am than comparing whatever version is read against a list of known versions to determine which config file I should use for that particular server. The problem is that when I compare the read version to my list of known versions, none of them match.
I printed out the variable to the screen, and it looked fine. I then added a '-' to the beginning and the end and this time, the following was printed
-2.2#012-
Does anyone know what this is and how it could be removed?
Here is my process.
A script that handles the installation of an app
sudo echo "2.2" > /opt/version
My ruby function
if FileTest.exists?("/opt/version")
Facter.add("app_version") do
setcode do
version = File.open('/opt/version', &:readline)
version
end
end
end
My puppet manifest
if versioncmp( $app_version, '2.2') == 0 {
notice("===> Installing 2.2 Configs")
} elsif versioncmp ($app_version, '2.3') == 0 {
notice("===> Installing 2.3 Configs")
} else {
notice("===> No version match. Continuing on.")
}
}
File.readline includes the line termination (in your case, "\n"). chomp will get rid of the line termination:
version = File.open('/opt/version', &:readline).chomp
When debugging and you want to see what's really in a variable, use p instead of puts. p will escape unprintable characters so you can see them:
puts "2.2\n" # => 2.2
#
p "2.2\n" # => "2.2\n"

How to change the prompt

I am trying to configure the prompt characters in ripl, an alternative to interactive ruby (irb). In irb, it is done using IRB.conf[:DEFAULT], but it does not seem to work with ripl. I am also having difficulty finding an instruction for it. Please guide to a link for an explanation or give a brief explanation.
Configuring a dynamic prompt in ~/.riplrc:
# Shows current directory
Ripl.config[:prompt] = lambda { Dir.pwd + '> ' }
# Print current line number
Ripl.config[:prompt] = lambda { "ripl(#{Ripl.shell.line})> " }
# Simple string prommpt
Ripl.config[:prompt] = '>>> '
Changing the prompt in the shell:
>> Ripl.shell.prompt = lambda { Dir.pwd + '> ' }
ripl loads your ~/.irbrc file, which
typically contains some irb specific
options (e.g. IRB.conf[:PROMPT]). To
avoid errors, you can install
ripl-irb, which catches calls to the
IRB constant and prints messages to
convert irb configuration to ripl
equivalents.
http://rbjl.net/44-ripl-why-should-you-use-an-irb-alternative

TokyoCabinet's Ruby C interface can't bzip

I'm using the Ruby official Ruby C interface and am not able to bzip working. It did build with bzip support, ./configure said:
checking bzlib.h usability... yes
checking bzlib.h presence... yes
checking for bzlib.h... yes
So I wrote this example program that just writes an entry to two files, one supposedly bzip'd and one not. Neither is compressed; aside from the simple file size test at the end I can edit the with_bzip.tcb
file and see the raw string text there.
require 'tokyocabinet'
include TokyoCabinet
def write filename, options
File.unlink filename if File.exists? filename
bdb = BDB::new
bdb.tune(0, 0, 0, -1 -1, options) or raise "Couldn't tune"
bdb.open(filename, BDB::OWRITER | BDB::OCREAT | BDB::OLCKNB) or raise "Couldn't open"
bdb["test"] = "This string should be compressed and not appear raw.\n" * 10000
bdb.close
end
write 'without_bzip.tcb', 0
write 'with_bzip.tcb', BDB::TBZIP
puts "Not actually compressed" unless File.size('with_bzip.tcb') < File.size('without_bzip.tcb')
What makes it worse is that if I try a preview release of Oklahoma Mixer (example following - though I don't have the reputation to add the new tag), it compresses fine. When I tucked some debugging into its try() call, it seems to be making the same call to tune(0, 0, 0, -1, -1, 4). I'm pretty completely stumped - can anyone tell me what my code above is doing wrong?
require 'oklahoma_mixer'
OklahomaMixer.open("minimal_om.tcb", :opts => 'lb') do |db|
db["test"] = "This string should be compressed and not appear raw.\n" * 10000
end
It is an evil, subtle bug. I left out a comma in the tune() call and wrote -1 -1 instead of -1, -1. All the arguments are optional, so it was quietly not bzipping. Argh.

Resources