text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
<|fim_suffix|> DB::shouldReceive('table')->andThrow(new Exception());
$resp = $this->get('/status');
$resp->assertStatus(500);
$resp->assertJson([
'database' => false,
]);
}
public function test_returns_500_status_and_false_on_wrong_cache_return()
{
... | fim | BookStackApp/BookStack | php |
<|fim_suffix|>{
$errMessage = $response->getData(true)['error']['message'] ?? '';
return str_contains($errMessage, 'do not have permission');
}
return $response->status() === 302
&& $response->headers->get('Location') === url('/')
&& str_starts_with(sessi... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\Theme;
use BookStack\Activity\ActivityType;
use BookStack\Activity\DispatchWebhookJob;
use BookStack\Activity\Models\Webhook;
use BookStack\Entities\Models\Book;
use BookStack\Entities\Models\Page;
use BookStack\Entities\Tools\PageContent;
use BookStack\Facades\Theme;
use BookStack... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\Theme;
use BookStack\Exceptions\ThemeException;
use BookStack\Facades\Theme;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;
class LogicalThemeTest extends TestCase
{
public function test_theme_functions_file_used_and_app_boot_event_... | fim | BookStackApp/BookStack | php |
<|fim_suffix|>ce="' . $nonce . '">hellofromcustomscript</script>', false);
});
}
protected function usingModuleFolder(callable $callback): void
{
$this->usingThemeFolder(function (string $themeFolder) use ($callback) {
$moduleFolderPath = theme_path('modules/test-module');
... | fim | BookStackApp/BookStack | php |
<|fim_suffix|>$this->asEditor()->get($page->getUrl('/export/html'));
$resp->assertSee($bodyStartStr);
$resp->assertSee($bodyEndStr);
});
}
public function test_login_and_register_message_template_files_can_be_used()
{
$loginMessage = 'Welcome to this instance, login ... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\Unit;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Tests\TestCase;
/**
* Class ConfigTest
* Many of the tests here are to check on tweaks made
* to maintain backwards compatibility.
*/
... | fim | BookStackApp/BookStack | php |
<|fim_suffix|>ying upon in the framework.
* This is primarily to keep track of certain bits of functionality that
* may be used in important areas such as to enforce permissions.
*/
class FrameworkAssumptionTest extends TestCase
{
public function test_scopes_error_if_not_existing()
{
$this->expectExc... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\Unit;
use BookStack\Activity\Tools\IpFormatter;
use Tests\TestCase;
class IpFormatterTest extends TestCase
{
public function test_ips_formatted_as_expected()
{
$this->assertEquals('192.123.45.5', (new IpFormatter('192.123.45.5', 4))->format());
$this->asser... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\Unit;
use BookStack\Access\Oidc\OidcIdToken;
use BookStack\Access\Oidc\OidcInvalidTokenException;
use Tests\Helpers\OidcJwtHelper;
use Tests\TestCase;
class OidcIdTokenTest extends TestCase
{
public function test_valid_token_passes_validation()
{
$token = new OidcI... | fim | BookStackApp/BookStack | php |
<|fim_suffix|> id="content">doggos</pre>'],
'<pre id="content">doggos</pre>',
);
}
public function test_block_content_in_allowable_parent_element()
{
$this->runParserTest(
'<div>{{@45#content}}</div>',
['45' => '<pre id="content">doggos</pre>'],
... | fim | BookStackApp/BookStack | php |
<|fim_suffix|>e.html');
$this->files->deleteAllAttachmentFiles();
}
public function test_file_upload_works_when_local_secure_restricted_is_in_use()
{
config()->set('filesystems.attachments', 'local_secure_restricted');
$page = $this->entities->page();
$fileName = 'upload_t... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\Uploads;
use BookStack\Exceptions\HttpFetchException;
use BookStack\Uploads\UserAvatars;
use BookStack\Users\Models\User;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Tests\TestCase;
class AvatarTest extends TestCase
{
... | fim | BookStackApp/BookStack | php |
<|fim_suffix|> 'image' => 'image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4gEcDCo5iYNs+gAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAAFElEQVQI12O0jN/KgASYGFABqXwAZtoBV6Sl3hIAAAAASUVORK5CYII=',
]);
};
$upload()->assert... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\Uploads;
use BookStack\Uploads\ImageStorage;
use Tests\TestCase;
class ImageStorageTest extends TestCase
{
public function test_local_image_storage_sets_755_directory_permissions()
{
if (PHP_OS_FAMILY !== 'Linux') {
$this->markTestSkipped('Test only wor... | fim | BookStackApp/BookStack | php |
<|fim_suffix|> config()->set('filesystems.images', 'local_secure_restricted');
$this->asEditor();
$galleryFile = $this->files->uploadedImage('my-secure-restricted-thumb-test-test.png');
$page = $this->entities->page();
$upload = $this->call('POST', '/images/gallery', ['uploaded_to' =>... | fim | BookStackApp/BookStack | php |
<?php
namespace Tests;
use BookStack\Http\Request;
class UrlTest extends TestCase
{
public function test_url_helper_takes_custom_url_into_account()
{
$this->runWithEnv(['APP_URL' => 'http://example.com/bookstack'], function () {
$this->assertEquals('http://example.com/bookstack/books', ur... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\User;
use BookStack\Activity\ActivityType;
use BookStack\Users\Models\Role;
use BookStack\Users\Models\User;
use Tests\TestCase;
class RoleManagementTest extends TestCase
{
public function test_cannot_delete_admin_role()
{
$adminRole = Role::getRole('admin');
... | fim | BookStackApp/BookStack | php |
<|fim_suffix|>l($resp)->assertElementContains('#api_tokens', $token->expires_at->format('Y-m-d'));
}
public function test_secret_shown_once_after_creation()
{
$editor = $this->users->editor();
$resp = $this->asAdmin()->followingRedirects()->post("/api-tokens/{$editor->id}/create", $this->te... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\User;
use BookStack\Access\Mfa\MfaValue;
use BookStack\Activity\ActivityType;
use BookStack\Permissions\Permission;
use Tests\TestCase;
class UserManagementMfaTest extends TestCase
{
public function test_configured_mfa_options_visible_on_user_edit()
{
$editor = $th... | fim | BookStackApp/BookStack | php |
<?php
namespace Tests\User;
use BookStack\Access\Mfa\MfaValue;
use BookStack\Access\SocialAccount;
use BookStack\Access\UserInviteException;
use BookStack\Access\UserInviteService;
use BookStack\Activity\ActivityType;
use BookStack\Activity\Models\Activity;
use BookStack\Activity\Models\Comment;
use BookStack\Activit... | fim | BookStackApp/BookStack | php |
<|fim_suffix|>hange()
{
$editor = $this->users->editor();
$resp = $this->actingAs($editor)->get('/my-account/auth');
$resp->assertSee('Change Password');
$this->withHtml($resp)->assertElementExists('form[action$="/my-account/auth/password"]');
$password = Str::random();
... | fim | BookStackApp/BookStack | php |
<?php
namespace Tests\User;
use Tests\TestCase;
class UserPreferencesTest extends TestCase
{
public function test_update_sort_preference()
{
$editor = $this->users->editor();
$this->actingAs($editor);
$updateRequest = $this->patch('/preferences/change-sort/books', [
'sort... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\User;
use BookStack\Activity\ActivityType;
use BookStack\Facades\Activity;
use BookStack\Users\Models\User;
use Tests\TestCase;
class UserProfileTest extends TestCase
{
/**
* @var User
*/
protected $user;
protected function setUp(): void
{
parent... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\User;
use BookStack\Permissions\Permission;
use BookStack\Users\Models\User;
use Tests\TestCase;
class UserSearchTest extends TestCase
{
public function test_select_search_matches_by_name()
{
$viewer = $this->users->viewer();
$admin = $this->users->admin();... | fim | BookStackApp/BookStack | php |
<|fim_suffix|>1 13:00:00 BST', $result);
}
public function test_iso_with_timezone_works_from_non_utc_dates()
{
$formatter = new DateFormatter('Asia/Shanghai');
$dateTime = new Carbon('2025-06-10 15:25:00', 'America/New_York');
$result = $formatter->absolute($dateTime);
$thi... | fim | BookStackApp/BookStack | php |
<|fim_prefix|><?php
namespace Tests\Util;
use BookStack\Util\HtmlToPla<|fim_suffix|> {
$html = <<<HTML
<p><strong>H</strong><a>e</a><sup>l</sup><span>l</span><em>o</em></p>
HTML;
$expected = <<<TEXT
Hello
TEXT;
$this->runTest($html, $expected);
}
protected function runTest(string $ht... | fim | BookStackApp/BookStack | php |
<|fim_suffix|>al=a.example.com', 'result' => false,],
['config' => 'https://*.example.com', 'url' => 'https://a.com/a/b#example.com', 'result' => false,],
['config' => 'https://a.*.example.com', 'url' => 'https://a.b.c.example.com/c/d', 'result' => true,],
['config' => 'https://examp... | fim | BookStackApp/BookStack | php |
fn main() {
set_git_revision_hash();
set_windows_exe_options();
}
/// Embed a Windows manifest and set some linker options.
///
/// The main reason for this is to enable long path support on Windows. This
/// still, I believe, requires enabling long path support in the registry. But
/// if that's enabled, then... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use std::{
ffi::{OsStr, OsString},
fs::File,
io,
path::{Path, PathBuf},
process::Command,
};
use globset::{Glob, GlobSet, GlobSetBuilder};
use crate::process::{CommandError, CommandReader, CommandReaderBuilder};
/// A builder for a matcher that determines which files get decompresse... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> Vec::unescape_bytes(s)
}
/// Unescapes an OS string.
///
/// This is like [`unescape`], but accepts an OS string.
///
/// Note that this first lossily decodes the given OS string as UTF-8. That
/// is, an escaped string (the thing given) should be valid UTF-8.
pub fn unescape_os(string: &OsStr) -> Vec<u... | fim | BurntSushi/ripgrep | rust |
use std::{ffi::OsString, io};
/// Returns the hostname of the current system.
///
/// It is unusual, although technically possible, for this routine to return
/// an error. It is difficult to list out the error conditions, but one such
/// possibility is platform support.
///
/// # Platform specific behavior
///
/// O... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/// An error that occurs when parsing a human readable size description.
///
/// This error provides an end user friendly message describing why the
/// description couldn't be parsed and what the expected format is.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseSizeError {
original: String,
... | fim | BurntSushi/ripgrep | rust |
/*!
This crate provides common routines used in command line applications, with a
focus on routines useful for search oriented applications. As a utility
library, there is no central type or function. However, a key focus of this
crate is to improve failure modes and provide user friendly error messages
when things go ... | fim | BurntSushi/ripgrep | rust |
use std::{ffi::OsStr, io, path::Path};
use bstr::io::BufReadExt;
use crate::escape::{escape, escape_os};
/// An error that occurs when a pattern could not be converted to valid UTF-8.
///
/// The purpose of this error is to give a more targeted failure mode for
/// patterns written by end users that are not valid UT... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>dle =
std::thread::spawn(move || stderr_to_command_error(&mut stderr));
StderrReader::Async(Some(handle))
}
/// Create a reader for stderr that reads contents synchronously.
fn sync(stderr: process::ChildStderr) -> StderrReader {
StderrReader::Sync(stderr)
}
... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use std::io::{self, IsTerminal};
use termcolor::HyperlinkSpec;
/// A writer that supports coloring with either line or block<|fim_suffix|> => w.is_synchronous(),
BlockBuffered(ref w) => w.is_synchronous(),
}
}
}
<|fim_middle|> buffering.
#[derive(Debug)]
pub struct StandardStream... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
Provides completions for ripgrep's CLI for the bash shell.
*/
use crate::flags::defs::FLAGS;
const TEMPLATE_FULL: &'static str = "
_rg() {
local i cur prev opts cmds
COMPREPLY=()
cur=\"${COMP_WORDS[COMP_CWORD]}\"
prev=\"${COMP_WORDS[COMP_CWORD-1]}\"
cmd=\"\"
opts=\"\"
for i in ${COMP_... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
Provides completions for ripgrep's CLI for the fish shell.
*/
use crate::flags::{CompletionType, defs::FLAGS};
const TEMPLATE: &'static str = "complete -c rg !SHORT! -l !LONG! -d '!DOC!'";
const TEMPLATE_NEGATED: &'static str = "complete -c rg -l !NEGATED! -n '__rg_contains_opt !LONG! !SHORT!' -d '!... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>h;
<|fim_prefix|>/*!
Modules for generating com<|fim_middle|>pletions for various shells.
*/
static ENCODINGS: &'static str = include_str!("encodings.sh");
pub(super) mod bash;
pub(super) mod fish;
pub(super) mod powershell;
pub(super) mod zs<|endoftext|> | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
Provides completions for ripgrep's CLI for PowerShell.
*/
use crate::flags::defs::FLAGS;
const TEMPLATE: &'static str = "
using namespace System.Management.Automation
using namespace System.Management.Automation.Language
Register-ArgumentCompleter -Native -CommandName 'rg' -ScriptBlock {
param($w... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
Provides completions for ripgrep's CLI for the zsh shell.
Unlike completion short for other shells (at time of writing), zsh's
completions for ripgrep are maintained by hand. This is because:
1. They are lovingly written by an expert in such things.
2. Are much higher in quality than the ones below ... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> }
Err(err) => {
errs.push(anyhow::anyhow!("{line_number}: {err}"));
}
}
Ok(true)
})?;
Ok((args, errs))
}
#[cfg(test)]
mod tests {
use super::parse_reader;
use std::ffi::OsString;
#[test]
fn basic() {
let (args, e... | fim | BurntSushi/ripgrep | rust |
/*!
Provides routines for generating ripgrep's "short" and "long" help
documentation.
The short version is used when the `-h` flag is given, while the long version
is used when the `--help` flag is given.
*/
use std::{collections::BTreeMap, fmt::Write};
use crate::flags::{Category, Flag, defs::FLAGS, doc::version};
... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> r"This flag can be disabled with \fB\-\-{negated}\fP."
);
}
}
writeln!(out, ".RE");
}
<|fim_prefix|>/*!
Provides routines for generating ripgrep's man page in `roff` format.
*/
use std::{collections::BTreeMap, fmt::Write};
use crate::flags::{Flag, defs::FLAGS, doc::version};... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
Modules for generating documentation for ripgrep's flags.
*/
pub(crate) mod help;
pub(crate) mod man;
pub(crate) mod version;
/// Searches for `\tag{...}` occurrences in `doc` and calls `replacement` for
/// each such tag found.
///
/// The first argument given to `replacement` is the tag value, `..... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
Provides routines for generating version strings.
Version strings can be just the digits, an overall short one-line description
or something more verbose that includes things like CPU target feature support.
*/
use std::fmt::Write;
/// Generates just the numerical part of the version <|fim_suffix|>... | fim | BurntSushi/ripgrep | rust |
/*!
Provides the definition of high level arguments from CLI flags.
*/
use std::{
collections::HashSet,
path::{Path, PathBuf},
};
use {
bstr::BString,
grep::printer::{ColorSpecs, SummaryKind},
};
use crate::{
flags::lowargs::{
BinaryMode, BoundaryMode, BufferMode, CaseMode, ColorChoice,
... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> of this separator.
///
/// Note that this may return an empty `Vec`.
pub(crate) fn into_bytes(self) -> Vec<u8> {
self.0.into()
}
}
/// The type of logging to do. `Debug` emits some details while `Trace` emits
/// much more.
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum LoggingM... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>fferent, then it indicates a bug, and thus a
/// panic is acceptable.
fn unwrap_value(self) -> OsString {
match self {
FlagValue::Switch(_) => {
unreachable!("got switch but expected flag value")
}
FlagValue::Value(v) => v,
}
... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> // based on whether short or long flag is given.
args.special = Some(SpecialMode::HelpShort);
continue;
}
lexopt::Arg::Short(ch) if ch == 'V' => {
// Special case -V/--version since behavior is differ... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>&& self.dent.path().is_dir()
}
/// Returns true if and only if this haystack points to a file.
fn is_file(&self) -> bool {
self.dent.file_type().map_or(false, |ft| ft.is_file())
}
}
<|fim_prefix|>/*!
Defines a builder for haystacks.
A "haystack" represents something we want to se... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
Defines a super simple logger that works with the `log` crate.
We don't do anything fancy. We just need basic log levels and the ability to
print to stderr. We therefore avoid bringing in extra dependencies just for
this functionality.
*/
use log::Log;
/// The simplest possible logger that logs to ... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
The main entry point into ripgrep.
*/
use std::{io::Write, process::ExitCode};
use ignore::WalkState;
use crate::flags::{HiArgs, SearchMode};
#[macro_use]
mod messages;
mod flags;
mod haystack;
mod logger;
mod search;
// Since Rust no longer uses jemalloc by default, ripgrep will, by default,
//... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
This module defines some macros and some light shared mutable state.
This state is responsible for keeping track of whether we should emit certain
kinds of messages to the user (such as errors) that are distinct from the
standard "debug" or "trace" log messages. This state is specifically set at
star... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
Defines a very high level "search worker" abstraction.
A search worker manages the high level interaction points between the matcher
(i.e., which regex engine is used), the searcher (i.e., how data is actually
read and matched using the regex engine) and the printer. For example, the
search worker is... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
This module benchmarks the glob implementation. For benchmarks on the ripgrep
tool itself, see the benchsuite directory.
*/
#![feature(test)]
extern crate test;
use globset::{Candidate, Glob, GlobMatcher, GlobSet, GlobSetBuilder};
const EXT: &'static str = "some/a/bigger/path/to/the/crazy/needle.tx... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>her(u64);
impl Hasher {
const OFFSET_BASIS: u64 = 0xcbf29ce484222325;
const PRIME: u64 = 0x100000001b3;
}
impl Default for Hasher {
fn default() -> Hasher {
Hasher(Hasher::OFFSET_BASIS)
}
}
impl std::hash::Hasher for Hasher {
fn finish(&self) -> u64 {
self.0
}
... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use std::fmt::Write;
use std::path::{Path, is_separator};
use regex_automata::meta::Regex;
use crate::{Candidate, Error, ErrorKind, new_regex};
/// Describes a matching strategy for a particular pattern.
///
/// This provides a way to more quickly determine whether a pattern matches
/// a particular fi... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>new("*.c").unwrap());
builder.add(Glob::new("src/lib.rs").unwrap());
let set = builder.build().unwrap();
assert!(set.is_match("foo.c"));
assert!(set.is_match("src/foo.c"));
assert!(!set.is_match("foo.rs"));
assert!(!set.is_match("tests/foo.rs"));
as... | fim | BurntSushi/ripgrep | rust |
use std::borrow::Cow;
use bstr::{ByteSlice, ByteVec};
/// The final component of the path, if it is a normal file.
///
/// If the path terminates in `..`, or consists solely of a root of prefix,
/// file_name will return `None`.
pub(crate) fn file_name<'a>(path: &Cow<'a, [u8]>) -> Option<Cow<'a, [u8]>> {
if path.... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use serde::{
de::{Error, SeqAccess, Visitor},
{Deserialize, Deserializer, Serialize, Serializer},
};
use crate::{Glob, GlobSet, GlobSetBuilder};
impl Serialize for Glob {
fn serialize<S: Serializer>(
&self,
serializer: S,
) -> Result<S::Ok, S::Error> {
serializer.... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>search_path(
&matcher,
dent.path(),
printer.sink_with_path(&matcher, dent.path()),
);
if let Err(err) = result {
eprintln!("{}: {}", dent.path().display(), err);
}
}
}
Ok(())
}
<|fim_prefix|... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
ripgrep, as a library.
This library is intended to provide a high level facade to the crates that
make up ripgrep's core searching routines. However, there is no high level
documentation available yet guiding users on how to fit all of the pieces
together.
Ever<|fim_suffix|> grep_matcher as matcher;... | fim | BurntSushi/ripgrep | rust |
use std::{env, io::Write, path::Path};
use {bstr::ByteVec, ignore::WalkBuilder, walkdir::WalkDir};
fn main() {
let mut path = env::args().nth(1).unwrap();
let mut parallel = false;
let mut simple = false;
let (tx, rx) = crossbeam_channel::bounded::<DirEntry>(100);
if path == "parallel" {
p... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/// This list represents the default file types that ripgrep ships with. In
/// general, any file format is fair game, although it should generally be
/// limited to reasonably popular open formats. For other cases, you can add
/// types to each invocation of ripgrep with the '--type-add' flag.
///
/// If... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>r::new().build().add_child(td.path());
assert!(err.is_none());
assert!(ig.matched("baz", false).is_ignore());
assert!(ig.matched("foo", false).is_whitelist());
assert!(ig.matched("bar", false).is_whitelist());
}
#[test]
fn errored() {
let td = tmpdir();... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>}
#[test]
fn parse_excludes_file5() {
let data = bytes("[core]\nexcludesFile = \" \"~/foo/bar \" \"");
assert!(super::parse_excludes_file(&data).is_none());
}
// See: https://github.com/BurntSushi/ripgrep/issues/106
#[test]
fn regression_106() {
gi_from_st... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>create temp dir after {} tries", TRIES))
}
/// Return the underlying path to this temporary directory.
pub fn path(&self) -> &Path {
&self.0
}
}
}
<|fim_prefix|>/*!
The ignore crate provides a fast recursive directory iterator that respects
various filters ... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>ched("baz/a", false).is_whitelist());
assert!(ov.matched("baz/a/b", false).is_whitelist());
}
#[test]
fn allow_directories() {
// This tests that directories are NOT ignored when they are unmatched.
let ov = ov(&["*.rs"]);
assert!(ov.matched("foo.rs", false).is... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>sStr> {
use memchr::memrchr;
use std::os::unix::ffi::OsStrExt;
let path = path.as_ref().as_os_str().as_bytes();
if path.is_empty() {
return None;
} else if path.len() == 1 && path[0] == b'.' {
return None;
} else if path.last() == Some(&b'.') {
return None;... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
The types module provides a way of associating globs on file names to file
types.
This can be used to match specific types of files. For example, among
the default file types provided, the Rust file type is defined to be `*.rs`
with name `rust`. Similarly, the C file type is defined to be `*.{c,h}` w... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>tmp, err) = self.ig.add_child(ent.path());
self.ig = igtmp;
ent.err = err;
return Some(Ok(ent));
}
Ok(WalkEvent::File(ent)) => {
let ent = DirEntry::new_walkdir(ent, None);
l... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use std::path::Path;
use ignore::gitignore::{Gitignore, GitignoreBuilder};
const IGNORE_FILE: &'static str =
"tests/gitignore_matched_path_or_any_parents_tests.gitignore";
fn get_gitignore() -> Gitignore {
let mut builder = GitignoreBuilder::new("ROOT");
let error = builder.add(IGNORE_FILE)... | fim | BurntSushi/ripgrep | rust |
use ignore::gitignore::GitignoreBuilder;
const IGNORE_FILE: &'static str = "tests/gitignore_skip_bom.gitignore";
/// Skip a Byte-Order Mark (BOM) at the beginning of the file, matching Git's
/// behavior.
///
/// Ref: <https://github.com/BurntSushi/ripgrep/issues/2177>
#[test]
fn gitignore_skip_bom() {
let mut bu... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> "testxxxtest",
);
interp!(
interp6,
vec![("foo", 2)],
vec!["", "", "xxx"],
"test $$foo test",
"test $foo test",
);
interp!(
interp7,
vec![("foo", 2)],
vec!["", "", "xxx"],
"test $foo",
"test xxx",
);
... | fim | BurntSushi/ripgrep | rust |
/*!
This crate provides an interface for regular expressions, with a focus on line
oriented search. The purpose of this crate is to provide a low level matching
interface that permits any kind of substring or regex implementation to power
the search routines provided by the
[`grep-searcher`](https://docs.rs/grep-search... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> dst| {
dst.push(b'z');
true
})
.unwrap();
assert_eq!(dst, b"z z");
// Test that replacements respect short circuiting.
dst.clear();
matcher
.replace(b"aa bb cc dd", &mut dst, |_, dst| {
dst.push(b'z');
false
... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>od test_matcher;
<|fim_prefix|>mo<|fim_middle|>d util;
m<|endoftext|> | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>-> Option<Match> {
self.0.pos(i).map(|(s, e)| Match::new(s, e))
}
}
<|fim_prefix|>use std::collections::HashMap;
use {
grep_matcher::{Captures, Match, Matcher, NoCaptures, NoError},
regex::bytes::{CaptureLocations, Regex},
};
#[derive(Debug)]
pub(crate) struct RegexMatcher {
pub ... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>{
ErrorKind::Regex(ref s) => write!(f, "{}", s),
}
}
}
<|fim_prefix|>/// An error that can occur in this crate.
///
/// Generally, this error c<|fim_middle|>orresponds to problems building a regular
/// expression, whether it's in parsing, compilation or a problem with
/// guarante... | fim | BurntSushi/ripgrep | rust |
/*!
An implementation of `grep-matcher`'s `Matcher` trait for
[PCRE2](https://www.pcre.org/).
*/
#![deny(missing_docs)]
pub use pcre2::{is_jit_available, version};
pub use crate::{
error::{Error, ErrorKind},
matcher::{RegexCaptures, RegexMatcher, RegexMatcherBuilder},
};
mod error;
mod matcher;
<|endoftext|... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use std::collections::HashMap;
use {
grep_matcher::{Captures, Match, Matcher},
pcre2::bytes::{CaptureLocations, Regex, RegexBuilder},
};
use crate::error::Error;
/// A builder for configuring the compilation of a PCRE2 regex.
#[derive(Clone, Debug)]
pub struct RegexMatcherBuilder {
builder:... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use termcolor::{Color, ColorSpec, ParseColorError};
/// Returns a default set of color specifications.
///
/// This may change over time, but the color choices are meant to be fairly
/// conservative that work across terminal themes.
///
/// Additional color specifications can be added to the list return... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>ine]
fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {
self.wtr.set_color(spec)
}
#[inline]
fn set_hyperlink(&mut self, link: &HyperlinkSpec) -> io::Result<()> {
self.wtr.set_hyperlink(link)
}
#[inline]
fn reset(&mut self) -> io::Result<()> {
... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use crate::hyperlink::HyperlinkAlias;
/// Aliases to well-known hyperlink schemes.
///
/// These need to be sorted by name.
pub(super) const HYPERLINK_PATTERN_ALIASES: &[HyperlinkAlias] = &[
alias(
"cursor",
"Cursor scheme (cursor://)",
"curso<|fim_suffix|>ritized_alias(
p... | fim | BurntSushi/ripgrep | rust |
use std::{cell::RefCell, io, path::Path, sync::Arc};
use {
bstr::ByteSlice,
termcolor::{HyperlinkSpec, WriteColor},
};
use crate::util::DecimalFormatter;
use self::aliases::HYPERLINK_PATTERN_ALIASES;
mod aliases;
/// Hyperlink configuration.
///
/// This configuration specifies both the [hyperlink format](... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>ink(&matcher))
.unwrap();
let got = printer_contents(&mut printer);
assert!(got.is_empty());
}
#[test]
fn always_begin_end_no_match() {
let matcher = RegexMatcher::new(r"DOES NOT MATCH").unwrap();
let mut printer =
JSONBuilder::new().al... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>h
/// here, since this is only used for data or file paths that are not valid
/// UTF-8.
///
/// [1]: https://tools.ietf.org/html/rfc3548#section-3
fn base64_standard(bytes: &[u8]) -> String {
const ALPHABET: &[u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>at, HyperlinkFormatError, hyperlink_aliases,
},
path::{PathPrinter, PathPrinterBuilder},
standard::{Standard, StandardBuilder, StandardSink},
stats::Stats,
summary::{Summary, SummaryBuilder, SummaryKind, SummarySink},
};
#[cfg(feature = "serde")]
pub use crate::json::{JSON, JSONBuilde... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
", expected, got);
}
}
}
<|fim_prefix|>/// Like assert_eq, but nicer output for long strings.
#[cfg(test)]
#[macro_export]
macro_rules! assert_eq... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>ub fn terminator(&mut self, terminator: u8) -> &mut PathPrinterBuilder {
self.config.terminator = terminator;
self
}
}
/// A printer file paths, with optional color and hyperlink support.
///
/// This printer is very similar to [`Summary`](crate::Summary) in that it
/// principally on... | fim | BurntSushi/ripgrep | rust |
use std::{
ops::{Add, AddAssign},
time::Duration,
};
use crate::util::NiceDuration;
/// Summary statistics produced at the end of a search.
///
/// When statistics are reported by a printer, they correspond to all searches
/// executed with that printer.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub str... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>nwrap();
let got = printer_contents(&mut printer);
assert_eq_printed!("sherlock\x002\n", got);
}
#[test]
fn count_path_separator() {
let matcher = RegexMatcher::new(r"Watson").unwrap();
let mut printer = SummaryBuilder::new()
.kind(SummaryKind::Cou... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>line, we should remove the line terminator.
// Otherwise, it's possible for the regex (via look-around) to observe
// the line terminator and not match because of it.
let mut m = Match::new(0, range.end);
// No need to rember the line terminator as we aren't doing a replace... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>
}
match *ast {
ast::ClassSetItem::Empty(_)
| ast::ClassSetItem::Ascii(_)
| ast::ClassSetItem::Unicode(_)
| ast::ClassSetItem::Perl(_) => {}
ast::ClassSetItem::Literal(ref x) => {
self.from_ast_literal(x);
... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use regex_syntax::hir::{
self, ClassBytesRange, ClassUnicodeRange, Hir, HirKind,
};
use crate::error::{Error, ErrorKind};
/// Returns an error when a sub-expression in `expr` must match `byte`.
pub(crate) fn check(expr: &Hir, byte: u8) -> Result<(), Error> {
assert!(byte.is_ascii(), "ban byte mu... | fim | BurntSushi/ripgrep | rust |
use {
grep_matcher::{ByteSet, LineTerminator},
regex_automata::meta::Regex,
regex_syntax::{
ast,
hir::{self, Hir},
},
};
use crate::{
ast::AstAnalysis, ban, error::Error, non_matching::non_matching_bytes,
strip::strip_from_match,
};
/// Config represents the configuration of a ... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>
write!(f, "the literal {:?} is not allowed in a regex", lit)
}
ErrorKind::InvalidLineTerminator(byte) => {
write!(
f,
"line terminators must be ASCII, but {byte:?} is not",
byte = [byte].as... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>/*!
An implementation of `grep-matcher`'s `Matcher` trait for Rust's <|fim_suffix|>
*/
#![deny(missing_docs)]
pub use crate::{
error::{Error, ErrorKind},
matcher::{RegexCaptures, RegexMatcher, RegexMatcherBuilder},
};
mod ast;
mod ban;
mod config;
mod error;
mod literal;
mod matcher;
mod non_mat... | fim | BurntSushi/ripgrep | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.