xaizek / vifm (License: GPLv2+) (since 2018-12-07)
Vifm is a file manager with curses interface, which provides Vi[m]-like environment for managing objects within file systems, extended with some useful ideas from mutt.
<root> / src / utils / matcher.c (66a065a4215f74f3d7f4445c294bc6fec04afceb) (14KiB) (mode 100644) [raw]
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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
/* vifm
 * Copyright (C) 2015 xaizek.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty 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
 */

#include "matcher.h"

#include <regex.h> /* regex_t regexec() regfree() */

#include <stddef.h> /* NULL */
#include <stdlib.h> /* free() malloc() */
#include <string.h> /* strcspn() strdup() strlen() strrchr() */

#include "../int/file_magic.h"
#include "globs.h"
#include "path.h"
#include "regexp.h"
#include "str.h"
#include "test_helpers.h"

/* Type of a matcher. */
typedef enum
{
	MT_REGEX, /* Regular expression. */
	MT_GLOBS, /* List of globs (translated to regular expression). */
	MT_MIME,  /* List of mime types (translated to regular expression). */
}
MType;

/* Wrapper for a regular expression, its state and compiled form. */
struct matcher_t
{
	char *expr;  /* User-entered pattern. */
	char *undec; /* User-entered pattern with decoration stripped. */
	char *raw;   /* Raw stripped value (regular expression). */
	int cflags;  /* Regular expression compilation flags. */
	MType type : 2;             /* Type of the matcher's pattern. */
	unsigned int full_path : 1; /* Matches full path instead of just file name. */
	unsigned int negated : 1;   /* Whether match is inverted. */
	unsigned int fglobs : 1;    /* Whether this matcher is a special case of
	                               globs ("faster" globs) that is optimized. */
	regex_t regex; /* The expression in compiled form, unless matcher is empty. */
};

static int is_full_path(const char expr[], int re, int glob, int *strip);
static MType determine_type(const char expr[], int re, int glob,
		int glob_by_def, int *strip);
static int compile_expr(matcher_t *m, int strip, int cs_by_def,
		const char on_empty_re[], char **error);
static int parse_glob(matcher_t *m, int strip, char **error);
static int is_fglobs(char expr[]);
static int parse_re(matcher_t *m, int strip, int cs_by_def,
		const char on_empty_re[], char **error);
static void free_matcher_items(matcher_t *matcher);
static int fglobs_matches(const matcher_t *matcher, const char path[]);
static int fglobs_includes(const matcher_t *matcher, const matcher_t *like);
static int is_negated(const char **expr);
static int is_re_expr(const char expr[], int allow_empty);
static int is_globs_expr(const char expr[]);
static int is_mime_expr(const char expr[]);
TSTATIC int matcher_is_fast(const matcher_t *matcher);

matcher_t *
matcher_alloc(const char expr[], int cs_by_def, int glob_by_def,
		const char on_empty_re[], char **error)
{
	const char *orig_expr = expr;
	const int negated = is_negated(&expr);
	const int re = is_re_expr(expr, 1), glob = is_globs_expr(expr);
	int strip;
	const int full_path = is_full_path(expr, re, glob, &strip);

	MType type = determine_type(expr, re, glob, glob_by_def, &strip);
	matcher_t *matcher, m = {
		.type = type,
		.raw = strdup(expr + strip),
		.negated = negated,
		.full_path = full_path,
	};

	*error = NULL;

	if(m.raw == NULL)
	{
		replace_string(error, "Failed to allocate memory for match expr copy.");
		return NULL;
	}

	m.expr = strdup(orig_expr);
	if(m.expr == NULL)
	{
		free(m.raw);
		replace_string(error, "Failed to clone match expr.");
		return NULL;
	}

	if(compile_expr(&m, strip, cs_by_def, on_empty_re, error) != 0)
	{
		free(m.raw);
		free(m.expr);
		free(m.undec);
		return NULL;
	}

	matcher = malloc(sizeof(*matcher));
	if(matcher == NULL)
	{
		replace_string(error, "Failed allocate memory for matcher.");
		free_matcher_items(&m);
	}
	else
	{
		*matcher = m;
	}

	return matcher;
}

/* Checks whether this is full path match expression.  Sets *strip to width of
 * markers before and after pattern.  Returns non-zero if so, otherwise zero is
 * returned. */
static int
is_full_path(const char expr[], int re, int glob, int *strip)
{
	int full_path = 0;

	*strip = 0;

	if(re)
	{
		const char *const s = strrchr(expr, '/') - 1;
		full_path = (expr[1] == '/' && s > expr + 1 && *s == '/');
		*strip = full_path ? 2 : 1;
	}
	else if(glob)
	{
		full_path = (expr[1] == '{' && expr[strlen(expr) - 2] == '}');
		*strip = full_path ? 2 : 1;
	}

	return full_path;
}

/* Determines type of the matcher for given expression.  Returns the type. */
static MType
determine_type(const char expr[], int re, int glob, int glob_by_def, int *strip)
{
	if(re)
	{
		return MT_REGEX;
	}
	if(glob)
	{
		return MT_GLOBS;
	}
	if(is_mime_expr(expr))
	{
		*strip = 1;
		return MT_MIME;
	}
	return glob_by_def ? MT_GLOBS : MT_REGEX;
}

/* Compiles m->raw into regular expression.  Also replaces global with
 * equivalent regexp.  Returns zero on success or non-zero on error with *error
 * containing description of it. */
static int
compile_expr(matcher_t *m, int strip, int cs_by_def, const char on_empty_re[],
		char **error)
{
	int err;

	switch(m->type)
	{
		case MT_MIME:
		case MT_GLOBS:
			if(parse_glob(m, strip, error) != 0)
			{
				return 1;
			}
			break;
		case MT_REGEX:
			if(parse_re(m, strip, cs_by_def, on_empty_re, error) != 0)
			{
				return 1;
			}
			break;
	}

	if(m->fglobs || m->raw[0] == '\0')
	{
		/* This is a faster glob or an empty matcher and we don't compile "". */
		return 0;
	}

	err = regexp_compile(&m->regex, m->raw, m->cflags);
	if(err != 0)
	{
		replace_string(error, get_regexp_error(err, &m->regex));
		regfree(&m->regex);
		return 1;
	}

	return 0;
}

/* Replaces global with equivalent regexp and setups flags.  Returns zero on
 * success or non-zero on error with *error containing description of it. */
static int
parse_glob(matcher_t *m, int strip, char **error)
{
	if(strip != 0)
	{
		/* Cut off trailing "}" or "}}". */
		m->raw[strlen(m->raw) - strip] = '\0';
	}

	m->undec = strdup(m->raw);
	if(m->undec == NULL)
	{
		replace_string(error, "Failed to allocate memory.");
		return 1;
	}

	if(is_fglobs(m->raw))
	{
		m->fglobs = 1;
		return 0;
	}

	char *re = globs_to_regex(m->raw);
	if(re == NULL)
	{
		replace_string(error, "Failed to convert globs into regexp.");
		return 1;
	}

	free(m->raw);
	m->raw = re;

	m->cflags = REG_EXTENDED | REG_ICASE;
	return 0;
}

/* Checks whether expression (command-separated list of glob patterns) can be
 * implemented without regular expressions.  Returns non-zero if so, otherwise
 * zero is returned. */
static int
is_fglobs(char expr[])
{
	if(expr[0] == '\0')
	{
		return 0;
	}

	expr = strdup(expr);

	char *glob = expr, *state = NULL;
	while((glob = split_and_get_dc(glob, &state)) != NULL)
	{
		const size_t pos = strcspn(glob, "[?*");
		if(glob[pos] == '\0')
		{
			continue;
		}
		if(glob[pos] == '*' &&
				glob[pos + 1 + strcspn(glob + pos + 1, "[?*")] == '\0')
		{
			continue;
		}
		break;
	}

	free(expr);
	return (glob == NULL);
}

/* Parses regexp flags.  Returns zero on success or non-zero on error with
 * *error containing description of it. */
static int
parse_re(matcher_t *m, int strip, int cs_by_def, const char on_empty_re[],
		char **error)
{
	if(strip != 0)
	{
		char *flags = strrchr(m->raw, '/');
		flags = (flags == NULL) ? (m->raw + strlen(m->raw)) : (flags + 1);

		if(parse_case_flag(flags, &cs_by_def) != 0)
		{
			replace_string(error, "Failed to parse flags.");
			return 1;
		}

		/* Cut the flags off by replacing trailing slash(es) with null character. */
		flags[-strip] = '\0';
	}

	if(m->raw[0] == '\0')
	{
		const char *const mark = (strip == 2) ? "//" : (strip == 1 ? "/" : "");

		replace_string(&m->raw, on_empty_re);
		put_string(&m->expr, format_str("%s%s%s%s", mark, on_empty_re, mark,
				m->expr + strip*2));
	}

	m->undec = strdup(m->raw);
	if(m->undec == NULL)
	{
		replace_string(error, "Failed to allocate memory.");
		return 1;
	}

	m->cflags = REG_EXTENDED | (cs_by_def ? 0 : REG_ICASE);
	return 0;
}

matcher_t *
matcher_clone(const matcher_t *matcher)
{
	matcher_t *const clone = malloc(sizeof(*clone));
	if(clone == NULL)
	{
		return NULL;
	}

	*clone = *matcher;
	clone->expr = strdup(matcher->expr);
	clone->raw = strdup(matcher->raw);
	clone->undec = strdup(matcher->undec);

	if(clone->expr == NULL || clone->raw == NULL || clone->undec == NULL)
	{
		matcher_free(clone);
		return NULL;
	}

	/* Don't compile regex for faster globs or empty matcher. */
	if(!clone->fglobs && clone->raw[0] != '\0')
	{
		if(regexp_compile(&clone->regex, matcher->raw, matcher->cflags) != 0)
		{
			matcher_free(clone);
			return NULL;
		}
	}

	return clone;
}

void
matcher_free(matcher_t *matcher)
{
	if(matcher != NULL)
	{
		free_matcher_items(matcher);
		free(matcher);
	}
}

/* Frees all resources allocated by the matcher, but not the matcher itself.
 * matcher can't be NULL. */
static void
free_matcher_items(matcher_t *matcher)
{
	if(!matcher->fglobs && matcher->raw != NULL && !matcher_is_empty(matcher))
	{
		/* Regex is compiled only for non-empty matchers of unoptimized patterns. */
		regfree(&matcher->regex);
	}
	free(matcher->expr);
	free(matcher->raw);
	free(matcher->undec);
}

int
matcher_matches(const matcher_t *matcher, const char path[])
{
	if(matcher_is_empty(matcher))
	{
		/* Empty matcher matches nothing, not even an empty string. */
		return 0;
	}

	if(matcher->type == MT_MIME)
	{
		path = get_mimetype(path, 1);
		if(path == NULL)
		{
			return matcher->negated;
		}
	}
	else if(!matcher->full_path)
	{
		path = get_last_path_component(path);
	}

	if(matcher->fglobs)
	{
		return fglobs_matches(matcher, path);
	}

	return (regexec(&matcher->regex, path, 0, NULL, 0) == 0)^matcher->negated;
}

/* Checks whether given path/name is matched by a fglobs matcher.  Returns
 * non-zero if so, otherwise zero is returned. */
static int
fglobs_matches(const matcher_t *matcher, const char path[])
{
	char *globs = strdup(matcher->raw);
	char *glob = globs, *state = NULL;
	while((glob = split_and_get_dc(glob, &state)) != NULL)
	{
		const char *asterisk = until_first(glob, '*');

		/* Literal with no special characters. */
		if(*asterisk == '\0')
		{
			if(strcasecmp(path, glob) == 0)
			{
				break;
			}
			continue;
		}

		size_t pos = asterisk - glob;
		/* `*something` */
		if(pos == 0)
		{
			if(path[0] != '.' && ends_with_case(path + 1, glob + 1))
			{
				break;
			}
			continue;
		}

		/* Literal with one escaped asterisk. */
		if(asterisk[-1] == '\\')
		{
			/* Compare parts around '\\' to ignore it. */
			--pos;
			if(strncasecmp(path, glob, pos) == 0 &&
					strcasecmp(path + pos, glob + pos + 1) == 0)
			{
				break;
			}
			continue;
		}

		/* Either `something*` or `some*thing`.  First case work here by matching
		 * its empty suffix. */
		if(strncasecmp(path, glob, pos) == 0 &&
				ends_with_case(path + pos, glob + pos + 1))
		{
			break;
		}
	}
	free(globs);
	return (glob != NULL)^matcher->negated;
}

int
matcher_is_empty(const matcher_t *matcher)
{
	return (matcher->raw[0] == '\0');
}

const char *
matcher_get_expr(const matcher_t *matcher)
{
	return matcher->expr;
}

const char *
matcher_get_undec(const matcher_t *matcher)
{
	return matcher->undec;
}

int
matcher_includes(const matcher_t *matcher, const matcher_t *like)
{
	if(matcher->type != like->type || matcher->fglobs != like->fglobs ||
			matcher->cflags != like->cflags || matcher->full_path != like->full_path)
	{
		return 0;
	}

	if(matcher->fglobs)
	{
		return fglobs_includes(matcher, like);
	}

	return (matcher->cflags & REG_ICASE)
	     ? (strcasestr(matcher->raw, like->raw) != NULL)
	     : (strstr(matcher->raw, like->raw) != NULL);
}

/* Checks whether matcher matches at least superset of what like is matching
 * for two fglobs matchers.  Returns non-zero if so, otherwise zero is
 * returned. */
static int
fglobs_includes(const matcher_t *matcher, const matcher_t *like)
{
	char *like_globs_copy = strdup(like->raw);

	int all_matched = 1;
	char *like_glob = like_globs_copy, *like_state = NULL;
	while((like_glob = split_and_get_dc(like_glob, &like_state)) != NULL)
	{
		char *mglobs_copy = strdup(matcher->raw);
		char *mglob = mglobs_copy, *mstate = NULL;
		while((mglob = split_and_get_dc(mglob, &mstate)) != NULL)
		{
			if(strcasecmp(like_glob, mglob) == 0)
			{
				break;
			}
		}
		free(mglobs_copy);

		if(mglob == NULL)
		{
			all_matched = 0;
			break;
		}
	}

	free(like_globs_copy);
	return all_matched;
}

/* Checks whether *expr specifies negated pattern.  Adjusts pointer if so.
 * Returns non-zero if so, otherwise zero is returned. */
static int
is_negated(const char **expr)
{
	if(**expr == '!' &&
			(is_re_expr(*expr + 1, 1) || is_globs_expr(*expr + 1) ||
			 is_mime_expr(*expr + 1)))
	{
		++*expr;
		return 1;
	}
	return 0;
}

/* Checks whether expr is a regular expression file name pattern.  Returns
 * non-zero if so, otherwise zero is returned. */
static int
is_re_expr(const char expr[], int allow_empty)
{
	const char *e = strrchr(expr, '/');
	return expr[0] == '/'                        /* Starts with slash. */
	    && e != NULL && e != expr                /* Has second slash. */
	    && (allow_empty || e - expr > 1);        /* Not empty pattern. */
}

/* Checks whether expr is a glob file name pattern.  Returns non-zero if so,
 * otherwise zero is returned. */
static int
is_globs_expr(const char expr[])
{
	return surrounded_with(expr, '{', '}') && expr[2] != '\0';
}

/* Checks whether expr is a mime type pattern.  Returns non-zero if so,
 * otherwise zero is returned. */
static int
is_mime_expr(const char expr[])
{
	return surrounded_with(expr, '<', '>') && expr[2] != '\0';
}

int
matcher_is_full_path(const matcher_t *matcher)
{
	return matcher->full_path;
}

TSTATIC int
matcher_is_fast(const matcher_t *matcher)
{
	return matcher->fglobs;
}

/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 noexpandtab cinoptions-=(0 : */
/* vim: set cinoptions+=t0 filetype=c : */
Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/vifm

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/vifm

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master