]> git.cworth.org Git - tar/blob - lib/rpmatch.c
Imported Upstream version 1.20
[tar] / lib / rpmatch.c
1 /* Determine whether string value is affirmation or negative response
2    according to current locale's data.
3
4    Copyright (C) 1996, 1998, 2000, 2002, 2003, 2006 Free Software
5    Foundation, Inc.
6
7    This program is free software: you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include <config.h>
21
22 #include <stddef.h>
23 #include <stdlib.h>
24
25 #if ENABLE_NLS
26 # include <sys/types.h>
27 # include <limits.h>
28 # include <regex.h>
29 # include "gettext.h"
30 # define _(msgid) gettext (msgid)
31
32 static int
33 try (const char *response, const char *pattern, const int match,
34      const int nomatch, const char **lastp, regex_t *re)
35 {
36   if (pattern != *lastp)
37     {
38       /* The pattern has changed.  */
39       if (*lastp)
40         {
41           /* Free the old compiled pattern.  */
42           regfree (re);
43           *lastp = NULL;
44         }
45       /* Compile the pattern and cache it for future runs.  */
46       if (regcomp (re, pattern, REG_EXTENDED) != 0)
47         return -1;
48       *lastp = pattern;
49     }
50
51   /* See if the regular expression matches RESPONSE.  */
52   return regexec (re, response, 0, NULL, 0) == 0 ? match : nomatch;
53 }
54 #endif
55
56
57 int
58 rpmatch (const char *response)
59 {
60 #if ENABLE_NLS
61   /* Match against one of the response patterns, compiling the pattern
62      first if necessary.  */
63
64   /* We cache the response patterns and compiled regexps here.  */
65   static const char *yesexpr, *noexpr;
66   static regex_t yesre, nore;
67   int result;
68
69   return ((result = try (response, _("^[yY]"), 1, 0,
70                          &yesexpr, &yesre))
71           ? result
72           : try (response, _("^[nN]"), 0, -1, &noexpr, &nore));
73 #else
74   /* Test against "^[yY]" and "^[nN]", hardcoded to avoid requiring regex */
75   return (*response == 'y' || *response == 'Y' ? 1
76           : *response == 'n' || *response == 'N' ? 0 : -1);
77 #endif
78 }