1
0
Fork 0
mirror of https://github.com/NixOS/nix synced 2025-06-30 15:48:00 +02:00

nix-env: Add regular expression support in selectors

So you can now do things like:

  $ nix-env -qa '.*zip.*'
  $ nix-env -qa '.*(firefox|chromium).*'
This commit is contained in:
Eelco Dolstra 2014-10-03 18:47:16 +02:00
parent 3800f441e4
commit 104e55bb7f
5 changed files with 165 additions and 23 deletions

View file

@ -1,5 +1,6 @@
#include "names.hh"
#include "util.hh"
#include "regex.hh"
namespace nix {
@ -32,7 +33,10 @@ DrvName::DrvName(const string & s) : hits(0)
bool DrvName::matches(DrvName & n)
{
if (name != "*" && name != n.name) return false;
if (name != "*") {
Regex regex(name);
if (!regex.matches(n.name)) return false;
}
if (version != "" && version != n.version) return false;
return true;
}

33
src/libutil/regex.cc Normal file
View file

@ -0,0 +1,33 @@
#include "regex.hh"
#include "types.hh"
namespace nix {
Regex::Regex(const string & pattern)
{
/* Patterns must match the entire string. */
int err = regcomp(&preg, ("^(" + pattern + ")$").c_str(), REG_NOSUB | REG_EXTENDED);
if (err) throw Error(format("compiling pattern %1%: %2%") % pattern % showError(err));
}
Regex::~Regex()
{
regfree(&preg);
}
bool Regex::matches(const string & s)
{
int err = regexec(&preg, s.c_str(), 0, 0, 0);
if (err == 0) return true;
else if (err == REG_NOMATCH) return false;
throw Error(format("matching string %1%: %2%") % s % showError(err));
}
string Regex::showError(int err)
{
char buf[256];
regerror(err, &preg, buf, sizeof(buf));
return string(buf);
}
}

22
src/libutil/regex.hh Normal file
View file

@ -0,0 +1,22 @@
#pragma once
#include "types.hh"
#include <sys/types.h>
#include <regex.h>
namespace nix {
class Regex
{
public:
Regex(const string & pattern);
~Regex();
bool matches(const string & s);
private:
regex_t preg;
string showError(int err);
};
}