In my YAML file I have:
foo:
- '0777'
When I load the file in my code (result = YAML.load_file(...)) I get
result[:foo] = [511]
This happens on Ubuntu. On Mac it is correct (["0777"]). When changed to:
foo:
- "'0777'"
it works on Ubuntu but the string consists the quotes: '0777'.
Why?
In Ruby for Integer if the argument is string, and happen to start with 0x, 0b, 0, it is interpreted as hex, binary, octal string respectively.
Therefore here 0777 is being treated as an octal string. Since '0777' octal = '511' decimal, you are getting 511 as result.
reference
Related
I am building an open source project using Ruby for testing HTTP services: https://github.com/Comcast/http-blackbox-test-tool
I want to be able to reference environment variables in my test-plan.yaml file. I could use ERB, however I don't want to support embedding any random Ruby code and ERB syntax is odd for non-rubyists, I just want to access environment variables using the commonly used Unix style ${ENV_VAR} syntax.
e.g.
order-lunch-app-health:
request:
url: ${ORDER_APP_URL}
headers:
content-type: 'application/text'
method: get
expectedResponse:
statusCode: 200
maxRetryCount: 5
All examples I have found for Ruby use ERB. Does anyone have a suggestion on the best way to deal with this? I an open to using another tool to preprocess the YAML and then send that to the Ruby application.
I believe something like this should work under most circumstances:
require 'yaml'
def load_yaml(file)
content = File.read file
content.gsub! /\${([^}]+)}/ do
ENV[$1]
end
YAML.load content
end
p load_yaml 'sample.yml'
As opposed to my original answer, this is both simpler and handles undefined ENV variables well.
Try with this YAML:
# sample.yml
path: ${PATH}
home: ${HOME}
error: ${NO_SUCH_VAR}
Original Answer (left here for reference)
There are several ways to do it. If you want to allow your users to use the ${VAR} syntax, then perhaps one way would be to first convert these variables to Ruby string substitution format %{VAR} and then evaluate all environment variables together.
Here is a rough proof of concept:
require 'yaml'
# Transform environments to a hash of { symbol: value }
env_hash = ENV.to_h.transform_keys(&:to_sym)
# Load the file and convert ${ANYTHING} to %{ANYTHING}
content = File.read 'sample.yml'
content.gsub! /\${([^}]+)}/, "%{\\1}"
# Use Ruby string substitution to replace %{VARS}
content %= env_hash
# Done
yaml = YAML.load content
p yaml
Use it with this sample.yml for instance:
# sample.yml
path: ${PATH}
home: ${HOME}
There are many ways this can be improved upon of course.
Preprocessing is easy, and I recommend you use a YAML loaderd/dumper
based solution, as the replacement might require quotes around the
replacement scalar. (E.g. you substitute the string true, if that
were not quoted, the resulting YAML would be read as a boolean).
Assuming your "source" is in input.yaml and your env. variable
ORDER_APP_URL set to https://some.site/and/url. And the following
script in expand.py:
import sys
import os
from pathlib import Path
import ruamel.yaml
def substenv(d, env):
if isinstance(d, dict):
for k, v in d.items():
if isinstance(v, str) and '${' in v:
d[k] = v.replace('${', '{').format(**env)
else:
substenv(v, env)
elif isinstance(d, list):
for idx, item in enumerate(d):
if isinstance(v, str) and '${' in v:
d[idx] = item.replace('${', '{').format(**env)
else:
substenv(item, env)
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
data = yaml.load(Path(sys.argv[1]))
substenv(data, os.environ)
yaml.dump(data, Path(sys.argv[2]))
You can then do:
python expand.py input.yaml output.yaml
which writes output.yaml:
order-lunch-app-health:
request:
url: https://some.site/and/url
headers:
content-type: 'application/text'
method: get
expectedResponse:
statusCode: 200
maxRetryCount: 5
Please note that the spurious quotes around 'application/text' are preserved, as would be any comments
in the original file.
Quotes around the substituted URL are not necessary, but the would have been added if they were.
The substenv routine recursively traverses the loaded data, and substitutes even if the substitution is in mid-scalar, and if there are more than substitution in one scalar. You can "tighten" the test:
if isinstance(v, str) and '${' in v:
if that would match too many strings loaded from YAML.
I been trying to encode strings using protoc cli utility.
Noticed that output still contains plain text.
What am i doing wrong?
osboxes#osboxes:~/proto/bin$ cat ./teststring.proto
syntax = "proto2";
message Test2 {
optional string b = 2;
}
echo b:\"my_testing_string\"|./protoc --encode Test2 teststring.proto>result.out
result.out contains:
^R^Qmy_testing_string
protoc versions libprotoc 3.6.0 and libprotoc 2.5.0
Just to formalize in an answer:
The command as written should be fine; the output is protobuf binary - it just resembles text because protobuf uses utf-8 to encode strings, and your content is dominated by a string. However, despite this: the file isn't actually text, and you should usually use a hex viewer or similar if you need to inspect it.
If you want to understand the internals of a file, https://protogen.marcgravell.com/decode is a good resource - it rips an input file or hex string following the protocol rules, and tells you what each byte means (field headers, length prefixes, payloads, etc).
I'm guessing your file is actually:
(hex) 10 11 6D 79 5F etc
i.e. 0x10 = "field 2, length prefixed", 0x11 = 17 (the payload length, encoded as varint), then "my_testing_string" encoded as 17 bytes of UTF8.
protoc --proto_path=${protobuf_path} --encode=${protobuf_message} ${protobuf_file} < ${source_file} > ${output_file}
and in this case:
protoc --proto_path=~/proto/bin --encode="Test2" ~/proto/bin/teststring.proto < ${source.txt} > ./output.bin
or:
cat b:\"my_testing_string\" | protoc --proto_path=~/proto/bin --encode="Test2" ~/proto/bin/teststring.proto > ./output.bin
I am trying to create a CRC32
But i keep getting this error for crcvalue = zlib.crc32(crcvalue)
builtins.TypeError: a bytes-like object is required, not 'int'
You are passing 0 to crc32 instead of the file name. This just makes no sense.
just encode the filename as bytes using ascii encoding and pass those bytes to the crc method:
>>> import zlib
>>> x = "filename"
>>> zlib.crc32(x.encode('ascii'))
1007413605
I have dozens of devices I need to login to using an API script. One set of devices has a password ending in $. I've tried a bunch of things but I can't seem to escape that $ char. Here is the error I'm seeing.
critical/config: Error: Validation failed for object 'gelt-uk4-gp!HTTP/80: Status Check ' of type 'Service'; Attribute 'vars' -> 'gspass': Closing $ not found in macro format string 'n0t-real#$'.
Location: in /etc/icinga2/zones.d/global-templates/global-services.conf: 55:5-55:31
/etc/icinga2/zones.d/global-templates/global-services.conf(53): if ( host.vars.company == "gelt-emea" ) {
/etc/icinga2/zones.d/global-templates/global-services.conf(54): vars.gsuser = "admin"
/etc/icinga2/zones.d/global-templates/global-services.conf(55): vars.gspass = "n0t-real#$"
^^^^^^^^^^^^^^^^^^^^^^^^^^^
You add an extra $ right beside the literal dollar sign.
So if the password is word54s$ you type:
vars.geltpass = "word54s$$"
Please find the code which I ran from the IRB terminal:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\rakshiar>irb
irb(main):001:0> src = 'E:\WIPData\Ruby\Scripts\TaxDocumentDownload'
=> "E:\\WIPData\\Ruby\\Scripts\\TaxDocumentDownload"
irb(main):002:0> dest = 'E:\WIPData\Ruby\Scripts'
=> "E:\\WIPData\\Ruby\\Scripts"
irb(main):003:0> dest<<'H00371101'
=> "E:\\WIPData\\Ruby\\ScriptsH00371101"
irb(main):004:0>
Why here such \\ is coming? How to fix that?
When i am running the same part from the script getting the below warnings:
CODE
src = 'E:\WIPData\Ruby\Scripts\TaxDocumentDownload'
dest = 'E:\WIPData\Ruby\Scripts'
dest<<'H00371101'
FileUtils.copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)
Warning:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\rakshiar>cd..
C:\Documents and Settings>cd..
C:\>e:
E:\>cd E:\WIPData\Ruby\Scripts
E:\WIPData\Ruby\Scripts>downloadv1.rb
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:93: warning: already initialized constant
OPT_TABLE
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:1268: warning: already initialized consta
nt S_IF_DOOR
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:1496: warning: already initialized consta
nt DIRECTORY_TERM
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:1500: warning: already initialized consta
nt SYSCASE
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:1619: warning: already initialized consta
nt LOW_METHODS
C:/Ruby193/lib/ruby/1.9.1/FileUtils.rb:1625: warning: already initialized consta
nt METHODS
Could you please say why such warnings are coming?
When try the below from the IRB again different output:
C:\Documents and Settings\rakshiar>irb
irb(main):001:0> src = "E:\WIPData\Ruby\Scripts\TaxDocumentDownload"
=> "E:WIPDataRubyScriptsTaxDocumentDownload"
irb(main):002:0> est = "E:\WIPData\Ruby\Scripts"
=> "E:WIPDataRubyScripts"
irb(main):003:0> est<<"H00371101"
=> "E:WIPDataRubyScriptsH00371101"
irb(main):004:0> est<<"H00371101"
EDIT:
ERROR
E:\WIPData\Ruby\Scripts>downloadv1.rb
E:/WIPData/Ruby/Scripts/downloadv1.rb:87: syntax error, unexpected tCONSTANT, ex
pecting $end
dest<<"H00371101"
^
From the script code part:
src = "E:\WIPData\Ruby\Scripts\TaxDocumentDownload"
dest = "E:\WIPData\Ruby\Scripts\"
dest<<"H00371101"
FileUtils.copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)
I want that src and dest directory as the real directory path. How to get that?
Thanks.
Ruby has, broadly speaking, two types of strings. In a double-quoted string, backslashes "escape" characters - a backslash followed by another letter produces a special character. For example, "\n" gives you a newline. Inside single-quoted strings, the backslash doesn't escape characters - '\n' is just a backslash followed by the letter n. (Actually this isn't 100% true, the exception is '\'' which is a single quote - otherwise there would be no way to embed a single quote in a single-quoted string.
That's why your single-quoted src = 'E:\WIPData\Ruby\Scripts\TaxDocumentDownload' will work, and double-quoted src = "E:\WIPData\Ruby\Scripts\TaxDocumentDownload" will not.
The double-backslashes are printed there because irb uses inspect on the resulting output, which returns the string in double-quoted form (with special characters escaped):
'"Hello," said Andy'.inspect # => "\"Hello,\" said Andy"
They're not really in the string, as you can see with puts:
puts '"Hello," said Andy' # => "Hello," said Andy
The error you have is because of using a double-quoted string, the backslashes are treated as escape characters, so your string is unterminated:
src = "E:\WIPData\Ruby\Scripts\"
dest<<"H00371101"
is parsed the same as
src = 'E:WIPDataRubyScripts"dest<<'H00371101
which is a syntax error.
You should go and read about the difference between single- and double-quoted strings. Here's one resource.
A quick google suggests that you might be doing require 'FileUtils' not require 'fileutils'? This post said that the same warnings disappeared once they changed to the latter. It's because Windows' file system is not case-sensitive - to Ruby, FileUtils.rb and fileutils.rb are two different files, but to Windows, they're the same.
The FileUtils warning it is because you have to change your required gem, like this:
require 'FileUtils' WRONG
require 'fileutils' OKAY
This will solve your warnings :)