summaryrefslogtreecommitdiffstats
path: root/gxpp.c
blob: e61fa9fbe5bed2641044550e2199b70b9f765042 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/*
 * gxpp.c  -- Simple XPath Util
 *	
 *	Print the string result of the XPath query to stdout.
 *	Optionaly print only the number of matches.
 *
 * Copyright © 2006-2008 Red Hat, Inc. All rights reserved.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions of the
 * GNU General Public License v.2.  This program is distributed in the hope
 * that it will be useful, but WITHOUT ANY WARRANTY expressed or implied,
 * including the implied warranties of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
 * trademarks that are incorporated in the source code or documentation are not
 * subject to the GNU General Public License and may only be used or replicated
 * with the express permission of Red Hat, Inc.
 *
 * Red Hat Author(s): Dean Jansa <djansa@redhat.com>
 *                    Nathan Straz <nstraz@redhat.com>
 */

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <libxml/xinclude.h>

#include "gxp-int.h"

static int gxpp(char *xfile, const char *xpath_query, const char *prefix);
static int xpath(xmlDocPtr doc, xmlXPathContextPtr ctx, const char *xpathstr,
                 const char *xfile);
static int xpath_nodedump(xmlXPathContextPtr ctx, const char *xpathstr,
                          const char *xfile);
static void usage(const char *pname);

static struct {
	unsigned countonly      : 1;      /* -c                      */
	unsigned addfileprefix  : 1;      /* -H or multi file args   */
	unsigned omitfileprefix : 1;      /* -h with multi file args */
	unsigned filenomatch    : 1;      /* -L                      */
	unsigned filematch      : 1;      /* -l                      */
	unsigned quiet          : 1;      /* -q                      */
	unsigned xmlnodedump    : 1;      /* -x                      */
} gxpp_opts;
	


int 
main(int argc, char **argv) 
{
	char *xpath_query;
	char *prefix;
	int retval;
	int c;

	gxpp_opts.countonly = 0;
	gxpp_opts.addfileprefix = 0;
	gxpp_opts.omitfileprefix = 0;
	gxpp_opts.filenomatch = 0;
	gxpp_opts.filematch = 0;
	gxpp_opts.quiet = 0;
	gxpp_opts.xmlnodedump = 0;
	xpath_query = NULL;
	prefix = NULL;

	while ((c = getopt(argc, argv, "+cHhLlqxp:")) != -1) {
		switch (c) {
			case 'c':
				gxpp_opts.countonly = 1;
				break;
			case 'H':
				gxpp_opts.addfileprefix = 1;
				gxpp_opts.omitfileprefix = 0;
				break;
			case 'h':
				gxpp_opts.addfileprefix = 0;
				gxpp_opts.omitfileprefix = 1;
				break;
			case 'L':
				gxpp_opts.filenomatch = 1;
				gxpp_opts.filematch = 0;
				gxpp_opts.quiet = 1;
				break;
			case 'l':
				gxpp_opts.filenomatch = 0;
				gxpp_opts.filematch = 1;
				gxpp_opts.quiet = 1;
				break;
			case 'p':
				prefix = strdup(optarg);
				break;
			case 'q':
				gxpp_opts.quiet = 1;
				break;
			case 'x':
				gxpp_opts.xmlnodedump = 1;
				break;
			case '?':
				usage(argv[0]);
				exit(2);
				break;
		}
	}

	xpath_query = argv[optind];
	if (!xpath_query) {
		fprintf(stderr, "Missing XPath Query\n");
		usage(argv[0]);
		exit(2);
	} 

	optind++;
	if (!argv[optind]) {
		/* No files given, use stdin */
		retval = gxpp("-", xpath_query, prefix);
	} else {
		/* Rest of the args are the files to search */
		if (((argc - optind) > 1) 
		    && (!gxpp_opts.omitfileprefix)) gxpp_opts.addfileprefix = 1;

		for (c = optind; c < argc; c++) {
			retval = gxpp(argv[c], xpath_query, prefix);
			if (retval < 0) {
				break;
			}
			if (gxpp_opts.filematch && retval > 0) printf("%s\n", argv[c]);
			if (gxpp_opts.filenomatch && !retval) printf("%s\n", argv[c]);
		}
	}

	if (retval == -1) {
			retval = 2;
	} else {
		retval = !retval;
	}

	exit(retval);
}


/*
 * gxpp --
 *
 *	Open file, parse doc and run the xpath query.
 *
 *	Returns:
 *		Number of matches on success, less than zero on failure.
 *		No matches is not a failure, return of 0 is just no matches found.
 */

static int
gxpp(char *xfile, const char *xpath_query, const char *prefix)
{
	xmlDocPtr doc;
	xmlXPathContextPtr ctx;
	char *cp;
	int retval;

	if (!(doc = xmlParseFile(xfile))) {
		fprintf(stderr, "XML Parse failed\n");
		return -1;
	}

	ctx = generate_context(doc, prefix);

	/* FIXME: do some error checking */
	xmlXIncludeProcess(doc);
	if (gxpp_opts.xmlnodedump) {
		retval = xpath_nodedump(ctx, xpath_query, xfile);
	} else {
		if (gxpp_opts.countonly) {
			cp = malloc(strlen(xpath_query) + strlen("count()") + 1);
			sprintf(cp, "count(%s)", xpath_query);
			xpath_query = cp;
		}

		retval = xpath(doc, ctx, xpath_query, xfile);
	}

	xmlXPathFreeContext(ctx);
	xmlFreeDoc(doc);

	return retval;
}


/*
 * xpath_nodedump --
 *
 *	Dump all XML nodes which match XPath query to stdout.
 *
 *	Returns:
 *		Number of nodes which matched XPath query
 */

static int
xpath_nodedump(xmlXPathContextPtr ctx, const char *xpathstr, const char *xfile)
{
	xmlXPathObjectPtr obj = NULL;
	xmlNodePtr node;
	xmlBufferPtr xmlbp;
	int i;
	
	obj = xmlXPathEvalExpression((xmlChar *)xpathstr, ctx);

	if ((obj == NULL) || (obj->type != XPATH_NODESET) 
	     || (obj->nodesetval == NULL))  {
		return 0;
	}

	for (i = 0; i < obj->nodesetval->nodeNr; i++) {
		node = xmlXPathNodeSetItem(obj->nodesetval, i);

		xmlbp = xmlBufferCreate();
		xmlNodeDump(xmlbp, NULL, node, 0, 0);
		if (!gxpp_opts.quiet) {
			if (gxpp_opts.addfileprefix) printf("%s: ", xfile);
			printf("%s\n", xmlBufferContent(xmlbp));
		}
		xmlBufferFree(xmlbp);	
	}

	xmlXPathFreeObject(obj);

	return i;
}


/*
 * xpath --
 *
 *	Dump all XML nodes string values which match XPath query to stdout.
 *
 *	Returns:
 *		Number of nodes which matched XPath query.
 *		-1 on error.
 */

static int
xpath(xmlDocPtr doc, xmlXPathContextPtr ctx, const char *xpathstr, 
      const char *xfile)
{
	xmlNodeSetPtr nodeset;
	xmlXPathObjectPtr result;
	xmlChar *strval;
	int matchc = 0;
	double num;
	int i;

	result = xmlXPathEvalExpression((xmlChar *)xpathstr, ctx);
	if (result == NULL) {
		return -1;
	}

	switch (result->type) {
		case XPATH_NODESET:
			if (xmlXPathNodeSetIsEmpty(result->nodesetval)){
				xmlXPathFreeObject(result);
				return 0;
			}

			nodeset = result->nodesetval;
			matchc=nodeset->nodeNr;
			for (i=0; i < nodeset->nodeNr; i++) {
				strval = xmlNodeListGetString(doc, 
		              		nodeset->nodeTab[i]->xmlChildrenNode, 1);
				if (strval) {
					if (!gxpp_opts.quiet) {
						if (gxpp_opts.addfileprefix) printf("%s: ", xfile);
						printf("%s\n", strval);
					}
					xmlFree(strval);
				}
			}

			break;

		case XPATH_BOOLEAN:
			matchc=1;
			if (!gxpp_opts.quiet) {
				if (gxpp_opts.addfileprefix) printf("%s: ", xfile);
				printf("%d\n", xmlXPathCastToBoolean(result));
			}
			break;

		case XPATH_NUMBER:
			matchc=1;
			num = xmlXPathCastToNumber(result);
			if (!gxpp_opts.quiet) {
				if (gxpp_opts.addfileprefix) printf("%s: ", xfile);
				if ((ceil(num) - num) == 0) {
					printf("%lld\n", (long long int)num);
				} else {
					printf("%f\n", num);
				}
			}
			break;

		case XPATH_STRING:
			matchc=1;
			/*
			 * xmlXPathCastToString(result) -- return the string value of 
			 * the object, NULL in case of error. A new string is allocated 
			 * only if needed (result  isn't a string object).  We are only
			 * in this case if result is a string obj, no need to free()
			 * the return value.
			 */
			if (!gxpp_opts.quiet) {
				if (gxpp_opts.addfileprefix) printf("%s: ", xfile);
				printf("%s\n", xmlXPathCastToString(result));
			}
			break;

		default:
			matchc=0;
			break;
	}

	xmlXPathFreeObject(result);
    return matchc;
}


static void 
usage(const char *pname)
{
	fprintf(stderr,"Usage: %s [OPTION]... XPATH [FILE]...\n", pname);
	fprintf(stderr,"Options:\n"
	               "-c          Print count of matches in file only\n"
	               "-H          Print filename for each match. \n"
	               "-h          Suppress filenames when multiple files are searched\n"
	               "-L          Print the filename of files without matches\n"
	               "-l          Print the filename of files with matches\n"
	               "-q          Suppress output of matches\n"
	               "-x          Dump nodes which match in XML format\n"
	               "-p prefix   Set prefix for default namespace\n");

	return;
}