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