summaryrefslogtreecommitdiff
path: root/src/execline/dollarat.c
blob: 136968b5cbf2b4e45437c98aae6e552c7d717ab6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* ISC license. */

#include <sys/types.h>
#include <skalibs/bytestr.h>
#include <skalibs/sgetopt.h>
#include <skalibs/buffer.h>
#include <skalibs/strerr2.h>
#include <skalibs/djbunix.h>
#include <skalibs/uint.h>
#include <skalibs/netstring.h>

#define USAGE "dollarat [ -n ] [ -0 | -d delimchar ]"

int main (int argc, char const *const *argv, char const *const *envp)
{
  unsigned int n, i = 0 ;
  char const *x ;
  char delim = '\n' ;
  int zero = 0 ;
  int nl = 1 ;
  PROG = "dollarat" ;
  {
    subgetopt_t l = SUBGETOPT_ZERO ;
    for (;;)
    {
      register int opt = subgetopt_r(argc, argv, "nd:0", &l) ;
      if (opt == -1) break ;
      switch (opt)
      {
        case 'n' : nl = 0 ; break ;
        case 'd' : delim = *l.arg ; break ;
        case '0' : zero = 1 ; break ;
        default : strerr_dieusage(100, USAGE) ;
      }
    }
    argc -= l.ind ; argv += l.ind ;
  }
  if (zero) delim = 0 ;
  x = env_get2(envp, "#") ;
  if (!x) strerr_dienotset(100, "#") ;
  if (!uint0_scan(x, &n)) strerr_dieinvalid(100, "#") ;
  for (; i < n ; i++)
  {
    char fmt[UINT_FMT] ;
    fmt[uint_fmt(fmt, i+1)] = 0 ;
    x = env_get2(envp, fmt) ;
    if (!x) strerr_dienotset(100, fmt) ;
    if (delim || zero)
    {
      if ((buffer_puts(buffer_1, x) < 0)
       || (((i < n-1) || nl) && (buffer_put(buffer_1, &delim, 1) < 0)))
        strerr_diefu1sys(111, "write to stdout") ;
    }
    else
    {
      size_t written = 0 ;
      if (!netstring_put(buffer_1, x, str_len(x), &written))
        strerr_diefu1sys(111, "write a netstring to stdout") ;
    }
  }
  if (!buffer_flush(buffer_1))
    strerr_diefu1sys(111, "write to stdout") ;
  return 0 ;
}