id stringlengths 20 30 | source stringclasses 1
value | chunk_index int64 0 520k | token_count int32 154 512 | content stringlengths 185 57.5k |
|---|---|---|---|---|
rust_dataset_chunk_519600 | rust_dataset.txt | 519,600 | 512 | FormFieldKind::Select => FormFieldKind::Select,
ProtobufFormFieldKind::Toggle => FormFieldKind::Toggle,
ProtobufFormFieldKind::Number => FormFieldKind::Number,
ProtobufFormFieldKind::Choose => FormFieldKind::Choose,
}
}
}
impl From<FormField> for ProtobufFormField {
... |
rust_dataset_chunk_519601 | rust_dataset.txt | 519,601 | 512 | o::into),
fields: spec
.fields
.into_iter()
.map(FormField::try_from)
.collect::<Result<Vec<_>, _>>()?,
submit_label: spec.submit_label,
cancel_label: spec.cancel_label,
})
}
}
impl From<PromptPlacement> for... |
rust_dataset_chunk_519602 | rust_dataset.txt | 519,602 | 512 | .corner
.as_deref()
.and_then(|corner| corner.parse().ok())
.map(PromptPlacement::Corner)
.ok_or("Invalid prompt corner"),
}
}
}
impl From<PromptSpec> for prompt_request::Spec {
fn from(spec: PromptSpec) -> Self {
match spec {
... |
rust_dataset_chunk_519603 | rust_dataset.txt | 519,603 | 512 | <prompt_request::Spec> for PromptSpec {
type Error = &'static str;
fn try_from(spec: prompt_request::Spec) -> Result<Self, &'static str> {
Ok(match spec {
prompt_request::Spec::Confirm(spec) => PromptSpec::Confirm {
message: spec.message.map(Into::into).unwrap_or_default(),
... |
rust_dataset_chunk_519604 | rust_dataset.txt | 519,604 | 512 | illis() as u64),
default: request.default,
placement: request.placement.map(Into::into),
focused: request.focused,
capture_all_keys: request.capture_all_keys,
outside_click: request
.outside_click
.map(|outside_click| outside_cl... |
rust_dataset_chunk_519605 | rust_dataset.txt | 519,605 | 512 | PromptValue {
type Error = &'static str;
fn try_from(value: ProtobufPromptValue) -> Result<Self, &'static str> {
Ok(match value.value.ok_or("Empty prompt value")? {
prompt_value::Value::Text(text) => PromptValue::Text(text),
prompt_value::Value::Number(number) => PromptValue::Nu... |
rust_dataset_chunk_519606 | rust_dataset.txt | 519,606 | 512 | .try_into()?),
None => None,
})
},
prompt_result::Result::Error(message) => PromptResult::Error(message),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::data::{OutsideClick, PopupCorner, StyledText};
use std::collections::BTr... |
rust_dataset_chunk_519607 | rust_dataset.txt | 519,607 | 512 | ::info("About", "Text").placement(PromptPlacement::Mouse));
let colored = StyledText {
text: "Delete x?".to_owned(),
indices: vec![vec![], vec![], vec![], vec![7]],
};
round_trip_request(PromptRequest::confirm(colored.clone()));
round_trip_request(PromptRequest::i... |
rust_dataset_chunk_519608 | rust_dataset.txt | 519,608 | 512 | PromptResult::Answered(PromptValue::Bool(false)),
PromptResult::Answered(PromptValue::Choice("c".to_owned())),
PromptResult::Answered(PromptValue::Choices(vec![])),
PromptResult::Answered(PromptValue::Form(form)),
PromptResult::Confirmed(true),
PromptResult::... |
rust_dataset_chunk_519609 | rust_dataset.txt | 519,609 | 512 | Action) -> bool {
let known_name = (0..=LAST_ACTION_NAME_OF_0_45 as i32).contains(&action.name)
&& !ACTION_NAMES_0_45_CANNOT_DECODE
.iter()
.any(|name| *name as i32 == action.name);
if !known_name {
return false;
}
match &action.optional_payload {
Some(Opt... |
rust_dataset_chunk_519610 | rust_dataset.txt | 519,610 | 512 | let adapted = event_for_0_45_plugin(event)?;
let bytes = adapted.encode_to_vec();
Some(ProtobufEvent::decode(bytes.as_slice()).expect("the bytes decode"))
}
#[test]
fn every_action_the_0_45_decoder_knew_still_passes_and_newer_ones_do_not() {
for name in 0..=LAST_ACTION_NAME_OF_0_45... |
rust_dataset_chunk_519611 | rust_dataset.txt | 519,611 | 512 | UpdatePayload { current_mode, .. })) => {
assert_eq!(current_mode, InputMode::RenameTab as i32);
assert!(input_mode_known_to_0_45(current_mode));
},
other => panic!("unexpected payload {:?}", other),
}
}
#[test]
fn other_mode_updates_reach_a_0... |
rust_dataset_chunk_519612 | rust_dataset.txt | 519,612 | 512 | action = ProtobufAction {
name: ActionName::SwitchModeForAllClients as i32,
optional_payload: Some(OptionalPayload::SwitchModeForAllClientsPayload(
SwitchToModePayload {
input_mode: InputMode::RenameSession as i32,
},
)),
}... |
rust_dataset_chunk_519613 | rust_dataset.txt | 519,613 | 512 | match resize {
Resize::Increase => ResizeAction::Increase as i32,
Resize::Decrease => ResizeAction::Decrease as i32,
},
direction: None,
})
}
}
impl TryFrom<ProtobufResize> for ResizeStrategy {
type Error = &'static str;
fn try_from(protobuf_... |
rust_dataset_chunk_519614 | rust_dataset.txt | 519,614 | 512 | Some(ResizeDirection::Right) => Ok(Direction::Right),
Some(ResizeDirection::Up) => Ok(Direction::Up),
Some(ResizeDirection::Down) => Ok(Direction::Down),
None => Err("No direction for the given index"),
}
}
}
impl TryFrom<Direction> for ProtobufMoveDirection ... |
rust_dataset_chunk_519615 | rust_dataset.txt | 519,615 | 512 | (context: EventContext) -> Self {
ProtobufEventContext {
slot_id: context.slot_id,
client_id: context.client_id,
}
}
}
impl From<ProtobufEventContext> for EventContext {
fn from(context: ProtobufEventContext) -> Self {
EventContext {
slot_id: context.... |
rust_dataset_chunk_519616 | rust_dataset.txt | 519,616 | 512 | 32,
client_id: None,
slot_ids,
},
}
}
}
impl From<ProtobufRenderRequest> for RenderResponse {
fn from(request: ProtobufRenderRequest) -> Self {
match ProtobufRenderKind::try_from(request.kind) {
Ok(ProtobufRenderKind::All) => RenderRespons... |
rust_dataset_chunk_519617 | rust_dataset.txt | 519,617 | 512 | (deprecated)]
impl TryFrom<Style> for ProtobufStyle {
type Error = &'static str;
fn try_from(style: Style) -> Result<Self, &'static str> {
let s = ProtobufStyling::try_from(style.colors)?;
let palette = Palette::try_from(style.colors).map_err(|_| "malformed style payload")?;
Ok(ProtobufS... |
rust_dataset_chunk_519618 | rust_dataset.txt | 519,618 | 512 | BorderStyle {
top: ProtobufLineStyle::from(border_style.top) as i32,
right: ProtobufLineStyle::from(border_style.right) as i32,
bottom: ProtobufLineStyle::from(border_style.bottom) as i32,
left: ProtobufLineStyle::from(border_style.left) as i32,
rounded_corner... |
rust_dataset_chunk_519619 | rust_dataset.txt | 519,619 | 512 | _array.map(|arr| MultiplayerColors {
player_1: arr[0],
player_2: arr[1],
player_3: arr[2],
player_4: arr[3],
player_5: arr[4],
player_6: arr[5],
player_7: arr[6],
player_8: arr[7],
player_9: arr[8],
player_10: arr[9],
})
}
#[macro_expo... |
rust_dataset_chunk_519620 | rust_dataset.txt | 519,620 | 512 | list_unselected: color_definitions!(proto, list_unselected, 6),
list_selected: color_definitions!(proto, list_selected, 6),
frame_unselected,
frame_selected: color_definitions!(proto, frame_selected, 6),
frame_highlight: color_definitions!(proto, frame_highlight, 6),
... |
rust_dataset_chunk_519621 | rust_dataset.txt | 519,621 | 512 | .try_into()?,
ribbon_unselected: style.ribbon_unselected.try_into()?,
ribbon_selected: style.ribbon_selected.try_into()?,
ribbon_hover: ribbon_hover_vec?,
table_title: style.table_title.try_into()?,
table_cell_unselected: style.table_cell_unselected.try_into()... |
rust_dataset_chunk_519622 | rust_dataset.txt | 519,622 | 512 | white: protobuf_palette
.white
.ok_or("malformed palette payload")?
.try_into()?,
orange: protobuf_palette
.orange
.ok_or("malformed palette payload")?
.try_into()?,
gray: protobuf_palette
... |
rust_dataset_chunk_519623 | rust_dataset.txt | 519,623 | 512 | .try_into()?),
..Default::default()
})
}
}
impl TryFrom<ProtobufColor> for PaletteColor {
type Error = &'static str;
fn try_from(protobuf_color: ProtobufColor) -> Result<Self, &'static str> {
match ProtobufColorType::try_from(protobuf_color.color_type).ok() {
Some(Pr... |
rust_dataset_chunk_519624 | rust_dataset.txt | 519,624 | 512 | ::Dark => Ok(ProtobufThemeHue::Dark),
}
}
}
impl TryFrom<ProtobufThemeHue> for ThemeHue {
type Error = &'static str;
fn try_from(protobuf_theme_hue: ProtobufThemeHue) -> Result<Self, &'static str> {
match protobuf_theme_hue {
ProtobufThemeHue::Light => Ok(ThemeHue::Light),
... |
rust_dataset_chunk_519625 | rust_dataset.txt | 519,625 | 512 | (LineStyle::Double),
top: None,
right: Some(LineStyle::Heavy),
bottom: None,
left: Some(LineStyle::Dashed),
rounded_corners: Some(false),
};
let protobuf: ProtobufBorderStyleOverride = border_style_override.into();
let decoded: BorderSt... |
rust_dataset_chunk_519626 | rust_dataset.txt | 519,626 | 512 | StyledText};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use std::collections::{BTreeMap, HashSet};
use std::fmt;
use std::str::FromStr;
use std::time::Duration;
pub const PROMPT_PLUGIN_ALIAS: &str = "prompt";
pub const PROMPT_PLUGIN_URL: &str = "zellij:prompt";
pub cons... |
rust_dataset_chunk_519627 | rust_dataset.txt | 519,627 | 512 | Clone, Copy, PartialEq, Eq, Hash)]
pub enum PromptElement {
Confirm,
Choose,
Input,
Number,
Toggle,
Select,
Menu,
Form,
Notify,
Info,
}
impl PromptElement {
pub fn name(&self) -> &'static str {
match self {
PromptElement::Confirm => "confirm",
... |
rust_dataset_chunk_519628 | rust_dataset.txt | 519,628 | 512 | : Some(label.into()),
emphasis: vec![],
}
}
pub fn emphasized(mut self, indices: impl IntoIterator<Item = usize>) -> Self {
self.emphasis = indices.into_iter().collect();
self
}
pub fn emphasize_first(self, count: usize) -> Self {
self.emphasized(0..count)
... |
rust_dataset_chunk_519629 | rust_dataset.txt | 519,629 | 512 | (Some(label), true) => Value::Array(vec![
Value::String(item.value.clone()),
Value::String(label.clone()),
]),
(_, false) => Value::Array(vec![
Value::String(item.value.clone()),
item.label.clone().map(Value... |
rust_dataset_chunk_519630 | rust_dataset.txt | 519,630 | 512 | {
let value = value.trim();
let invalid = || {
format!(
"invalid duration '{}', expected for example 30s, 500ms, 2m or 1h",
value
)
};
let split_at = value
.find(|c: char| !(c.is_ascii_digit() || c == '.'))
.unwrap_or(value.len());
let (number... |
rust_dataset_chunk_519631 | rust_dataset.txt | 519,631 | 512 | match object.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s.clone())),
Some(_) => Err(field_error(id, format!("\"{}\" must be a string", key))),
}
}
fn optional_bool(object: &Map<String, Value>, key: &str, id: &str) -> Result<bool, String> {
match ... |
rust_dataset_chunk_519632 | rust_dataset.txt | 519,632 | 512 | " => FormFieldKind::Toggle,
"number" => FormFieldKind::Number,
"choose" => FormFieldKind::Choose,
other => {
return Err(field_error(
&id,
format!(
"unknown type \"{}\", expected input, select, toggle, num... |
rust_dataset_chunk_519633 | rust_dataset.txt | 519,633 | 512 | }
if let Some(default) = &default {
match kind {
FormFieldKind::Input => {
if !default.is_string() {
return Err(field_error(&id, "\"default\" must be a string"));
}
},
FormFieldKind::Select => match default.as_str() ... |
rust_dataset_chunk_519634 | rust_dataset.txt | 519,634 | 512 | ,
})
}
pub fn parse_form_spec(text: &str) -> Result<FormSpec, String> {
let value: Value = serde_json::from_str(text)
.map_err(|e| format!("invalid form description: not valid JSON: {}", e))?;
let object = value
.as_object()
.ok_or_else(|| "invalid form description: must be a JSON o... |
rust_dataset_chunk_519635 | rust_dataset.txt | 519,635 | 512 | .to_owned()),
Some(Value::String(s)) if !s.is_empty() => Ok(s.clone()),
Some(_) => Err(format!(
"invalid form description: \"buttons.{}\" must be a non-empty string",
key
)),
}
};
... |
rust_dataset_chunk_519636 | rust_dataset.txt | 519,636 | 512 | pub fn new(id: impl Into<String>, kind: FormFieldKind, label: impl Into<String>) -> Self {
FormField {
id: id.into(),
kind,
label: label.into(),
required: false,
validate: None,
placeholder: None,
options: vec![],
... |
rust_dataset_chunk_519637 | rust_dataset.txt | 519,637 | 512 | pub fn step(mut self, step: i64) -> Self {
self.step = Some(step);
self
}
pub fn default_value(mut self, value: impl Into<Value>) -> Self {
self.default = Some(value.into());
self
}
fn to_json(&self) -> Value {
let mut object = Map::new();
object.insert("... |
rust_dataset_chunk_519638 | rust_dataset.txt | 519,638 | 512 | styles_to_json(&message.indices),
);
}
}
object.insert(
"fields".to_owned(),
Value::Array(self.fields.iter().map(|field| field.to_json()).collect()),
);
let mut buttons = Map::new();
buttons.insert(
... |
rust_dataset_chunk_519639 | rust_dataset.txt | 519,639 | 512 | message: StyledText,
options: Vec<String>,
},
Menu {
items: Vec<ChoiceItem>,
remember: Option<String>,
padded: bool,
},
Form {
spec: FormSpec,
},
Notify {
message: StyledText,
show_pane_name: bool,
show_tab_name: bool,
},
I... |
rust_dataset_chunk_519640 | rust_dataset.txt | 519,640 | 512 | PromptValue::Choices` with `multi()`.
pub fn choose(items: impl IntoIterator<Item = impl Into<ChoiceItem>>) -> Self {
PromptRequest::new(PromptSpec::Choose {
items: items.into_iter().map(Into::into).collect(),
multi: false,
selected: vec![],
})
}
/// A lin... |
rust_dataset_chunk_519641 | rust_dataset.txt | 519,641 | 512 | self
}
/// Several fields at once. The answer is `PromptValue::Form`, keyed by field id.
pub fn form(fields: Vec<FormField>) -> Self {
PromptRequest::form_spec(FormSpec::new(fields))
}
/// A form with its own title and button labels. The answer is `PromptValue::Form`.
pub fn form_spec(s... |
rust_dataset_chunk_519642 | rust_dataset.txt | 519,642 | 512 | }
self
}
pub fn buttons(mut self, submit: impl Into<String>, cancel: impl Into<String>) -> Self {
if let PromptSpec::Form { spec } = &mut self.spec {
spec.submit_label = submit.into();
spec.cancel_label = cancel.into();
}
self
}
pub fn time... |
rust_dataset_chunk_519643 | rust_dataset.txt | 519,643 | 512 | pub fn placeholder(mut self, text: impl Into<String>) -> Self {
if let PromptSpec::Input { placeholder, .. } = &mut self.spec {
*placeholder = Some(text.into());
}
self
}
pub fn validate(mut self, pattern: impl Into<String>) -> Self {
if let PromptSpec::Input { valid... |
rust_dataset_chunk_519644 | rust_dataset.txt | 519,644 | 512 | >) {
let mut args = BTreeMap::new();
fn insert(args: &mut BTreeMap<String, String>, key: &str, value: String) {
args.insert(key.to_owned(), value);
}
fn set_styled(args: &mut BTreeMap<String, String>, message: &StyledText) {
insert(args, ARG_MESSAGE, message.text.... |
rust_dataset_chunk_519645 | rust_dataset.txt | 519,645 | 512 | mut args, ARG_MIN, min.to_string());
}
if let Some(max) = max {
insert(&mut args, ARG_MAX, max.to_string());
}
insert(&mut args, ARG_STEP, step.to_string());
},
PromptSpec::Toggle { message } => {
... |
rust_dataset_chunk_519646 | rust_dataset.txt | 519,646 | 512 | >) -> Option<String> {
match (min, max) {
(Some(min), Some(max)) if value < min || value > max => {
Some(format!("Must be between {} and {}", min, max))
},
(Some(min), None) if value < min => Some(format!("Must be at least {}", min)),
(None, Some(max)) if value > max => S... |
rust_dataset_chunk_519647 | rust_dataset.txt | 519,647 | 512 | (default)
.map(Some)
.map_err(|e| format!("default: {}", e)),
None => Ok(None),
}
}
pub fn parse_request(
name: &str,
args: &BTreeMap<String, String>,
payload: Option<&str>,
) -> Result<PipePrompt, String> {
let element = PromptElement::from_str(name)?;
let timeo... |
rust_dataset_chunk_519648 | rust_dataset.txt | 519,648 | 512 | selected: args
.get(ARG_SELECTED)
.map(|s| decode_list(s))
.unwrap_or_default(),
}
},
PromptElement::Input => {
let validate = args.get(ARG_VALIDATE).cloned();
if let Some(pattern) = &validate {
... |
rust_dataset_chunk_519649 | rust_dataset.txt | 519,649 | 512 | .map(|i| decode_items(i))
.unwrap_or_default();
if items.is_empty() {
return Err("menu needs at least one item".to_owned());
}
PromptSpec::Menu {
items,
remember: args.get(ARG_REMEMBER).cloned(),
padded:... |
rust_dataset_chunk_519650 | rust_dataset.txt | 519,650 | 512 | )]
mod tests {
use super::*;
#[test]
fn only_info_prompts_close_on_an_outside_click_unless_asked() {
assert_eq!(
PromptRequest::info("About this", "Details").outside_click_or_default(),
OutsideClick::Close
);
assert_eq!(
PromptRequest::confirm("Go... |
rust_dataset_chunk_519651 | rust_dataset.txt | 519,651 | 512 | Label", false),
ChoiceItem::plain("v\tLabel")
);
}
#[test]
fn the_example_form_description_is_accepted() {
let spec = parse_form_spec(
r#"{ "title": "New project",
"fields": [
{ "id": "name", "type": "input", "label": "Name", "validate":... |
rust_dataset_chunk_519652 | rust_dataset.txt | 519,652 | 512 | "#,
)
.unwrap();
assert_eq!(
styled.message,
Some(StyledText {
text: "Delete Alt n?".to_owned(),
indices: vec![vec![], vec![], vec![], vec![7, 8, 9, 10, 11]],
})
);
assert_eq!(parse_form_spec(&styled.to_json()), ... |
rust_dataset_chunk_519653 | rust_dataset.txt | 519,653 | 512 | {
let spec = parse_form_spec(
r#"{ "fields": [ { "id": "name", "type": "input", "validate": "(" } ] }"#,
)
.unwrap();
let error = check_form_patterns(&spec, |p| {
if p == "(" {
Err("unclosed group".to_owned())
} else {
... |
rust_dataset_chunk_519654 | rust_dataset.txt | 519,654 | 512 | 10]],
}),
PromptRequest::input(StyledText {
text: "Name of the branch".to_owned(),
indices: vec![vec![12, 13]],
}),
PromptRequest::select(
StyledText {
text: "License".to_owned(),
indi... |
rust_dataset_chunk_519655 | rust_dataset.txt | 519,655 | 512 | parsed = parse_request(&name, &args, payload.as_deref()).unwrap();
let mut expected = request.clone();
expected.placement = None;
expected.focused = !request.is_notice();
assert_eq!(parsed.request, expected);
assert!(!parsed.json && !parsed.null && !parsed.st... |
rust_dataset_chunk_519656 | rust_dataset.txt | 519,656 | 512 | ().unwrap_err().contains("\"a\""));
}
#[test]
fn caller_args_are_stripped() {
let mut args = BTreeMap::new();
args.insert(CALLER_PANE_TITLE_ARG.to_owned(), "fake".to_owned());
args.insert(ARG_TITLE.to_owned(), "t".to_owned());
strip_caller_args(&mut args);
assert_eq!... |
rust_dataset_chunk_519657 | rust_dataset.txt | 519,657 | 512 | )?;
Ok(())
}
/// Save session token for a server (upsert)
pub fn save_session_token(server_url: &str, session_token: &str) -> Result<()> {
let db_path = get_db_path()?;
// Set file permissions to 0600 if creating new file
let is_new = !db_path.exists();
let conn = Connection::open(&db_path)?... |
rust_dataset_chunk_519658 | rust_dataset.txt | 519,658 | 512 | Serializer};
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "snake_case")]
#[value(rename_all = "snake_case")]
pub enum CliEventType {
#[value(skip)]
InitialState,
PaneOpened,
PaneClosed,
PaneFocused,
PaneRename... |
rust_dataset_chunk_519659 | rust_dataset.txt | 519,659 | 512 | ok_or_else(|| format!("Unknown event type: {}", s))
}
}
impl std::fmt::Display for CliEventType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
pub fn input_mode_name(mode: InputMode) -> String {
format!("{:?}", mode).to_lowercase()
}
... |
rust_dataset_chunk_519660 | rust_dataset.txt | 519,660 | 512 | pub tab_id: usize,
pub position: usize,
pub name: String,
pub is_fullscreen_active: bool,
pub is_sync_panes_active: bool,
pub are_floating_panes_visible: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CliClientState {
pub client_id: ClientId,
pub is_we... |
rust_dataset_chunk_519661 | rust_dataset.txt | 519,661 | 512 | _id: Option<usize>,
cwd: String,
},
PaneCommandChanged {
#[serde(with = "pane_id_string")]
pane_id: PaneId,
tab_id: Option<usize>,
command: Vec<String>,
is_foreground: bool,
},
TabCreated {
tab: CliTabState,
},
TabClosed {
tab_id: u... |
rust_dataset_chunk_519662 | rust_dataset.txt | 519,662 | 512 | Moved,
CliEvent::TabFocused { .. } => CliEventType::TabFocused,
CliEvent::ModeChanged { .. } => CliEventType::ModeChanged,
CliEvent::ClientAttached { .. } => CliEventType::ClientAttached,
CliEvent::ClientDetached { .. } => CliEventType::ClientDetached,
CliEven... |
rust_dataset_chunk_519663 | rust_dataset.txt | 519,663 | 512 | _id, *previous_tab_id],
CliEvent::TabCreated { tab } => vec![tab.tab_id],
_ => vec![],
}
}
pub fn is_scoped(&self) -> bool {
self.pane_id().is_some() || !self.tab_ids().is_empty()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct... |
rust_dataset_chunk_519664 | rust_dataset.txt | 519,664 | 512 | _id, Some(p.tab_id)))
.collect();
let tabs = tabs
.into_iter()
.filter(|t| {
self.tab_ids.contains(&t.tab_id)
|| panes.iter().any(|p| p.tab_id == t.tab_id)
})
... |
rust_dataset_chunk_519665 | rust_dataset.txt | 519,665 | 512 | }
assert!("nope".parse::<CliEventType>().is_err());
}
#[test]
fn filter_by_type() {
let filter = CliEventFilter {
event_types: vec![CliEventType::PaneOpened],
..Default::default()
};
assert!(filter.accepts(&CliEvent::PaneOpened {
pane: pa... |
rust_dataset_chunk_519666 | rust_dataset.txt | 519,666 | 512 | let tab = |tab_id: usize| CliTabState {
tab_id,
position: tab_id,
name: format!("Tab #{}", tab_id),
is_fullscreen_active: false,
is_sync_panes_active: false,
are_floating_panes_visible: false,
};
let scoped = filter.scope_initial_s... |
rust_dataset_chunk_519667 | rust_dataset.txt | 519,667 | 512 | : Option<String>,
pub startup_card: Option<StartupCard>,
#[serde(default)]
pub disconnect_others: bool,
}
impl SwitchContext {
pub fn with_startup_card(startup_card: StartupCard) -> Self {
SwitchContext {
startup_card: Some(startup_card),
..Default::default()
}
... |
rust_dataset_chunk_519668 | rust_dataset.txt | 519,668 | 512 | mut self, from: &str, to: &str) {
if from == to {
return;
}
self.back.retain(|name| name != from && name != to);
self.forward.clear();
self.back.push(from.to_owned());
self.last = Some(from.to_owned());
self.trim();
}
pub fn target(&self, histo... |
rust_dataset_chunk_519669 | rust_dataset.txt | 519,669 | 512 | eref() {
if !keep(last) {
self.last = None;
}
}
}
pub fn rename_session(&mut self, old_name: &str, new_name: &str) {
for name in self.back.iter_mut().chain(self.forward.iter_mut()) {
if name == old_name {
*name = new_name.to_own... |
rust_dataset_chunk_519670 | rust_dataset.txt | 519,670 | 512 | history = self.clone();
history.remove_session(current);
SessionHistoryInfo {
current: current.to_owned(),
previous: history.previous().map(|s| s.to_owned()),
back: history.back,
forward: history.forward,
..Default::default()
}
}
... |
rust_dataset_chunk_519671 | rust_dataset.txt | 519,671 | 512 | = SessionHistory::default();
visit(&mut history, &["a", "b", "c"]);
assert_eq!(history.back, vec!["a", "b"]);
assert_eq!(history.previous(), Some("b"));
assert!(history.forward.is_empty());
}
#[test]
fn revisiting_a_session_moves_it_instead_of_repeating_it() {
let m... |
rust_dataset_chunk_519672 | rust_dataset.txt | 519,672 | 512 | SessionHistory::default();
visit(&mut history, &["a", "b", "c"]);
history.go_back("c");
history.record_switch("b", "d");
assert!(history.forward.is_empty());
assert_eq!(history.back, vec!["a", "b"]);
}
#[test]
fn ended_sessions_are_removed() {
let mut histor... |
rust_dataset_chunk_519673 | rust_dataset.txt | 519,673 | 512 | own.apply(HistoryMove::Toggle, "api"),
Some("web".to_owned())
);
}
#[test]
fn adopting_replaces_own_forward_entries_and_drops_the_current_one() {
let mut own = SessionHistory {
back: vec!["a".to_owned(), "here".to_owned()],
forward: vec!["f1".... |
rust_dataset_chunk_519674 | rust_dataset.txt | 519,674 | 512 | ".to_owned()),
};
own.adopt(handed, "here");
assert_eq!(own.back, vec!["y", "w", "x"]);
assert_eq!(own.forward, vec!["f", "z"]);
assert_eq!(own.last.as_deref(), Some("x"));
assert_eq!(own.go_back("here"), Some("x".to_owned()));
}
#[test]
fn adopting_at_the_li... |
rust_dataset_chunk_519675 | rust_dataset.txt | 519,675 | 512 | () {
let names: Vec<String> = (0..20).map(|i| format!("h{}", i)).collect();
let handed = SessionHistory {
back: names.clone(),
forward: vec![],
last: names.last().cloned(),
};
let mut own = SessionHistory {
back: (0..20).map(|i| format!("o{... |
rust_dataset_chunk_519676 | rust_dataset.txt | 519,676 | 512 | BTreeMap<String, String>,
}
impl SessionContext {
pub fn fact(&self, name: &str) -> Option<String> {
match name {
FACT_DIRECTORY => self.folder.as_ref().map(|f| folder_key(f)),
FACT_GIT_REPO => self.repo.clone(),
FACT_GIT_BRANCH => self.branch.clone(),
FACT_... |
rust_dataset_chunk_519677 | rust_dataset.txt | 519,677 | 512 | ),
}
impl std::fmt::Display for SessionIndexError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SessionIndexError::Database(e) => write!(f, "session index database error: {}", e),
SessionIndexError::Io(e) => write!(f, "session index io error: {}... |
rust_dataset_chunk_519678 | rust_dataset.txt | 519,678 | 512 | _SOCK_DIR, sock_dir_overridden))
}
pub fn hostname() -> Option<String> {
#[cfg(unix)]
{
let mut buffer = [0u8; 256];
let result =
unsafe { libc::gethostname(buffer.as_mut_ptr() as *mut libc::c_char, buffer.len()) };
if result != 0 {
return None;
}
... |
rust_dataset_chunk_519679 | rust_dataset.txt | 519,679 | 512 | (), None),
};
if name.is_empty() || !seen.insert(name.clone()) {
None
} else {
Some((name, label))
}
})
.collect()
}
pub fn parse_fact_lines(stdout: &str) -> BTreeMap<String, String> {
stdout
.lines()
.f... |
rust_dataset_chunk_519680 | rust_dataset.txt | 519,680 | 512 | matching_facts: matching,
script_label: None,
});
}
}
match then {
ThenOrder::Recent => rest.sort_by(compare_within_tier),
ThenOrder::Alphabetical => rest.sort_by(|a, b| a.row.name.cmp(&b.row.name)),
ThenOrder::None => rest.clear(),
... |
rust_dataset_chunk_519681 | rust_dataset.txt | 519,681 | 512 | |row| row.get(0))?;
let integrity: String = conn.query_row("PRAGMA quick_check", [], |row| row.get(0))?;
if integrity != "ok" {
return Err(SessionIndexError::Database(rusqlite::Error::InvalidQuery));
}
let had_table: bool = conn
.query_row(
"SELEC... |
rust_dataset_chunk_519682 | rust_dataset.txt | 519,682 | 512 | _LAYOUT_FILE_NAME);
let Ok(metadata) = std::fs::metadata(&layout_file) else {
continue;
};
let Some(name) = path.file_name().map(|n| n.to_string_lossy().to_string()) else {
continue;
};
let modified = metadata
.m... |
rust_dataset_chunk_519683 | rust_dataset.txt | 519,683 | 512 | repo,
worktree,
branch,
facts: serde_json::from_str(&facts).unwrap_or_default(),
},
created_at: created_at.max(0) as u64,
last_used_at: last_used_at.max(0) as u64,
})
}
const COLUMNS: &'static str =
... |
rust_dataset_chunk_519684 | rust_dataset.txt | 519,684 | 512 | params![name, now as i64],
)?;
Ok(inserted > 0)
}
pub fn touch(&self, name: &str, now: u64) -> Result<bool> {
let changed = self.conn.execute(
"UPDATE sessions SET last_used_at = ?2 WHERE name = ?1 AND last_used_at <> ?2",
params![name, now as i64],
... |
rust_dataset_chunk_519685 | rust_dataset.txt | 519,685 | 512 | }
/// Give the session with this id a new name. Nothing on disk is renamed: the socket and the
/// cache folder stay named by the id.
pub fn rename_by_id(&self, id: &str, new_name: &str, now: u64) -> Result<()> {
let transaction = Transaction::new_unchecked(&self.conn, TransactionBehavior::Immedia... |
rust_dataset_chunk_519686 | rust_dataset.txt | 519,686 | 512 | self, transaction: &Transaction) -> Result<String> {
loop {
let candidate = crate::sessions::generate_session_id();
if query_session_name(transaction, &candidate)?.is_none()
&& !self.files_named(&candidate)
{
return Ok(candidate);
}... |
rust_dataset_chunk_519687 | rust_dataset.txt | 519,687 | 512 | ::COLUMNS
);
self.query_rows(&sql, &[&prefix, &upper])
}
pub fn rows_exactly_in_folder(&self, folder: &Path) -> Result<Vec<SessionRow>> {
let key = folder_key(folder);
let sql = format!("SELECT {} FROM sessions WHERE folder = ?1", Self::COLUMNS);
self.query_rows(&sql, &[... |
rust_dataset_chunk_519688 | rust_dataset.txt | 519,688 | 512 | let sql = format!(
"SELECT {} FROM sessions ORDER BY name ASC LIMIT ?1",
Self::COLUMNS
);
self.query_rows(&sql, &[&(limit as i64)])
}
pub fn rows_for_names(&self, names: &[String]) -> Result<Vec<SessionRow>> {
let mut rows = vec![];
for name in names {
... |
rust_dataset_chunk_519689 | rust_dataset.txt | 519,689 | 512 | : u64,
) -> Vec<Candidate> {
let mut seen = HashSet::new();
let mut candidates = vec![];
for row in rows {
if row.name == exclude || !seen.insert(row.name.clone()) {
continue;
}
match self.session_state(&row.name) {
Some(sta... |
rust_dataset_chunk_519690 | rust_dataset.txt | 519,690 | 512 | (SessionRow {
name: name.clone(),
context: SessionContext::default(),
created_at: now,
last_used_at: 0,
});
}
}
let extra = limit.saturating_sub(rows.len().min(limit));
if extra > 0 {
... |
rust_dataset_chunk_519691 | rust_dataset.txt | 519,691 | 512 | (conn: &Connection, name: &str) -> Result<Option<String>> {
Ok(conn
.query_row(
"SELECT COALESCE(id, name) FROM sessions WHERE name = ?1",
params![name],
|row| row.get(0),
)
.optional()?)
}
fn query_session_name(conn: &Connection, id: &str) -> Result<Opti... |
rust_dataset_chunk_519692 | rust_dataset.txt | 519,692 | 512 | mut dead: Vec<String> = match std::fs::read_dir(cache_dir) {
Ok(entries) => entries
.filter_map(|entry| entry.ok())
.filter(|entry| entry.path().is_dir())
.filter_map(|entry| entry.file_name().into_string().ok())
.filter(|id| {
!live_sessions.cont... |
rust_dataset_chunk_519693 | rust_dataset.txt | 519,693 | 512 | ).ok())
.unwrap_or_default()
}
/// Socket filenames are session ids; `names_by_id` maps them to session names (an id without an
/// entry is the name of a session that predates ids).
pub fn running_session_names_in(
sock_dir: &Path,
names_by_id: &HashMap<String, String>,
) -> Vec<String> {
let Ok(e... |
rust_dataset_chunk_519694 | rust_dataset.txt | 519,694 | 512 | !(bench, index_file_name(bench_dir, true));
assert_ne!(bench, index_file_name(other_bench_dir, true));
}
struct TestIndex {
index: SessionIndex,
root: tempfile::TempDir,
}
impl TestIndex {
fn new() -> Self {
let root = tempfile::tempdir().unwrap();
... |
rust_dataset_chunk_519695 | rust_dataset.txt | 519,695 | 512 | rows_in_folder(Path::new("/work/api"))
.unwrap()
.into_iter()
.map(|r| r.name)
.collect();
names.sort();
assert_eq!(names, vec!["same".to_owned(), "sub".to_owned()]);
let exact: Vec<String> = test
.index
.rows_exactly_in_fol... |
rust_dataset_chunk_519696 | rust_dataset.txt | 519,696 | 512 | "missing".to_owned(),
])
.unwrap();
assert_eq!(deleted, 2);
assert!(test.index.get("renamed").unwrap().is_none());
assert!(test.index.get("plain").unwrap().is_none());
assert!(test.index.get("kept").unwrap().is_some());
}
#[cfg(unix)]
... |
rust_dataset_chunk_519697 | rust_dataset.txt | 519,697 | 512 | assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].row.name, "alive");
assert_eq!(candidates[0].state, SessionState::Resumable);
assert!(test.index.get("gone").unwrap().is_none());
}
#[test]
fn tiers_follow_the_default_rule_order() {
let mut test = TestIndex::new();
... |
rust_dataset_chunk_519698 | rust_dataset.txt | 519,698 | 512 | 3)),
("unrelated".to_owned(), None),
]
);
assert_eq!(
ranked[0].matching_facts,
vec!["directory".to_owned(), "git_branch".to_owned()]
);
assert_eq!(ranked[2].matching_facts, vec!["directory".to_owned()]);
}
#[test]
fn a_sub... |
rust_dataset_chunk_519699 | rust_dataset.txt | 519,699 | 512 | rank_candidates(&target, &rules, ThenOrder::None, candidates, &[]);
let names: Vec<String> = ranked
.iter()
.map(|r| r.candidate.row.name.clone())
.collect();
assert_eq!(
names,
vec![
"older-running".to_owned(),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.