1/* strftime - loadable builtin interface to strftime(3) */
2
3/* See Makefile for compilation details. */
4
5#include <config.h>
6
7#if defined (HAVE_UNISTD_H)
8#  include <unistd.h>
9#endif
10
11#include "bashtypes.h"
12#include "posixtime.h"
13
14#include <stdio.h>
15
16#include "builtins.h"
17#include "shell.h"
18#include "common.h"
19
20int
21strftime_builtin (list)
22     WORD_LIST *list;
23{
24  char *format, *tbuf;
25  size_t tbsize, tsize;
26  time_t secs;
27  struct tm *t;
28  int n;
29  intmax_t i;
30
31  if (list == 0)
32    {
33      builtin_usage ();
34      return (EX_USAGE);
35    }
36
37  if (no_options (list))
38    return (EX_USAGE);
39
40  format = list->word->word;
41  if (format == 0 || *format == 0)
42    {
43      printf ("\n");
44      return (EXECUTION_SUCCESS);
45    }
46
47  list = list->next;
48
49  if (list && list->word->word)
50    {
51      n = legal_number (list->word->word, &i);
52      if (n == 0 || i < 0 || i != (time_t)i)
53	{
54	  sh_invalidnum (list->word->word);
55	  return (EXECUTION_FAILURE);
56	}
57      else
58        secs = i;
59    }
60  else
61    secs = NOW;
62
63  t = localtime (&secs);
64
65  tbsize = strlen (format) * 4;
66  tbuf = 0;
67
68  /* Now try to figure out how big the buffer should really be.  strftime(3)
69     will return the number of bytes placed in the buffer unless it's greater
70     than MAXSIZE, in which case it returns 0. */
71  for (n = 1; n < 4; n++)
72    {
73      tbuf = xrealloc (tbuf, tbsize * n);
74      tsize = strftime (tbuf, tbsize * n, format, t);
75      if (tsize)
76        break;
77    }
78
79  printf ("%s\n", tbuf);
80  free (tbuf);
81
82  return (EXECUTION_SUCCESS);
83}
84
85/* An array of strings forming the `long' documentation for a builtin xxx,
86   which is printed by `help xxx'.  It must end with a NULL. */
87char *strftime_doc[] = {
88	"Converts date and time format to a string and displays it on the",
89	"standard output.  If the optional second argument is supplied, it",
90	"is used as the number of seconds since the epoch to use in the",
91	"conversion, otherwise the current time is used.",
92	(char *)NULL
93};
94
95/* The standard structure describing a builtin command.  bash keeps an array
96   of these structures.  The flags must include BUILTIN_ENABLED so the
97   builtin can be used. */
98struct builtin strftime_struct = {
99	"strftime",		/* builtin name */
100	strftime_builtin,	/* function implementing the builtin */
101	BUILTIN_ENABLED,	/* initial flags for builtin */
102	strftime_doc,		/* array of long documentation strings. */
103	"strftime format [seconds]",	/* usage synopsis; becomes short_doc */
104	0			/* reserved for internal use */
105};
106