(main): Call initialize_main.
[platform/upstream/coreutils.git] / src / date.c
1 /* date - print or set the system date and time
2    Copyright (C) 1989-2003 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18    David MacKenzie <djm@gnu.ai.mit.edu> */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
24 #if HAVE_LANGINFO_CODESET
25 # include <langinfo.h>
26 #endif
27
28 #include "system.h"
29 #include "argmatch.h"
30 #include "closeout.h"
31 #include "error.h"
32 #include "getdate.h"
33 #include "getline.h"
34 #include "posixtm.h"
35 #include "posixver.h"
36 #include "strftime.h"
37 #include "timespec.h"
38
39 /* The official name of this program (e.g., no `g' prefix).  */
40 #define PROGRAM_NAME "date"
41
42 #define AUTHORS "David MacKenzie"
43
44 int putenv ();
45
46 static void show_date (const char *format, struct timespec when);
47
48 enum Time_spec
49 {
50   /* display only the date: 1999-03-25 */
51   TIME_SPEC_DATE=1,
52   /* display date and hour: 1999-03-25T03-0500 */
53   TIME_SPEC_HOURS,
54   /* display date, hours, and minutes: 1999-03-25T03:23-0500 */
55   TIME_SPEC_MINUTES,
56   /* display date, hours, minutes, and seconds: 1999-03-25T03:23:14-0500 */
57   TIME_SPEC_SECONDS
58 };
59
60 static char const *const time_spec_string[] =
61 {
62   "date", "hours", "minutes", "seconds", 0
63 };
64
65 static enum Time_spec const time_spec[] =
66 {
67   TIME_SPEC_DATE, TIME_SPEC_HOURS, TIME_SPEC_MINUTES, TIME_SPEC_SECONDS
68 };
69
70 /* The name this program was run with, for error messages. */
71 char *program_name;
72
73 /* If nonzero, display an ISO 8601 format date/time string */
74 static int iso_8601_format = 0;
75
76 /* If non-zero, display time in RFC-(2)822 format for mail or news. */
77 static int rfc_format = 0;
78
79 #define COMMON_SHORT_OPTIONS "Rd:f:r:s:u"
80
81 static struct option const long_options[] =
82 {
83   {"date", required_argument, NULL, 'd'},
84   {"file", required_argument, NULL, 'f'},
85   {"iso-8601", optional_argument, NULL, 'I'},
86   {"reference", required_argument, NULL, 'r'},
87   {"rfc-822", no_argument, NULL, 'R'},
88   {"set", required_argument, NULL, 's'},
89   {"uct", no_argument, NULL, 'u'},
90   {"utc", no_argument, NULL, 'u'},
91   {"universal", no_argument, NULL, 'u'},
92   {GETOPT_HELP_OPTION_DECL},
93   {GETOPT_VERSION_OPTION_DECL},
94   {NULL, 0, NULL, 0}
95 };
96
97 #if LOCALTIME_CACHE
98 # define TZSET tzset ()
99 #else
100 # define TZSET /* empty */
101 #endif
102
103 #ifdef _DATE_FMT
104 # define DATE_FMT_LANGINFO() nl_langinfo (_DATE_FMT)
105 #else
106 # define DATE_FMT_LANGINFO() ""
107 #endif
108
109 void
110 usage (int status)
111 {
112   if (status != 0)
113     fprintf (stderr, _("Try `%s --help' for more information.\n"),
114              program_name);
115   else
116     {
117       printf (_("\
118 Usage: %s [OPTION]... [+FORMAT]\n\
119   or:  %s [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]\n\
120 "),
121               program_name, program_name);
122       fputs (_("\
123 Display the current time in the given FORMAT, or set the system date.\n\
124 \n\
125   -d, --date=STRING         display time described by STRING, not `now'\n\
126   -f, --file=DATEFILE       like --date once for each line of DATEFILE\n\
127   -ITIMESPEC, --iso-8601[=TIMESPEC]  output date/time in ISO 8601 format.\n\
128                             TIMESPEC=`date' for date only,\n\
129                             `hours', `minutes', or `seconds' for date and\n\
130                             time to the indicated precision.\n\
131                             --iso-8601 without TIMESPEC defaults to `date'.\n\
132 "), stdout);
133       fputs (_("\
134   -r, --reference=FILE      display the last modification time of FILE\n\
135   -R, --rfc-822             output RFC-822 compliant date string\n\
136   -s, --set=STRING          set time described by STRING\n\
137   -u, --utc, --universal    print or set Coordinated Universal Time\n\
138 "), stdout);
139       fputs (HELP_OPTION_DESCRIPTION, stdout);
140       fputs (VERSION_OPTION_DESCRIPTION, stdout);
141       fputs (_("\
142 \n\
143 FORMAT controls the output.  The only valid option for the second form\n\
144 specifies Coordinated Universal Time.  Interpreted sequences are:\n\
145 \n\
146   %%   a literal %\n\
147   %a   locale's abbreviated weekday name (Sun..Sat)\n\
148 "), stdout);
149       fputs (_("\
150   %A   locale's full weekday name, variable length (Sunday..Saturday)\n\
151   %b   locale's abbreviated month name (Jan..Dec)\n\
152   %B   locale's full month name, variable length (January..December)\n\
153   %c   locale's date and time (Sat Nov 04 12:02:33 EST 1989)\n\
154 "), stdout);
155       fputs (_("\
156   %C   century (year divided by 100 and truncated to an integer) [00-99]\n\
157   %d   day of month (01..31)\n\
158   %D   date (mm/dd/yy)\n\
159   %e   day of month, blank padded ( 1..31)\n\
160 "), stdout);
161       fputs (_("\
162   %F   same as %Y-%m-%d\n\
163   %g   the 2-digit year corresponding to the %V week number\n\
164   %G   the 4-digit year corresponding to the %V week number\n\
165 "), stdout);
166       fputs (_("\
167   %h   same as %b\n\
168   %H   hour (00..23)\n\
169   %I   hour (01..12)\n\
170   %j   day of year (001..366)\n\
171 "), stdout);
172       fputs (_("\
173   %k   hour ( 0..23)\n\
174   %l   hour ( 1..12)\n\
175   %m   month (01..12)\n\
176   %M   minute (00..59)\n\
177 "), stdout);
178       fputs (_("\
179   %n   a newline\n\
180   %N   nanoseconds (000000000..999999999)\n\
181   %p   locale's upper case AM or PM indicator (blank in many locales)\n\
182   %P   locale's lower case am or pm indicator (blank in many locales)\n\
183   %r   time, 12-hour (hh:mm:ss [AP]M)\n\
184   %R   time, 24-hour (hh:mm)\n\
185   %s   seconds since `00:00:00 1970-01-01 UTC' (a GNU extension)\n\
186 "), stdout);
187       fputs (_("\
188   %S   second (00..60); the 60 is necessary to accommodate a leap second\n\
189   %t   a horizontal tab\n\
190   %T   time, 24-hour (hh:mm:ss)\n\
191   %u   day of week (1..7);  1 represents Monday\n\
192 "), stdout);
193       fputs (_("\
194   %U   week number of year with Sunday as first day of week (00..53)\n\
195   %V   week number of year with Monday as first day of week (01..53)\n\
196   %w   day of week (0..6);  0 represents Sunday\n\
197   %W   week number of year with Monday as first day of week (00..53)\n\
198 "), stdout);
199       fputs (_("\
200   %x   locale's date representation (mm/dd/yy)\n\
201   %X   locale's time representation (%H:%M:%S)\n\
202   %y   last two digits of year (00..99)\n\
203   %Y   year (1970...)\n\
204 "), stdout);
205       fputs (_("\
206   %z   RFC-822 style numeric timezone (-0500) (a nonstandard extension)\n\
207   %Z   time zone (e.g., EDT), or nothing if no time zone is determinable\n\
208 \n\
209 By default, date pads numeric fields with zeroes.  GNU date recognizes\n\
210 the following modifiers between `%' and a numeric directive.\n\
211 \n\
212   `-' (hyphen) do not pad the field\n\
213   `_' (underscore) pad the field with spaces\n\
214 "), stdout);
215       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
216     }
217   exit (status);
218 }
219
220 /* Parse each line in INPUT_FILENAME as with --date and display each
221    resulting time and date.  If the file cannot be opened, tell why
222    then exit.  Issue a diagnostic for any lines that cannot be parsed.
223    If any line cannot be parsed, return nonzero;  otherwise return zero.  */
224
225 static int
226 batch_convert (const char *input_filename, const char *format)
227 {
228   int status;
229   FILE *in_stream;
230   char *line;
231   int line_length;
232   size_t buflen;
233   struct timespec when;
234
235   if (strcmp (input_filename, "-") == 0)
236     {
237       input_filename = _("standard input");
238       in_stream = stdin;
239     }
240   else
241     {
242       in_stream = fopen (input_filename, "r");
243       if (in_stream == NULL)
244         {
245           error (EXIT_FAILURE, errno, "`%s'", input_filename);
246         }
247     }
248
249   line = NULL;
250   buflen = 0;
251   status = 0;
252   while (1)
253     {
254       line_length = getline (&line, &buflen, in_stream);
255       if (line_length < 0)
256         {
257           /* FIXME: detect/handle error here.  */
258           break;
259         }
260
261       when.tv_sec = get_date (line, NULL);
262       when.tv_nsec = 0; /* FIXME: get_date should set this.  */
263
264       if (when.tv_sec == -1)
265         {
266           if (line[line_length - 1] == '\n')
267             line[line_length - 1] = '\0';
268           error (0, 0, _("invalid date `%s'"), line);
269           status = 1;
270         }
271       else
272         {
273           show_date (format, when);
274         }
275     }
276
277   if (fclose (in_stream) == EOF)
278     error (2, errno, "`%s'", input_filename);
279
280   if (line != NULL)
281     free (line);
282
283   return status;
284 }
285
286 int
287 main (int argc, char **argv)
288 {
289   int optc;
290   const char *datestr = NULL;
291   const char *set_datestr = NULL;
292   struct timespec when;
293   int set_date = 0;
294   char *format;
295   char *batch_file = NULL;
296   char *reference = NULL;
297   struct stat refstats;
298   int n_args;
299   int status;
300   int option_specified_date;
301   char const *short_options = (posix2_version () < 200112
302                                ? COMMON_SHORT_OPTIONS "I::"
303                                : COMMON_SHORT_OPTIONS "I:");
304
305   initialize_main (&argc, &argv);
306   program_name = argv[0];
307   setlocale (LC_ALL, "");
308   bindtextdomain (PACKAGE, LOCALEDIR);
309   textdomain (PACKAGE);
310
311   close_stdout_set_status (2);
312   atexit (close_stdout);
313
314   while ((optc = getopt_long (argc, argv, short_options, long_options, NULL))
315          != -1)
316     switch (optc)
317       {
318       case 0:
319         break;
320       case 'd':
321         datestr = optarg;
322         break;
323       case 'f':
324         batch_file = optarg;
325         break;
326       case 'I':
327         iso_8601_format = (optarg
328                            ? XARGMATCH ("--iso-8601", optarg,
329                                         time_spec_string, time_spec)
330                            : TIME_SPEC_DATE);
331         break;
332       case 'r':
333         reference = optarg;
334         break;
335       case 'R':
336         rfc_format = 1;
337         break;
338       case 's':
339         set_datestr = optarg;
340         set_date = 1;
341         break;
342       case 'u':
343         /* POSIX says that `date -u' is equivalent to setting the TZ
344            environment variable, so this option should do nothing other
345            than setting TZ.  */
346         if (putenv ("TZ=UTC0") != 0)
347           xalloc_die ();
348         TZSET;
349         break;
350       case_GETOPT_HELP_CHAR;
351       case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
352       default:
353         usage (EXIT_FAILURE);
354       }
355
356   n_args = argc - optind;
357
358   option_specified_date = ((datestr ? 1 : 0)
359                            + (batch_file ? 1 : 0)
360                            + (reference ? 1 : 0));
361
362   if (option_specified_date > 1)
363     {
364       error (0, 0,
365         _("the options to specify dates for printing are mutually exclusive"));
366       usage (EXIT_FAILURE);
367     }
368
369   if (set_date && option_specified_date)
370     {
371       error (0, 0,
372           _("the options to print and set the time may not be used together"));
373       usage (EXIT_FAILURE);
374     }
375
376   if (n_args > 1)
377     {
378       error (0, 0, _("too many non-option arguments: %s%s"),
379              argv[optind + 1], n_args == 2 ? "" : " ...");
380       usage (EXIT_FAILURE);
381     }
382
383   if ((set_date || option_specified_date)
384       && n_args == 1 && argv[optind][0] != '+')
385     {
386       error (0, 0, _("\
387 the argument `%s' lacks a leading `+';\n\
388 When using an option to specify date(s), any non-option\n\
389 argument must be a format string beginning with `+'."),
390              argv[optind]);
391       usage (EXIT_FAILURE);
392     }
393
394   /* Simply ignore --rfc-822 if specified when setting the date.  */
395   if (rfc_format && !set_date && n_args > 0)
396     {
397       error (0, 0,
398              _("a format string may not be specified when using\
399  the --rfc-822 (-R) option"));
400       usage (EXIT_FAILURE);
401     }
402
403   if (set_date)
404     datestr = set_datestr;
405
406   if (batch_file != NULL)
407     {
408       status = batch_convert (batch_file,
409                               (n_args == 1 ? argv[optind] + 1 : NULL));
410     }
411   else
412     {
413       bool valid_date = true;
414       status = 0;
415
416       if (!option_specified_date && !set_date)
417         {
418           if (n_args == 1 && argv[optind][0] != '+')
419             {
420               /* Prepare to set system clock to the specified date/time
421                  given in the POSIX-format.  */
422               set_date = 1;
423               datestr = argv[optind];
424               valid_date = posixtime (&when.tv_sec,
425                                       datestr,
426                                       (PDS_TRAILING_YEAR
427                                        | PDS_CENTURY | PDS_SECONDS));
428               when.tv_nsec = 0; /* FIXME: posixtime should set this.  */
429               format = NULL;
430             }
431           else
432             {
433               /* Prepare to print the current date/time.  */
434               datestr = _("undefined");
435               if (gettime (&when) != 0)
436                 error (EXIT_FAILURE, errno, _("cannot get time of day"));
437               format = (n_args == 1 ? argv[optind] + 1 : NULL);
438             }
439         }
440       else
441         {
442           /* (option_specified_date || set_date) */
443           if (reference != NULL)
444             {
445               if (stat (reference, &refstats))
446                 error (EXIT_FAILURE, errno, "%s", reference);
447               when.tv_sec = refstats.st_mtime;
448               when.tv_nsec = TIMESPEC_NS (refstats.st_mtim);
449             }
450           else
451             {
452               when.tv_sec = get_date (datestr, NULL);
453               when.tv_nsec = 0; /* FIXME: get_date should set this.  */
454               valid_date = (when.tv_sec != (time_t) -1);
455             }
456
457           format = (n_args == 1 ? argv[optind] + 1 : NULL);
458         }
459
460       if (! valid_date)
461         error (EXIT_FAILURE, 0, _("invalid date `%s'"), datestr);
462
463       if (set_date)
464         {
465           /* Set the system clock to the specified date, then regardless of
466              the success of that operation, format and print that date.  */
467           if (settime (&when) != 0)
468             {
469               error (0, errno, _("cannot set date"));
470               status = 1;
471             }
472         }
473
474       show_date (format, when);
475     }
476
477   exit (status);
478 }
479
480 /* Display the date and/or time in WHEN according to the format specified
481    in FORMAT, followed by a newline.  If FORMAT is NULL, use the
482    standard output format (ctime style but with a timezone inserted). */
483
484 static void
485 show_date (const char *format, struct timespec when)
486 {
487   struct tm *tm;
488   char *out = NULL;
489   size_t out_length = 0;
490   /* ISO 8601 formats.  See below regarding %z */
491   static char const * const iso_format_string[] =
492   {
493     "%Y-%m-%d",
494     "%Y-%m-%dT%H%z",
495     "%Y-%m-%dT%H:%M%z",
496     "%Y-%m-%dT%H:%M:%S%z"
497   };
498
499   tm = localtime (&when.tv_sec);
500
501   if (format == NULL)
502     {
503       if (rfc_format)
504         format = "%a, %d %b %Y %H:%M:%S %z";
505       else if (iso_8601_format)
506         format = iso_format_string[iso_8601_format - 1];
507       else
508         {
509           char *date_fmt = DATE_FMT_LANGINFO ();
510           /* Do not wrap the following literal format string with _(...).
511              For example, suppose LC_ALL is unset, LC_TIME="POSIX",
512              and LANG="ko_KR".  In that case, POSIX says that LC_TIME
513              determines the format and contents of date and time strings
514              written by date, which means "date" must generate output
515              using the POSIX locale; but adding _() would cause "date"
516              to use a Korean translation of the format.  */
517           format = *date_fmt ? date_fmt : "%a %b %e %H:%M:%S %Z %Y";
518         }
519     }
520   else if (*format == '\0')
521     {
522       printf ("\n");
523       return;
524     }
525
526   while (1)
527     {
528       int done;
529       out_length += 200;
530       out = xrealloc (out, out_length);
531
532       /* Mark the first byte of the buffer so we can detect the case
533          of nstrftime producing an empty string.  Otherwise, this loop
534          would not terminate when date was invoked like this
535          `LANG=de date +%p' on a system with good language support.  */
536       out[0] = '\1';
537
538       if (rfc_format)
539         setlocale (LC_ALL, "C");
540
541       done = (nstrftime (out, out_length, format, tm, 0, when.tv_nsec)
542               || out[0] == '\0');
543
544       if (rfc_format)
545         setlocale (LC_ALL, "");
546
547       if (done)
548         break;
549     }
550
551   printf ("%s\n", out);
552   free (out);
553 }