Categories
Development Devops Software

(almost) Native BASH semver CHECK

Recently I needed a simple way to compare semver strings in a BASH script and was unable to find a solution that I liked so I wrote one. Why almost-native BASH? Leveraging the common available sort utility avoids re-implementing the version sort logic, reduces potential bugs and size of the function to a simple 3 lines vs 30+ lines for most BASH-native solutions.

This is working well in environments I manage. If you notice any bugs or issues please comment.

Function returns a standard -1, 0, 1 response. Basic unit tests included to validate functionality and provide example usage.

Enjoy!

#!/usr/bin/env bash

function semver_check {
  # sort low->high then pick the last one (highest)
  local HV; HV=$(echo -e "$1\n$2" |sort -V |tail -1)
  # They're not the same and $1 is not the high version = -1
  [[ "$1" != "$2" && "$1" != "$HV" ]] && echo -1 && return
  # 0 = they're the same; 1 = not the same
  [[ "$1" == "$2" ]]; echo $?
}

#
# TESTS
#

LV="1.2.3"
HV="2.3.4"

ARGS=("Test A: Ver1 == Ver2" "$LV" "$LV")
echo -n "${ARGS[*]} "
[[ $(semver_check "${ARGS[1]}" "${ARGS[2]}") -eq 0 ]] && echo "PASS" || echo "FAIL"

ARGS=("Test B: Ver1 < Ver2" "$LV" "$HV")
echo -n "${ARGS[*]} "
[[ $(semver_check "${ARGS[1]}" "${ARGS[2]}") -lt 0 ]] && echo "PASS" || echo "FAIL"

ARGS=("Test C: Ver1 > Ver2" "$HV" "$LV")
echo -n "${ARGS[*]} "
[[ $(semver_check "${ARGS[1]}" "${ARGS[2]}") -gt 0 ]] && echo "PASS" || echo "FAIL"

ARGS=("Test D: Ver1 >= Ver2" "$HV" "$LV")
echo -n "${ARGS[*]} "
RESULT="PASS"
[[ $(semver_check "${ARGS[1]}" "${ARGS[2]}") -ge 0 ]] || RESULT="FAIL"
[[ $(semver_check "${ARGS[1]}" "${ARGS[1]}") -ge 0 ]] || RESULT="FAIL"
echo ${RESULT}

ARGS=("Test E: Ver1 <= Ver2" "$LV" "$HV")
echo -n "${ARGS[*]} "
RESULT="PASS"
[[ $(semver_check "${ARGS[1]}" "${ARGS[2]}") -le 0 ]] || RESULT="FAIL"
[[ $(semver_check "${ARGS[1]}" "${ARGS[1]}") -le 0 ]] || RESULT="FAIL"
echo ${RESULT}

Addendum: The sort binary dependency must support natural version sort option (-V, --version-sort) This option is available on GNU coreutils 7+ and is also available on Mac OS 10.14+

Categories
Development NodeJS Software

The best way to do module.exports in node

Recently had a question asked regarding the right way to export an object in node. Consider the following code

class Foo {
    constructor() {
        this.foo = 'foo'
    }
}

module.exports = function() {
    return new Foo()
}

We have a class that exports a function which returns a shiny new Foo object.

Great! Then someone asks. Why bother wrapping it in a function when you can just return the object? Let’s see.

class Foo {
    constructor() {
        this.foo = 'foo'
    }
}
module.exports = new Foo()

Basically the same thing right? Not so fast! Yes, the function is gone and now it is returning that shiny new Foo object directly. However this second version will only create one Foo object. You can require the module anywhere in your code and it will always return the same Foo object.

Take a look at this REPL (Read-Eval-Print-Loop)

> foo=require('./foo')()
Foo { foo: 'foo' }
> foo.foo='bar'
'bar'
> bar=require('./foo')()
Foo { foo: 'foo' }
> foo
Foo { foo: 'bar' }

As you can see above this is the foo module from our first example. You can tell by the trailing parens () on the require statement. That is executing the function that is exported by the module.

We assigned the Foo object to a variable named foo. You can see that the property ‘foo’ of object foo is set to a string with the value ‘foo’.

Next we set the property foo to a string ‘bar’ and then we require foo again. This time we assign it the variable bar and we see that it is in fact a brand new Foo object because bar.foo equals ‘foo’ but foo.foo equals ‘bar’

(wishing I’d used different variables at this point, oh well too late for that now) Still with me? Great!

So everything looks good… well, that is if you want a brand new Foo every time you require the module, but what about that second example. Let’s have a look.

> foo=require('./foo')
Foo { foo: 'foo' }
> bar=require('./foo')
Foo { foo: 'foo' }
> bar.foo='bar'
'bar'
> foo
Foo { foo: 'bar' }
> baz=require('./foo')
Foo { foo: 'bar' }

Here we require the same foo module twice assign it once to foo and once to bar. They are both the same, as you would expect however this time when we set bar.foo to the string value ‘bar’ we can actually see that we only have a single object because when we check our foo object the foo property is now a string with the value ‘bar’.

Just to make the point extra clear we require foo a third time and assign it to baz. Again you see that baz.foo equals ‘bar’.

This is what is known as a Singleton, the module only creates one object the first time it is used and then it hands that same object out every time it is required again.

This is a very important concept to understand and remember. One way isn’t better than another. The method you choose depends on what you are trying to accomplish. For example if you have a logging module that you want to configure once but use everywhere then you’ll want to use the second example but if you’re creating a catalog of items each with their own distinct properties you’ll want to stick with the first example.

Categories
Development Devops Software SysAdmin

Inline parsing JSON objects in 3 languages

JavaScript Object Notation commonly known as JSON, is a convenient format for many reasons and it is no wonder that many APIs and web services today support returning (in some cases exclusively) JSON.  Many times I have had a need to parse values from large JSON Objects in a shell script environment or a command line shell, and use them as inputs to another program.  This has put me on the look out for easy ways to handle inline parsing of JSON Objects using languages commonly available on modern Linux systems.

Below are examples in three languages (Node JS, Python and Perl) to accomplish this task.

Example JSON Object:

{"product": {"builds": {"1234": "IT WORKS!"}, "default": "1234"}}

Inline Node JS:

node -e "s=''; i=process.stdin; i.on('data', function(d) { s += d }); i.on('end', function() { j=JSON.parse(s).product; console.log(j.builds[j.default]) })"

Inline Python:

python -c 'import sys, json; j=json.load(sys.stdin)["product"]; print j["builds"][j["default"]]'

Inline Perl:

perl -e 'use JSON; local $/; $d=decode_json(<>)->{product}; print $d->{builds}->{$d->{default}}'
  • The JSON module is required in the above example. If not already available it can easily be installed via CPAN with:
sudo perl -MCPAN -e 'install JSON'


Full example for Python:

echo '{"product": {"builds": {"1234": "IT WORKS!"}, "default": "1234"}}' |python -c 'import sys, json; j=json.load(sys.stdin)["product"]; print j["builds"][j["default"]]'

Categories
Development

Stompy.COM 2.0 live!

New site live – http://www.stompy.com

Categories
Development

Free RADIUS patch

Submitted a bug fix / patch to the rlm_unix module which was merged with the main branch of the Free Radius project on June 30th 2003.

Revision 1.57 / (download) – annotate – [select for diffs], Mon Jun 30 15:22:45 2003 UTC by aland
Branch: MAIN
Changes since 1.56: +3 -3 lines
Diff to previous 1.56 (colored)
Use the ‘canonical user name’ for Unix group lookups, not the
User-Name attribute.

Patch from James J. Williams

rlm_unix_patch.tgz