Skip to content

Instantly share code, notes, and snippets.

@aruthane
Last active March 27, 2021 08:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aruthane/005c6c48f0deb9c4bfc83bc75e0e95f7 to your computer and use it in GitHub Desktop.
Save aruthane/005c6c48f0deb9c4bfc83bc75e0e95f7 to your computer and use it in GitHub Desktop.
D Programming Language port of https://github.com/zserge/glob-grep
#!/usr/bin/env rdmd
import std.stdio : stderr, File, writefln;
import std.file : dirEntries, SpanMode;
import std.string : indexOf;
void main(string[] args)
{
if (args.length != 2)
{
stderr.writefln("USAGE: %s <pattern>", args[0]);
return;
}
walk(".", args[1]);
}
void walk(string path, string pattern)
{
foreach (entry; dirEntries(".", SpanMode.depth))
{
if (entry.isFile)
{
size_t lineNumber;
lineLoop: foreach (line; File(entry.name).byLine())
{
lineNumber++;
if (line.indexOf('\00') > -1)
{
break lineLoop;
}
if (glob(pattern, line.idup))
{
writefln("%s:%d\t%s", entry.name, lineNumber, line);
}
}
}
}
}
bool glob(string pattern, string text)
{
size_t p = 0;
size_t t = 0;
size_t np = 0;
size_t nt = 0;
while (p < pattern.length || t < text.length)
{
if (p < pattern.length)
{
switch (pattern[p])
{
case '*':
np = p;
nt = t + 1;
p += 1;
continue;
case '?':
if (nt < text.length)
{
p += 1;
t += 1;
continue;
}
break;
default:
if (t < text.length && text[t] == pattern[p])
{
p += 1;
t += 1;
continue;
}
}
}
if (nt > 0 && nt <= text.length)
{
p = np;
t = nt;
continue;
}
return false;
}
return true;
}
unittest
{
assert(glob("", ""));
assert(glob("hello", "hello"));
assert(glob("h??lo", "hello"));
assert(glob("h*o", "hello"));
assert(glob("h*ello", "hello"));
assert(glob("*h*o*", "hello world"));
assert(glob("h*o*", "hello world"));
assert(glob("*h*d", "hello world"));
assert(glob("*h*l*w*d", "hello world"));
assert(glob("*h?l*w*d", "hello world"));
assert(!glob("hello", "hi"));
assert(!glob("h?i", "hi"));
assert(!glob("h*l", "hello"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment