getquote

Getquote implementation for ledger(1)
Log | Files | Refs | README

getquoteaction (1945B)


      1 #!/usr/bin/awk -f
      2 #
      3 # Helper script for getquote, ledger-compatible price fetcher
      4 #
      5 # Copyright (c) 2026 Jacob R. Edwards <jacob@jacobedwards.org>
      6 #
      7 # Permission to use, copy, modify, and distribute this software for any
      8 # purpose with or without fee is hereby granted, provided that the above
      9 # copyright notice and this permission notice appear in all copies.
     10 #
     11 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     12 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     13 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     14 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     15 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     16 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     17 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     18 
     19 function resolve_symbol(s, _start) {
     20 	if (!_start)
     21 		_start = s
     22 	else if (s == _start)
     23 		err(s ": Circular definition")
     24 
     25 	if (!(s in k))
     26 		return s
     27 	if (k[s] ~ /^=/)
     28 		return resolve_symbol(substr(k[s], 2), _start)
     29 	return s
     30 }
     31 
     32 function resolve_action(s) {
     33 	if (!(s in k)) {
     34 		if ("*" in k)
     35 			s = "*"
     36 		else
     37 			return ""
     38 	}
     39 	if (k[s] !~ /^=/)
     40 		return k[s]
     41 	return ""
     42 }
     43 
     44 function err(msg) {
     45 	print msg > "/dev/stderr"
     46 	exit (status = 1)
     47 }
     48 
     49 BEGIN {
     50 	if (ARGC-- <= 1)
     51 		err("usage: getquoteaction symbol [file ...]")
     52 	s = ARGV[1]
     53 	delete ARGV[1]
     54 }
     55 
     56 # Remove comments
     57 { sub("(^|[ 	]+)#.*", "", $0) }
     58 
     59 # Remove empty lines (sometimes created by removing comments)
     60 /^$/ { next }
     61 
     62 # Error on obviously invalid lines
     63 NF != 2 { err(NR ": Must have two lines") }
     64 
     65 {
     66 	if ($1 == "*" && $2 ~ /^=/)
     67 		err("error: Wildcard can only be used for actions")
     68 	if ($2 !~ /^=/ && $2 != "quote" && $2 != "exchange")
     69 		err("error: " $2 ": Only quote and exchange actions supported")
     70 	k[$1] = $2
     71 }
     72 
     73 END {
     74 	if (status)
     75 		exit status
     76 	s = resolve_symbol(s)
     77 	a = resolve_action(s)
     78 	OFS = "	"
     79 	print s, a
     80 }