Skip to content

Commit

Permalink
chore(docs): convert any comments meant for type/function documentati…
Browse files Browse the repository at this point in the history
…on into actual doc comments and reword some comments
  • Loading branch information
lthoerner committed Aug 31, 2023
1 parent 366e3fc commit 1e11712
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 60 deletions.
18 changes: 8 additions & 10 deletions src/eval/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ use crate::state::{Path, ShellState};
use super::tokenizer::tokenize;
use crate::errors::Result;

// Represents a collection of builtin commands
// Allows for command resolution and execution through aliases
/// Represents a collection of builtin commands
/// Allows for command resolution and execution through aliases
pub struct Dispatcher {
commands: Vec<Builtin>,
}

impl Default for Dispatcher {
// Initializes the Dispatcher with the default shell commands and aliases
/// Initializes the `Dispatcher` with the default shell commands and aliases
#[rustfmt::skip]
fn default() -> Self {
let mut dispatcher = Self::new();
Expand Down Expand Up @@ -47,7 +47,7 @@ impl Dispatcher {
}
}

// Adds a builtin to the Dispatcher
/// Adds a builtin to the `Dispatcher`
fn add_builtin<F: Fn(&mut ShellState, Vec<&str>) -> Result<()> + 'static>(
&mut self,
true_name: &str,
Expand All @@ -58,8 +58,7 @@ impl Dispatcher {
.push(Builtin::new(true_name, aliases, function))
}

// Finds a builtin command by name or alias
// Returns None if the builtin does not exist
/// Attempts to locate a builtin command by name or alias
fn resolve(&self, command_name: &str) -> Option<&Builtin> {
for command in &self.commands {
if command.true_name == command_name {
Expand All @@ -74,7 +73,7 @@ impl Dispatcher {
None
}

// Evaluates and executes a command from a string
/// Evaluates and executes a command from a string
pub fn eval(&self, shell: &mut ShellState, line: &str) -> Result<()> {
let args = tokenize(line);
let command_name = args.get(0).unwrap().as_str();
Expand All @@ -84,8 +83,7 @@ impl Dispatcher {
Ok(())
}

// Resolves and dispatches a command to the appropriate function or external binary
// If the command does not exist, returns None
/// Resolves and dispatches a command to the appropriate builtin or executable
fn dispatch(
&self,
shell: &mut ShellState,
Expand All @@ -97,7 +95,7 @@ impl Dispatcher {
command.run(shell, command_args)
} else {
// If the command is not in the Dispatcher, try to run it as an executable from the PATH
let path = Path::resolve_executable(command_name, &shell.environment.PATH);
let path = Path::try_resolve_executable(command_name, &shell.environment.PATH);
if let Ok(path) = path {
// Check if the file is executable (has the executable bit set)
if let Ok(metadata) = fs_err::metadata(path.path()) {
Expand Down
9 changes: 6 additions & 3 deletions src/eval/readline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use rustyline::{
use crate::errors::{Handle, Result};
use crate::state::ShellState;

/// Helper providing autocomplete, syntax highlighting, and other features to the `LineEditor`
#[derive(Helper, Completer, Hinter, Validator, Highlighter)]
struct LineEditorHelper {
#[rustyline(Completer)]
Expand All @@ -34,12 +35,13 @@ impl LineEditorHelper {
}
}

/// Editor for reading lines of input from the user
pub struct LineEditor {
editor: Editor<LineEditorHelper, DefaultHistory>,
}

impl LineEditor {
// Creates a LineEditor with the default configuration and history file
/// Creates a `LineEditor` with the default configuration and given history file
pub fn new(history_file: &str) -> Result<Self> {
let config = Config::builder()
.history_ignore_space(true)
Expand All @@ -66,7 +68,8 @@ impl LineEditor {
Ok(Self { editor })
}

pub fn prompt_and_read_line(&mut self, shell: &ShellState) -> Option<String> {
/// Prints the shell prompt and reads a line of input from the user
pub fn prompt_and_read_line(&mut self, shell: &ShellState) -> String {
loop {
let input = self.editor.readline(&shell.generate_prompt());
match input {
Expand All @@ -80,7 +83,7 @@ impl LineEditor {
println!("Failed to save history file.");
}

return Some(line);
return line;
} else {
// TODO: Do not reprompt on a blank line
continue;
Expand Down
4 changes: 2 additions & 2 deletions src/eval/symbols.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Separators
// Separator tokens
pub const WHITESPACE: char = ' ';
pub const SEMICOLON: char = ';';
pub const AMPERSAND: char = '&';
Expand All @@ -10,7 +10,7 @@ pub const DOUBLE_QUOTE: char = '"';
pub const BACKSLASH: char = '\\';
pub const DOLLAR: char = '$';

//Operators
// Operator tokens
pub const AND_IF: &str = "&&";
pub const OR_IF: &str = "||";
pub const DSEMI: &str = ";;";
Expand Down
2 changes: 2 additions & 0 deletions src/eval/tokenizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use super::symbols::{
SINGLE_QUOTE, WHITESPACE,
};

/// Separates a line of input into tokens, such as arguments, separators, and operators
pub fn tokenize(input: &str) -> Vec<String> {
let symbols = Symbols::new();

Expand Down Expand Up @@ -133,6 +134,7 @@ pub fn tokenize(input: &str) -> Vec<String> {
tokens
}

/// Pushes the given token to the tokenized list and clears the token buffer
fn delimit_token(tokens: &mut Vec<String>, curr_token: &mut String) {
if !curr_token.is_empty() {
tokens.push(curr_token.clone());
Expand Down
4 changes: 2 additions & 2 deletions src/exec/builtins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ pub fn read_file(_shell: &mut ShellState, args: Vec<&str>) -> Result<()> {

pub fn run_executable(shell: &mut ShellState, mut args: Vec<&str>) -> Result<()> {
let executable_name = args[0].to_owned();
let executable_path = Path::from_str(&executable_name, &shell.environment.HOME)
let executable_path = Path::try_from_str(&executable_name, &shell.environment.HOME)
.replace_err_with_msg(
builtin_err!(FailedToRun),
&format!("Failed to resolve executable path: '{}'", executable_name),
Expand Down Expand Up @@ -264,7 +264,7 @@ pub fn environment_variable(shell: &mut ShellState, args: Vec<&str>) -> Result<(
pub fn edit_path(shell: &mut ShellState, args: Vec<&str>) -> Result<()> {
check_args(&args, 2, "edit-path <append | prepend> <path>")?;
let action = args[0];
let path = Path::from_str(args[1], &shell.environment.HOME).replace_err_with_msg(
let path = Path::try_from_str(args[1], &shell.environment.HOME).replace_err_with_msg(
builtin_err!(FailedToRun),
&format!("Invalid directory: '{}'", args[1]),
)?;
Expand Down
10 changes: 5 additions & 5 deletions src/exec/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ use std::process::Command as Process;
use crate::errors::{Handle, Result};
use crate::state::{Path, ShellState};

// Represents either a builtin (internal command) or an executable (external command)
// A Runnable may be executed by calling its .run() method
/// Represents either a builtin (internal command) or an executable (external command)
/// A `Runnable` may be executed by calling its `.run()` method
pub trait Runnable {
fn run(&self, shell: &mut ShellState, arguments: Vec<&str>) -> Result<()>;
}

// Wrapper type for Vec<String> that makes it easier to read code related to Builtins
/// Wrapper type that makes it easier to read code related to builtins
pub struct Aliases {
aliases: Vec<String>,
}
Expand All @@ -29,7 +29,7 @@ impl Aliases {
}
}

// Represents a builtin function, its name and its aliases
/// Represents a builtin function, its name and its aliases
pub struct Builtin {
pub true_name: String,
pub aliases: Aliases,
Expand Down Expand Up @@ -61,7 +61,7 @@ impl Runnable for Builtin {
}
}

// Represents an external binary/executable
/// Represents an executable (external command)
pub struct Executable {
path: Path,
}
Expand Down
6 changes: 2 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,8 @@ fn main() {

loop {
let line = line_editor.prompt_and_read_line(&shell.read().unwrap());
if let Some(line) = line {
let status = dispatcher.eval(&mut shell.write().unwrap(), &line);
handle_error(status, &mut shell.write().unwrap());
}
let status = dispatcher.eval(&mut shell.write().unwrap(), &line);
handle_error(status, &mut shell.write().unwrap());
}
}

Expand Down
12 changes: 6 additions & 6 deletions src/state/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ use fs_err::File;

use crate::errors::{Handle, Result};

// Represents any settings for the shell, most of which can be configured by the user
/// Represents any settings for the shell, most of which can be configured by the user
pub struct Configuration {
// The truncation length for the prompt
/// The truncation length for the prompt
pub truncation_factor: Option<usize>,
// Whether to show the prompt tick on a new line
/// Whether to show the prompt tick on a new line
pub multi_line_prompt: bool,
// How many directories to store in the back/forward history
/// How many directories to store in the back/forward history
pub history_limit: Option<usize>,
// Whether or not to print out full error messages and status codes when a command fails
/// Whether or not to print out full error messages and status codes when a command fails
pub show_errors: bool,
/// Paths to recursively search for plugins
pub plugin_paths: Vec<PathBuf>,
Expand All @@ -34,7 +34,7 @@ impl Default for Configuration {
}

impl Configuration {
// Scans a configuration file for settings and updates the configuration accordingly
/// Scans a configuration file for settings and updates the configuration accordingly
pub fn from_file(filename: &str) -> Result<Self> {
let filename = PathBuf::from(filename);
let dirname = filename
Expand Down
25 changes: 13 additions & 12 deletions src/state/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use bitflags::bitflags;
use super::path::Path;
use crate::errors::{Handle, Result};

// Identifier enum for safely accessing environment variables
/// Identifier enum for safely accessing environment variables
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EnvVariable {
User,
Expand All @@ -33,7 +33,7 @@ impl Display for EnvVariable {
}

impl EnvVariable {
// Does the same thing as .to_string(), but uses legacy environment variable names
/// Does the same thing as `.to_string()`, but uses legacy environment variable names
fn to_legacy_string(self) -> String {
match self {
Self::User => "USER".to_string(),
Expand All @@ -45,6 +45,7 @@ impl EnvVariable {
}

bitflags! {
/// Flags for updating multiple environment variables at once
pub struct EnvVariables: u8 {
const USER = 0b0001;
const HOME = 0b0010;
Expand All @@ -53,7 +54,7 @@ bitflags! {
}
}

// Represents the shell environment by encapsulating the environment variables
/// Represents the shell environment by encapsulating the environment variables
// * Environment variables are represented in all caps by convention,
// * any fields that are not actual environment variables are represented in the usual snake_case
#[allow(non_snake_case)]
Expand All @@ -75,7 +76,7 @@ impl Environment {
pub fn new() -> Result<Self> {
let USER = get_parent_env_var(EnvVariable::User)?;
let HOME = PathBuf::from(get_parent_env_var(EnvVariable::Home)?);
let CWD = Path::from_str(get_parent_env_var(EnvVariable::Cwd)?.as_str(), &HOME)?;
let CWD = Path::try_from_str(get_parent_env_var(EnvVariable::Cwd)?.as_str(), &HOME)?;
let PATH = convert_path(get_parent_env_var(EnvVariable::Path)?.as_str(), &HOME)?;

Ok(Self {
Expand All @@ -89,7 +90,7 @@ impl Environment {
})
}

// Updates the shell process's environment variables to match the internal representation
/// Updates the shell process's environment variables to match the internal representation
fn update_process_env_vars(&self, vars: EnvVariables) -> Result<()> {
// TODO: How to detect errors here?
if vars.contains(EnvVariables::USER) {
Expand All @@ -109,10 +110,10 @@ impl Environment {
Ok(())
}

// Sets the current working directory and stores the previous working directory
/// Sets the current working directory and stores the previous working directory
pub fn set_CWD(&mut self, new_directory: &str, history_limit: Option<usize>) -> Result<()> {
let starting_directory = self.CWD.clone();
let new_directory = Path::from_str(new_directory, &self.HOME)?;
let new_directory = Path::try_from_str(new_directory, &self.HOME)?;

// Add the old directory to the history, avoiding duplicates
if new_directory != starting_directory {
Expand All @@ -132,7 +133,7 @@ impl Environment {
Ok(())
}

// Sets the current working directory to the previous working directory
/// Sets the CWD to the previous working directory
pub fn previous_directory(&mut self) -> Result<()> {
let starting_directory = self.CWD.clone();
if let Some(previous_path) = self.backward_directories.pop_back() {
Expand All @@ -144,7 +145,7 @@ impl Environment {
}
}

// Sets the current working directory to the next working directory
/// Sets the CWD to the next working directory
pub fn next_directory(&mut self) -> Result<()> {
let starting_directory = self.CWD.clone();
if let Some(next_path) = self.forward_directories.pop_front() {
Expand All @@ -157,19 +158,19 @@ impl Environment {
}
}

// Gets the name of the user who invoked the shell (to be used when the shell is first initialized)
/// Gets the environment variables from the parent process during shell initialization
fn get_parent_env_var(variable: EnvVariable) -> Result<String> {
std::env::var(variable.to_legacy_string())
.replace_err(state_err!(MissingEnvironmentVariable(variable)))
}

// Converts the PATH environment variable from a string to a vector of Paths
/// Converts the PATH environment variable from a string to a collection of `Path`s
fn convert_path(path: &str, home: &PathBuf) -> Result<VecDeque<Path>> {
let mut paths = VecDeque::new();

let path_strings = path.split(':').collect::<Vec<&str>>();
for path_string in path_strings {
let path = Path::from_str(path_string, home).replace_err(path_err!(
let path = Path::try_from_str(path_string, home).replace_err(path_err!(
FailedToConvertStringToPath(path_string.to_owned())
))?;
paths.push_back(path);
Expand Down
Loading

0 comments on commit 1e11712

Please sign in to comment.