sh-i18n--envsubst.con commit Merge branch 'po/object-id' into next (0faff38)
   1/*
   2 * sh-i18n--envsubst.c - a stripped-down version of gettext's envsubst(1)
   3 *
   4 * Copyright (C) 2010 Ævar Arnfjörð Bjarmason
   5 *
   6 * This is a modified version of
   7 * 67d0871a8c:gettext-runtime/src/envsubst.c from the gettext.git
   8 * repository. It has been stripped down to only implement the
   9 * envsubst(1) features that we need in the git-sh-i18n fallbacks.
  10 *
  11 * The "Close standard error" part in main() is from
  12 * 8dac033df0:gnulib-local/lib/closeout.c. The copyright notices for
  13 * both files are reproduced immediately below.
  14 */
  15
  16#include "git-compat-util.h"
  17
  18/* Substitution of environment variables in shell format strings.
  19   Copyright (C) 2003-2007 Free Software Foundation, Inc.
  20   Written by Bruno Haible <bruno@clisp.org>, 2003.
  21
  22   This program is free software; you can redistribute it and/or modify
  23   it under the terms of the GNU General Public License as published by
  24   the Free Software Foundation; either version 2, or (at your option)
  25   any later version.
  26
  27   This program is distributed in the hope that it will be useful,
  28   but WITHOUT ANY WARRANTY; without even the implied warranty of
  29   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  30   GNU General Public License for more details.
  31
  32   You should have received a copy of the GNU General Public License
  33   along with this program; if not, write to the Free Software Foundation,
  34   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
  35
  36/* closeout.c - close standard output and standard error
  37   Copyright (C) 1998-2007 Free Software Foundation, Inc.
  38
  39   This program is free software; you can redistribute it and/or modify
  40   it under the terms of the GNU General Public License as published by
  41   the Free Software Foundation; either version 2, or (at your option)
  42   any later version.
  43
  44   This program is distributed in the hope that it will be useful,
  45   but WITHOUT ANY WARRANTY; without even the implied warranty of
  46   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  47   GNU General Public License for more details.
  48
  49   You should have received a copy of the GNU General Public License
  50   along with this program; if not, write to the Free Software Foundation,
  51   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
  52
  53#include <errno.h>
  54#include <stdio.h>
  55#include <stdlib.h>
  56#include <string.h>
  57
  58/* If true, substitution shall be performed on all variables.  */
  59static unsigned short int all_variables;
  60
  61/* Forward declaration of local functions.  */
  62static void print_variables (const char *string);
  63static void note_variables (const char *string);
  64static void subst_from_stdin (void);
  65
  66int
  67cmd_main (int argc, const char *argv[])
  68{
  69  /* Default values for command line options.  */
  70  /* unsigned short int show_variables = 0; */
  71
  72  switch (argc)
  73        {
  74        case 1:
  75          error ("we won't substitute all variables on stdin for you");
  76          break;
  77          /*
  78          all_variables = 1;
  79      subst_from_stdin ();
  80          */
  81        case 2:
  82          /* echo '$foo and $bar' | git sh-i18n--envsubst --variables '$foo and $bar' */
  83          all_variables = 0;
  84          note_variables (argv[1]);
  85      subst_from_stdin ();
  86          break;
  87        case 3:
  88          /* git sh-i18n--envsubst --variables '$foo and $bar' */
  89          if (strcmp(argv[1], "--variables"))
  90                error ("first argument must be --variables when two are given");
  91          /* show_variables = 1; */
  92      print_variables (argv[2]);
  93          break;
  94        default:
  95          error ("too many arguments");
  96          break;
  97        }
  98
  99  /* Close standard error.  This is simpler than fwriteerror_no_ebadf, because
 100     upon failure we don't need an errno - all we can do at this point is to
 101     set an exit status.  */
 102  errno = 0;
 103  if (ferror (stderr) || fflush (stderr))
 104    {
 105      fclose (stderr);
 106      exit (EXIT_FAILURE);
 107    }
 108  if (fclose (stderr) && errno != EBADF)
 109    exit (EXIT_FAILURE);
 110
 111  exit (EXIT_SUCCESS);
 112}
 113
 114/* Parse the string and invoke the callback each time a $VARIABLE or
 115   ${VARIABLE} construct is seen, where VARIABLE is a nonempty sequence
 116   of ASCII alphanumeric/underscore characters, starting with an ASCII
 117   alphabetic/underscore character.
 118   We allow only ASCII characters, to avoid dependencies w.r.t. the current
 119   encoding: While "${\xe0}" looks like a variable access in ISO-8859-1
 120   encoding, it doesn't look like one in the BIG5, BIG5-HKSCS, GBK, GB18030,
 121   SHIFT_JIS, JOHAB encodings, because \xe0\x7d is a single character in these
 122   encodings.  */
 123static void
 124find_variables (const char *string,
 125                void (*callback) (const char *var_ptr, size_t var_len))
 126{
 127  for (; *string != '\0';)
 128    if (*string++ == '$')
 129      {
 130        const char *variable_start;
 131        const char *variable_end;
 132        unsigned short int valid;
 133        char c;
 134
 135        if (*string == '{')
 136          string++;
 137
 138        variable_start = string;
 139        c = *string;
 140        if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_')
 141          {
 142            do
 143              c = *++string;
 144            while ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
 145                   || (c >= '0' && c <= '9') || c == '_');
 146            variable_end = string;
 147
 148            if (variable_start[-1] == '{')
 149              {
 150                if (*string == '}')
 151                  {
 152                    string++;
 153                    valid = 1;
 154                  }
 155                else
 156                  valid = 0;
 157              }
 158            else
 159              valid = 1;
 160
 161            if (valid)
 162              callback (variable_start, variable_end - variable_start);
 163          }
 164      }
 165}
 166
 167
 168/* Print a variable to stdout, followed by a newline.  */
 169static void
 170print_variable (const char *var_ptr, size_t var_len)
 171{
 172  fwrite (var_ptr, var_len, 1, stdout);
 173  putchar ('\n');
 174}
 175
 176/* Print the variables contained in STRING to stdout, each one followed by a
 177   newline.  */
 178static void
 179print_variables (const char *string)
 180{
 181  find_variables (string, &print_variable);
 182}
 183
 184
 185/* Type describing list of immutable strings,
 186   implemented using a dynamic array.  */
 187typedef struct string_list_ty string_list_ty;
 188struct string_list_ty
 189{
 190  const char **item;
 191  size_t nitems;
 192  size_t nitems_max;
 193};
 194
 195/* Initialize an empty list of strings.  */
 196static inline void
 197string_list_init (string_list_ty *slp)
 198{
 199  slp->item = NULL;
 200  slp->nitems = 0;
 201  slp->nitems_max = 0;
 202}
 203
 204/* Append a single string to the end of a list of strings.  */
 205static inline void
 206string_list_append (string_list_ty *slp, const char *s)
 207{
 208  /* Grow the list.  */
 209  if (slp->nitems >= slp->nitems_max)
 210    {
 211      slp->nitems_max = slp->nitems_max * 2 + 4;
 212      REALLOC_ARRAY(slp->item, slp->nitems_max);
 213    }
 214
 215  /* Add the string to the end of the list.  */
 216  slp->item[slp->nitems++] = s;
 217}
 218
 219/* Compare two strings given by reference.  */
 220static int
 221cmp_string (const void *pstr1, const void *pstr2)
 222{
 223  const char *str1 = *(const char **)pstr1;
 224  const char *str2 = *(const char **)pstr2;
 225
 226  return strcmp (str1, str2);
 227}
 228
 229/* Sort a list of strings.  */
 230static inline void
 231string_list_sort (string_list_ty *slp)
 232{
 233  QSORT(slp->item, slp->nitems, cmp_string);
 234}
 235
 236/* Test whether a sorted string list contains a given string.  */
 237static int
 238sorted_string_list_member (const string_list_ty *slp, const char *s)
 239{
 240  size_t j1, j2;
 241
 242  j1 = 0;
 243  j2 = slp->nitems;
 244  if (j2 > 0)
 245    {
 246      /* Binary search.  */
 247      while (j2 - j1 > 1)
 248        {
 249          /* Here we know that if s is in the list, it is at an index j
 250             with j1 <= j < j2.  */
 251          size_t j = (j1 + j2) >> 1;
 252          int result = strcmp (slp->item[j], s);
 253
 254          if (result > 0)
 255            j2 = j;
 256          else if (result == 0)
 257            return 1;
 258          else
 259            j1 = j + 1;
 260        }
 261      if (j2 > j1)
 262        if (strcmp (slp->item[j1], s) == 0)
 263          return 1;
 264    }
 265  return 0;
 266}
 267
 268
 269/* Set of variables on which to perform substitution.
 270   Used only if !all_variables.  */
 271static string_list_ty variables_set;
 272
 273/* Adds a variable to variables_set.  */
 274static void
 275note_variable (const char *var_ptr, size_t var_len)
 276{
 277  char *string = xmemdupz (var_ptr, var_len);
 278
 279  string_list_append (&variables_set, string);
 280}
 281
 282/* Stores the variables occurring in the string in variables_set.  */
 283static void
 284note_variables (const char *string)
 285{
 286  string_list_init (&variables_set);
 287  find_variables (string, &note_variable);
 288  string_list_sort (&variables_set);
 289}
 290
 291
 292static int
 293do_getc (void)
 294{
 295  int c = getc (stdin);
 296
 297  if (c == EOF)
 298    {
 299      if (ferror (stdin))
 300        error ("error while reading standard input");
 301    }
 302
 303  return c;
 304}
 305
 306static inline void
 307do_ungetc (int c)
 308{
 309  if (c != EOF)
 310    ungetc (c, stdin);
 311}
 312
 313/* Copies stdin to stdout, performing substitutions.  */
 314static void
 315subst_from_stdin (void)
 316{
 317  static char *buffer;
 318  static size_t bufmax;
 319  static size_t buflen;
 320  int c;
 321
 322  for (;;)
 323    {
 324      c = do_getc ();
 325      if (c == EOF)
 326        break;
 327      /* Look for $VARIABLE or ${VARIABLE}.  */
 328      if (c == '$')
 329        {
 330          unsigned short int opening_brace = 0;
 331          unsigned short int closing_brace = 0;
 332
 333          c = do_getc ();
 334          if (c == '{')
 335            {
 336              opening_brace = 1;
 337              c = do_getc ();
 338            }
 339          if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_')
 340            {
 341              unsigned short int valid;
 342
 343              /* Accumulate the VARIABLE in buffer.  */
 344              buflen = 0;
 345              do
 346                {
 347                  if (buflen >= bufmax)
 348                    {
 349                      bufmax = 2 * bufmax + 10;
 350                      buffer = xrealloc (buffer, bufmax);
 351                    }
 352                  buffer[buflen++] = c;
 353
 354                  c = do_getc ();
 355                }
 356              while ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
 357                     || (c >= '0' && c <= '9') || c == '_');
 358
 359              if (opening_brace)
 360                {
 361                  if (c == '}')
 362                    {
 363                      closing_brace = 1;
 364                      valid = 1;
 365                    }
 366                  else
 367                    {
 368                      valid = 0;
 369                      do_ungetc (c);
 370                    }
 371                }
 372              else
 373                {
 374                  valid = 1;
 375                  do_ungetc (c);
 376                }
 377
 378              if (valid)
 379                {
 380                  /* Terminate the variable in the buffer.  */
 381                  if (buflen >= bufmax)
 382                    {
 383                      bufmax = 2 * bufmax + 10;
 384                      buffer = xrealloc (buffer, bufmax);
 385                    }
 386                  buffer[buflen] = '\0';
 387
 388                  /* Test whether the variable shall be substituted.  */
 389                  if (!all_variables
 390                      && !sorted_string_list_member (&variables_set, buffer))
 391                    valid = 0;
 392                }
 393
 394              if (valid)
 395                {
 396                  /* Substitute the variable's value from the environment.  */
 397                  const char *env_value = getenv (buffer);
 398
 399                  if (env_value != NULL)
 400                    fputs (env_value, stdout);
 401                }
 402              else
 403                {
 404                  /* Perform no substitution at all.  Since the buffered input
 405                     contains no other '$' than at the start, we can just
 406                     output all the buffered contents.  */
 407                  putchar ('$');
 408                  if (opening_brace)
 409                    putchar ('{');
 410                  fwrite (buffer, buflen, 1, stdout);
 411                  if (closing_brace)
 412                    putchar ('}');
 413                }
 414            }
 415          else
 416            {
 417              do_ungetc (c);
 418              putchar ('$');
 419              if (opening_brace)
 420                putchar ('{');
 421            }
 422        }
 423      else
 424        putchar (c);
 425    }
 426}