libag - 著名的银色搜索者,但是图书馆
几周前,一位朋友问我是否知道在文本和二进制文件中进行递归正则表达式搜索的工具。我立刻想到了 Ag,但不幸的是,ag(1) 是一个程序,而不是一个库。
虽然并非不可能,但解析 Ag 输出会有点令人头疼,而且为每次搜索生成一个新进程听起来很乏味。像 ripgrep(1) 这样的类似工具可以以 JSON 格式输出,这当然使它变得更容易,但我们仍在讨论生成过程和解析输出。
libag就是这样诞生的。 Libag 允许您以正确的方式(或接近正确的方式)使用 ag 搜索引擎(及其设施)。
Libag 旨在尽可能简单,因此将搜索过程分为三个简单的步骤:
初始化所有内部 ag 结构(通过ag_init()
)
执行任意多次搜索(通过ag_search()
)。
清理资源(通过ag_finish()
)。
自定义搜索设置是通过ag_init_config()
和ag_set_config()
完成的。结果是 struct ag_result* 的列表,其中包含文件、匹配列表(包含匹配和与匹配对应的文件偏移量)和标志。
(完整的例子可以在examples/中找到)
#include <libag.h>
...
struct ag_result * * results ;
size_t nresults ;
char * query = "foo" ;
char * paths [ 1 ] = { "." };
/* Initiate Ag library with default options. */
ag_init ();
/* Searches for foo in the current path. */
results = ag_search ( query , 1 , paths , & nresults );
if (! results ) {
printf ( "No result foundn" );
return ( 1 );
}
printf ( "%zu results found\n" , nresults );
/* Show them on the screen, if any. */
for ( size_t i = 0 ; i < nresults ; i ++ ) {
for ( size_t j = 0 ; j < results [ i ] -> nmatches ; j ++ ) {
printf ( "file: %s, match: %sn" ,
results [ i ] -> file , results [ i ] -> matches [ j ] -> match ,
}
}
/* Free all results. */
ag_free_all_results ( results , nresults );
/* Release Ag resources. */
ag_finish ();
...
Libag 打算支持 ag 的所有功能(正在进行中的工作)(或者至少是那些对库有意义的功能)。此外,它还允许通过ag_start_workers()
和ag_stop_workers()
对工作线程进行详细控制(有关更多详细信息,请参阅文档)。
Libag 对其他编程语言(Python 和 Node.js)提供(实验性)绑定支持。有关更多信息和更详细的文档,请参阅绑定/python 和绑定/javascript。
Libag 需要与 ag 相同的依赖项:c99 编译器和库:zlib、lzma 和 pcre。这些库可以一一安装,也可以由包管理器安装。
对于类似 Debian 的发行版,类似:
$ sudo apt install libpcre3-dev zlib1g-dev liblzma-dev
(或遵循此处的 Ag 建议)
解决依赖关系后,克隆存储库并构建。 Libag 支持 Makefile 和 CMake。选择最适合您需求的一种:
$ git clone https://github.com/Theldus/libag.git
$ cd libag/
$ make -j4
# Optionally (if you want to install):
$ make install # (PREFIX and DESTDIR allowed here, defaults to /usr/local/)
$ mkdir build/ && cd build/
$ cmake .. -DCMAKE_BUILD_TYPE=Release
$ make -j4
# Optionally (if you want to install):
$ make install
每个可用例程的详细文档可以在手册页上找到。此外,源代码有广泛的注释(libag.h 是必读的!)。有关绑定和示例的文档可以在此处找到。
完整的示例也可以在示例/文件夹中找到,并与库一起自动构建,以方便您;-)。
Libag 始终向社区开放,并愿意接受贡献,无论是问题、文档、测试、新功能、错误修复、拼写错误等。欢迎加入。
Libag 根据 Apache v2 许可证获得许可。