Merge branch 'RustedTerrier-main' into main

This commit is contained in:
g1n 2021-08-28 18:49:29 +00:00
commit 98a05f8f66
12 changed files with 263 additions and 139 deletions

75
rustfmt.toml Normal file
View File

@ -0,0 +1,75 @@
max_width = 100
hard_tabs = false
tab_spaces = 4
newline_style = "Auto"
indent_style = "Block"
use_small_heuristics = "Default"
fn_call_width = 60
attr_fn_like_width = 70
struct_lit_width = 18
struct_variant_width = 35
array_width = 60
chain_width = 60
single_line_if_else_max_width = 50
wrap_comments = false
format_code_in_doc_comments = false
comment_width = 80
normalize_comments = false
normalize_doc_attributes = false
license_template_path = ""
format_strings = false
format_macro_matchers = false
format_macro_bodies = true
empty_item_single_line = true
struct_lit_single_line = true
fn_single_line = false
where_single_line = false
imports_indent = "Block"
imports_layout = "Mixed"
imports_granularity = "Preserve"
group_imports = "Preserve"
reorder_imports = true
reorder_modules = true
reorder_impl_items = false
type_punctuation_density = "Wide"
space_before_colon = false
space_after_colon = true
spaces_around_ranges = false
binop_separator = "Front"
remove_nested_parens = true
combine_control_expr = true
overflow_delimited_expr = false
struct_field_align_threshold = 0
enum_discrim_align_threshold = 0
match_arm_blocks = true
match_arm_leading_pipes = "Never"
force_multiline_blocks = false
fn_args_layout = "Tall"
brace_style = "SameLineWhere"
control_brace_style = "AlwaysSameLine"
trailing_semicolon = true
trailing_comma = "Vertical"
match_block_trailing_comma = false
blank_lines_upper_bound = 1
blank_lines_lower_bound = 0
edition = "2015"
version = "One"
inline_attribute_width = 0
merge_derives = true
use_try_shorthand = false
use_field_init_shorthand = false
force_explicit_abi = true
condense_wildcard_suffixes = false
color = "Auto"
required_version = "1.4.37"
unstable_features = false
disable_all_formatting = false
skip_children = false
hide_parse_errors = false
error_on_line_overflow = false
error_on_unformatted = false
report_todo = "Never"
report_fixme = "Never"
ignore = []
emit_mode = "Files"
make_backup = false

View File

@ -1,18 +1,18 @@
use std::env;
use std::fs::File;
use std::path::Path;
use std::io::BufReader;
use std::io::stdout;
use std::io::prelude::*;
use std::io::stdout;
use std::io::BufReader;
use std::path::Path;
fn main() -> std::io::Result<()> {
fn main() -> std::io::Result<()> {
let args: Vec<String> = env::args().collect();
for arg in 1..args.len() {
match args[arg].as_str() {
"--help" => {
println!("Usage: cat [OPTIONS] FILE");
println!("Reads a file");
},
}
arg => {
if Path::new(arg).exists() {
let file = File::open(arg)?;

View File

@ -5,28 +5,28 @@ use std::fs::{self, File};
//use std::io::stdout;
//use std::io::prelude::*;
fn main(){
fn main() {
let args: Vec<String> = env::args().collect();
let mut pattern_and_filename: Vec<String> = Vec::new(); // 0 - pattern, 1 - name of files
let mut invert: bool = false;
for arg in 1..args.len() {
match args[arg].as_str() {
"--help" => {
println!("Usage: grep [OPTIONS] FILE");
println!("Print lines matching a pattern");
return;
},
}
"-v" => {
invert = true;
},
}
arg => {
if args.len() < 3 {
println!("grep: Not enought arguments");
return;
}
}
pattern_and_filename.push(arg.to_string());
},
}
}
}
let pattern = &pattern_and_filename[0];
@ -42,8 +42,7 @@ fn search<'a>(pattern: String, contents: &'a str, invert: bool) -> Vec<&'a str>
for line in contents.lines() {
if line.contains(&pattern) && !invert {
results.push(line);
}
else if !line.contains(&pattern) && invert {
} else if !line.contains(&pattern) && invert {
results.push(line);
}
}

View File

@ -1,12 +1,12 @@
use std::convert::TryInto;
use std::env;
use std::fs::File;
use std::path::Path;
use std::io::BufReader;
use std::io::stdout;
use std::io::prelude::*;
use std::convert::TryInto;
use std::io::stdout;
use std::io::BufReader;
use std::path::Path;
fn main() -> std::io::Result<()> {
fn main() -> std::io::Result<()> {
let args: Vec<String> = env::args().collect();
let mut num_of_lines: i32 = 10;
for arg in 1..args.len() {
@ -14,9 +14,9 @@ fn main() -> std::io::Result<()> {
"--help" => {
println!("Usage: head [OPTIONS] FILE");
println!("Output the first part of files");
},
}
"-n" => {
num_of_lines = args[arg+1].parse::<i32>().unwrap();
num_of_lines = args[arg + 1].parse::<i32>().unwrap();
}
arg => {
if Path::new(arg).exists() {

View File

@ -1,13 +1,13 @@
use std::env;
use std::fs;
use std::io::{stdout, Write};
use std::path::Path;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
/*extern crate chrono;
use chrono::prelude::*;*/
fn main(){
fn main() {
let args: Vec<String> = env::args().collect();
// Flags vars
let mut show_hidden = false;
@ -20,25 +20,30 @@ fn main(){
match args[arg].as_str() {
"--help" => {
println!("List files in directory");
},
}
"-a" | "--all" => {
show_hidden = true;
show_prev_and_current = true;
},
}
"-A" | "--almost-all" => {
show_hidden = true;
show_prev_and_current = false;
},
}
"-l" => {
long_listing = true;
},
}
arg => {
dir = Some(arg);
},
}
}
}
list_dir(dir.unwrap().to_string(), show_hidden, show_prev_and_current, long_listing);
}
list_dir(
dir.unwrap().to_string(),
show_hidden,
show_prev_and_current,
long_listing,
);
}
fn list_dir(arg: String, show_hidden: bool, show_prev_and_current: bool, long_listing: bool) {
let files = fs::read_dir(arg.clone()).unwrap();
if show_hidden && show_prev_and_current {
@ -75,6 +80,12 @@ fn long_listing_format(path: &Path, file: String) -> std::io::Result<()> {
} else {
permissions_string.push('-');
}
println!("{}{:o} {} {}", permissions_string, metadata.permissions().mode(), metadata.len(), file);
println!(
"{}{:o} {} {}",
permissions_string,
metadata.permissions().mode(),
metadata.len(),
file
);
Ok(())
}

View File

@ -1,11 +1,12 @@
use std::env;
use std::io::{stdin, stdout, Write};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::{
env, fs,
io::{stdin, stdout, Write},
path::Path,
process::{exit, Child, Command, Stdio},
};
fn main(){
let mut status=0;
fn main() {
let mut status = 0;
let user = env::var("USER").unwrap();
let home_dir = format!("{}{}", "/home/", user);
let mut pwd = env::current_dir().unwrap();
@ -23,7 +24,7 @@ fn main(){
let mut commands = input.trim().split(" | ").peekable();
let mut previous_command = None;
while let Some(command) = commands.next() {
while let Some(command) = commands.next() {
// Other shell variables that can be changed
// everything after the first whitespace character is interpreted as args to the command
@ -32,31 +33,32 @@ fn main(){
let args = parts;
match command {
"true" | ":" => {
"true" | ":" => {
status = 0;
},
}
"false" => {
status = 1;
},
}
"echo" => {
let args: Vec<&str> = args/*.peekable().peek().map_or("", |x| *x).split(" ")*/.collect();
let args: Vec<&str> = args // .peekable().peek().map_or("", |x| *x).split(" ")
.collect();
for arg in args {
if arg.contains("$") {
match arg {
"$?" => {
print!("{}", status);
},
}
"$PWD" => {
print!("{}", pwd.display());
},
}
"$USER" => {
print!("{}", user);
},
}
"$HOME" => {
print!("{}", home_dir);
},
}
arg => {
print!("\n");
print!("\n");
}
}
print!(" ");
@ -67,26 +69,49 @@ fn main(){
print!(" ");
stdout().flush().unwrap();
println!();
},
}
"cd" => {
let new_dir = args.peekable().peek().map_or(home_dir.clone(), |x| (*x).to_string());
let new_dir = args
.peekable()
.peek()
.map_or(home_dir.clone(), |x| (*x).to_string());
let root = Path::new(&new_dir);
if let Err(e) = env::set_current_dir(&root) {
eprintln!("{}", e);
}
previous_command = None;
pwd=env::current_dir().unwrap();
},
// current_dir() follows symlinks which isn't always accurate.
pwd = root.to_path_buf();
}
"pwd" => {
println!("{}", pwd.display());
},
let args: Vec<&str> = args.collect();
let mut output = Output::Logical;
for i in args {
if &i[..] == "-L" {
output = Output::Logical;
} else if &i[..] == "-P" {
output = Output::Physical;
}
}
match output {
Output::Logical => println!("{}", get_logical_dir()),
Output::Physical => {
println!(
"{}",
fs::canonicalize(get_logical_dir())
.unwrap()
.to_string_lossy()
)
}
}
}
"exit" => return,
"#" => {},
"#" => {}
command => {
let stdin = previous_command
.map_or(Stdio::inherit(),
|output: Child| Stdio::from(output.stdout.unwrap()));
let stdin = previous_command.map_or(Stdio::inherit(), |output: Child| {
Stdio::from(output.stdout.unwrap())
});
let stdout = if commands.peek().is_some() {
// there is another command piped behind this one
@ -105,13 +130,15 @@ fn main(){
.spawn();
match output {
Ok(output) => { previous_command = Some(output); },
Ok(output) => {
previous_command = Some(output);
}
Err(e) => {
previous_command = None;
eprintln!("{}", e);
},
}
};
},
}
}
}
@ -119,6 +146,22 @@ fn main(){
// block until the final command has finished
final_command.wait().unwrap();
}
}
}
fn get_logical_dir() -> String {
// current_dir follows symlinks which isn't what we want with
// logical pwd.
match env::var("PWD") {
Ok(d) => d,
Err(e) => {
eprintln!("Could not read environment variable $PWD: {}", e);
exit(1);
}
}
}
enum Output {
Logical,
Physical,
}

View File

@ -1,7 +1,7 @@
use std::env;
use std::fs;
fn main(){
fn main() {
let mut verbose_flag = false;
let args: Vec<String> = env::args().collect();
for arg in 1..args.len() {
@ -9,16 +9,16 @@ fn main(){
"--help" => {
println!("Usage: mkdir [OPTIONS] DIRECTORY");
return;
},
}
"-v" | "--verbose" => {
verbose_flag = true;
},
}
arg => {
fs::create_dir_all(arg.to_string());
if verbose_flag {
println!("mkdir: created directory '{}'", arg);
}
},
}
}
}
}

View File

@ -12,35 +12,32 @@ fn main() {
println!("Usage: rm [OPTIONS] DIRECTORY");
println!("Removes files or directories");
return;
},
}
"-v" | "--verbose" => {
verbose_flag = true;
},
}
"-d" | "--dir" => {
remove_dirs = true;
},
}
arg => {
if Path::new(arg).exists() {
if !Path::new(arg).is_dir() {
fs::remove_file(arg.to_string());
if verbose_flag {
println!("rm: removed '{}'", arg);
}
if Path::new(arg).exists() {
if !Path::new(arg).is_dir() {
fs::remove_file(arg.to_string());
if verbose_flag {
println!("rm: removed '{}'", arg);
}
else if Path::new(arg).is_dir() && remove_dirs {
fs::remove_dir(arg.to_string());
if verbose_flag {
println!("rm: removed directory '{}'", arg);
}
}
else if Path::new(arg).is_dir() {
println!("rm: cannot remove '{}': Is a directory", arg);
} else if Path::new(arg).is_dir() && remove_dirs {
fs::remove_dir(arg.to_string());
if verbose_flag {
println!("rm: removed directory '{}'", arg);
}
} else if Path::new(arg).is_dir() {
println!("rm: cannot remove '{}': Is a directory", arg);
}
else {
println!("rm: cannot remove '{}': No such file or directory", arg);
}
},
};
} else {
println!("rm: cannot remove '{}': No such file or directory", arg);
}
}
};
}
}

View File

@ -10,17 +10,16 @@ fn main() {
println!("Usage: rmdir [OPTIONS] DIRECTORY");
println!("Removes empty directory");
return;
},
}
"-v" | "--verbose" => {
verbose_flag = true;
},
}
arg => {
fs::remove_dir(arg.to_string());
if verbose_flag {
println!("rmdir: removed directory '{}'", arg);
}
},
};
fs::remove_dir(arg.to_string());
if verbose_flag {
println!("rmdir: removed directory '{}'", arg);
}
}
};
}
}

View File

@ -1,10 +1,10 @@
use std::env;
use std::fs::File;
use std::path::Path;
use std::io::BufReader;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::Path;
fn main() -> std::io::Result<()> {
fn main() -> std::io::Result<()> {
let args: Vec<String> = env::args().collect();
let mut num_of_lines: i32 = 10;
for arg in 1..args.len() {
@ -12,9 +12,9 @@ fn main() -> std::io::Result<()> {
"--help" => {
println!("Usage: tail [OPTIONS] FILE");
println!("Output the last part of files");
},
}
"-n" => {
num_of_lines = args[arg+1].parse::<i32>().unwrap();
num_of_lines = args[arg + 1].parse::<i32>().unwrap();
}
arg => {
if Path::new(arg).exists() {
@ -26,7 +26,7 @@ fn main() -> std::io::Result<()> {
Ok(())
}
fn get_line_at(path: &Path, line_num: i32) -> Result<(),()> {
fn get_line_at(path: &Path, line_num: i32) -> Result<(), ()> {
let file = File::open(path).expect("File not found or cannot be opened");
let content = BufReader::new(&file);
let lines = content.lines();

View File

@ -2,7 +2,7 @@ use std::env;
use std::fs::{self, File};
use std::path::Path;
fn main(){
fn main() {
let args: Vec<String> = env::args().collect();
for arg in 1..args.len() {
match args[arg].as_str() {
@ -10,7 +10,7 @@ fn main(){
println!("Usage: touch [OPTIONS] FILE");
println!("Creates empty file");
return;
},
}
arg => {
if !Path::new(arg).exists() {
File::create(arg);

View File

@ -1,40 +1,40 @@
use std::env;
use std::fs::File;
use std::path::Path;
use std::io::BufReader;
use std::io::prelude::*;
use std::io::BufReader;
use std::path::Path;
fn main() -> std::io::Result<()> {
let args: Vec<String> = env::args().collect();
let mut only_chars = false;
let mut only_lines = false;
Ok(for arg in 1..args.len() {
match args[arg].as_str() {
"-c" => { only_chars=true }
"-l" => { only_lines=true }
"--help" => {
println!("Usage: cat [OPTIONS] FILE");
println!("Reads a file");
},
arg => {
if Path::new(arg).exists() { let file = File::open(arg)?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
let mut lines = 0;
for _ in contents.lines() {
lines += 1;
}
if only_chars {
println!("{}", contents.len());
} else if only_lines {
println!("{}", lines);
} else {
println!("{} {} {}", lines, contents.len(), arg);
}
}
}
}
})
fn main() -> std::io::Result<()> {
let args: Vec<String> = env::args().collect();
let mut only_chars = false;
let mut only_lines = false;
Ok(for arg in 1..args.len() {
match args[arg].as_str() {
"-c" => only_chars = true,
"-l" => only_lines = true,
"--help" => {
println!("Usage: cat [OPTIONS] FILE");
println!("Reads a file");
}
arg => {
if Path::new(arg).exists() {
let file = File::open(arg)?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
let mut lines = 0;
for _ in contents.lines() {
lines += 1;
}
if only_chars {
println!("{}", contents.len());
} else if only_lines {
println!("{}", lines);
} else {
println!("{} {} {}", lines, contents.len(), arg);
}
}
}
}
})
}