| 1 | # Shared helpers for the in-tree spinel tools (spinel-doctor / spinel-reduce /
|
| 2 | # spinel-flatten). Compiled into each tool by `require_relative`; written in the
|
| 3 | # spinel subset so the tools themselves compile with spinel.
|
| 4 |
|
| 5 | # Exit status of the most recent sh() call.
|
| 6 | $sh_status = 0
|
| 7 |
|
| 8 | # Run a shell command, capturing stdout+stderr together, and record the exit
|
| 9 | # status in $sh_status. Returns the captured output.
|
| 10 | def sh(cmd)
|
| 11 | out = `#{cmd} 2>&1`
|
| 12 | $sh_status = $?
|
| 13 | out
|
| 14 | end
|
| 15 |
|
| 16 | # Locate the spinel compiler binary. Resolution order: $SPINEL (explicit path),
|
| 17 | # $SPINEL_DIR/spinel, then `spinel` on PATH. Exits 2 if none resolve.
|
| 18 | def find_spinel
|
| 19 | e = ENV["SPINEL"]
|
| 20 | return e if e && e.length > 0 && File.exist?(e)
|
| 21 | d = ENV["SPINEL_DIR"]
|
| 22 | if d && d.length > 0
|
| 23 | p = d + "/spinel"
|
| 24 | return p if File.exist?(p)
|
| 25 | end
|
| 26 | w = `command -v spinel 2>/dev/null`.strip
|
| 27 | return w if w.length > 0
|
| 28 | $stderr.puts "spinel-tool: cannot find the spinel compiler."
|
| 29 | $stderr.puts " set SPINEL=/path/to/spinel, or SPINEL_DIR, or put spinel on PATH."
|
| 30 | exit(2)
|
| 31 | end
|
| 32 |
|
| 33 | # Is `name` an executable on PATH?
|
| 34 | def have_cmd(name)
|
| 35 | `command -v #{name} 2>/dev/null`.strip.length > 0
|
| 36 | end
|
| 37 |
|
| 38 | # The last path component of `path`.
|
| 39 | def base_name(path)
|
| 40 | parts = path.split("/")
|
| 41 | parts[parts.length - 1]
|
| 42 | end
|
| 43 |
|
| 44 | # The directory of `path` ("." when there is no slash).
|
| 45 | def dir_name(path)
|
| 46 | parts = path.split("/")
|
| 47 | return "." if parts.length < 2
|
| 48 | parts[0, parts.length - 1].join("/")
|
| 49 | end
|
| 50 |
|
| 51 | # A scratch path under TMPDIR (or /tmp), tagged by the tool and source name so
|
| 52 | # concurrent runs on different sources don't collide.
|
| 53 | def tmp_path(tag, src, ext)
|
| 54 | d = ENV["TMPDIR"]
|
| 55 | d = "/tmp" if !d || d.length == 0
|
| 56 | d + "/spinel-" + tag + "-" + base_name(src) + ext
|
| 57 | end
|
| 58 |
|
| 59 | # Print to stderr and exit with `code`.
|
| 60 | def die(msg, code)
|
| 61 | $stderr.puts msg
|
| 62 | exit(code)
|
| 63 | end
|