1
0
mirror of https://github.com/Llewellynvdm/starship.git synced 2024-12-01 01:04:00 +00:00

Use "context" to contain run details (#14)

* Create "context" to contain run details

* Use context in tests and benchmarks
This commit is contained in:
Matan Kushner 2019-04-19 16:57:14 -04:00 committed by GitHub
parent 6d7485cf50
commit 022e0002e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 81 additions and 45 deletions

View File

@ -4,18 +4,17 @@ extern crate criterion;
use criterion::Criterion; use criterion::Criterion;
use clap::{App, Arg}; use clap::{App, Arg};
use starship::context::Context;
use starship::modules; use starship::modules;
use std::path::Path;
fn char_segment(c: &mut Criterion) { fn char_segment(c: &mut Criterion) {
let args = App::new("starship") let args = App::new("starship")
.arg(Arg::with_name("status_code")) .arg(Arg::with_name("status_code"))
.get_matches_from(vec!["starship", "0"]); .get_matches_from(vec!["starship", "0"]);
let context = Context::new_with_dir(args, "~");
let path = Path::new("~");
c.bench_function("char segment", move |b| { c.bench_function("char segment", move |b| {
b.iter(|| modules::handle("char", &path, &args)) b.iter(|| modules::handle("char", &context))
}); });
} }
@ -23,11 +22,10 @@ fn dir_segment(c: &mut Criterion) {
let args = App::new("starship") let args = App::new("starship")
.arg(Arg::with_name("status_code")) .arg(Arg::with_name("status_code"))
.get_matches_from(vec!["starship", "0"]); .get_matches_from(vec!["starship", "0"]);
let context = Context::new_with_dir(args, "~");
let path = Path::new("~");
c.bench_function("dir segment", move |b| { c.bench_function("dir segment", move |b| {
b.iter(|| modules::handle("dir", &path, &args)) b.iter(|| modules::handle("dir", &context))
}); });
} }
@ -35,11 +33,10 @@ fn line_break_segment(c: &mut Criterion) {
let args = App::new("starship") let args = App::new("starship")
.arg(Arg::with_name("status_code")) .arg(Arg::with_name("status_code"))
.get_matches_from(vec!["starship", "0"]); .get_matches_from(vec!["starship", "0"]);
let context = Context::new_with_dir(args, "~");
let path = Path::new("~");
c.bench_function("line break segment", move |b| { c.bench_function("line break segment", move |b| {
b.iter(|| modules::handle("line_break", &path, &args)) b.iter(|| modules::handle("line_break", &context))
}); });
} }

30
src/context.rs Normal file
View File

@ -0,0 +1,30 @@
use clap::ArgMatches;
use std::env;
use std::path::PathBuf;
pub struct Context<'a> {
pub current_dir: PathBuf,
pub arguments: ArgMatches<'a>,
}
impl<'a> Context<'a> {
pub fn new(arguments: ArgMatches) -> Context {
// TODO: Currently gets the physical directory. Get the logical directory.
let current_dir = env::current_dir().expect("Unable to identify current directory.");
Context {
current_dir,
arguments,
}
}
pub fn new_with_dir<T>(arguments: ArgMatches, dir: T) -> Context
where
T: Into<PathBuf>,
{
Context {
current_dir: dir.into(),
arguments,
}
}
}

View File

@ -1,4 +1,5 @@
// Lib is present to allow for benchmarking // Lib is present to allow for benchmarking
pub mod context;
pub mod modules; pub mod modules;
pub mod print; pub mod print;
pub mod segment; pub mod segment;

View File

@ -5,6 +5,7 @@ extern crate ansi_term;
extern crate dirs; extern crate dirs;
extern crate git2; extern crate git2;
mod context;
mod modules; mod modules;
mod print; mod print;
mod segment; mod segment;

View File

@ -1,7 +1,7 @@
use super::Segment;
use ansi_term::Color; use ansi_term::Color;
use clap::ArgMatches;
use std::path::Path; use super::Segment;
use crate::context::Context;
/// Creates a segment for the prompt character /// Creates a segment for the prompt character
/// ///
@ -11,14 +11,15 @@ use std::path::Path;
/// (green by default) /// (green by default)
/// - If the exit-code was anything else, the arrow will be formatted with /// - If the exit-code was anything else, the arrow will be formatted with
/// `COLOR_FAILURE` (red by default) /// `COLOR_FAILURE` (red by default)
pub fn segment(_current_dir: &Path, args: &ArgMatches) -> Option<Segment> { pub fn segment(context: &Context) -> Option<Segment> {
const PROMPT_CHAR: &str = ""; const PROMPT_CHAR: &str = "";
const COLOR_SUCCESS: Color = Color::Green; const COLOR_SUCCESS: Color = Color::Green;
const COLOR_FAILURE: Color = Color::Red; const COLOR_FAILURE: Color = Color::Red;
let mut segment = Segment::new("char"); let mut segment = Segment::new("char");
let arguments = &context.arguments;
if args.value_of("status_code").unwrap() == "0" { if arguments.value_of("status_code").unwrap() == "0" {
segment.set_style(COLOR_SUCCESS); segment.set_style(COLOR_SUCCESS);
} else { } else {
segment.set_style(COLOR_FAILURE); segment.set_style(COLOR_FAILURE);

View File

@ -1,10 +1,10 @@
use super::Segment;
use ansi_term::Color; use ansi_term::Color;
use clap::ArgMatches;
use dirs;
use git2::Repository; use git2::Repository;
use std::path::Path; use std::path::Path;
use super::Segment;
use crate::context::Context;
/// Creates a segment with the current directory /// Creates a segment with the current directory
/// ///
/// Will perform path contraction and truncation. /// Will perform path contraction and truncation.
@ -14,12 +14,13 @@ use std::path::Path;
/// ///
/// **Truncation** /// **Truncation**
/// Paths will be limited in length to `3` path components by default. /// Paths will be limited in length to `3` path components by default.
pub fn segment(current_dir: &Path, _args: &ArgMatches) -> Option<Segment> { pub fn segment(context: &Context) -> Option<Segment> {
const HOME_SYMBOL: &str = "~"; const HOME_SYMBOL: &str = "~";
const DIR_TRUNCATION_LENGTH: usize = 3; const DIR_TRUNCATION_LENGTH: usize = 3;
const SECTION_COLOR: Color = Color::Cyan; const SECTION_COLOR: Color = Color::Cyan;
let mut segment = Segment::new("dir"); let mut segment = Segment::new("dir");
let current_dir = &context.current_dir;
let dir_string; let dir_string;
if let Ok(repo) = git2::Repository::discover(current_dir) { if let Ok(repo) = git2::Repository::discover(current_dir) {

View File

@ -1,9 +1,8 @@
use super::Segment; use super::Segment;
use clap::ArgMatches; use crate::context::Context;
use std::path::Path;
/// Creates a segment for the line break /// Creates a segment for the line break
pub fn segment(_current_dir: &Path, _args: &ArgMatches) -> Option<Segment> { pub fn segment(_context: &Context) -> Option<Segment> {
const LINE_ENDING: &str = "\n"; const LINE_ENDING: &str = "\n";
let mut segment = Segment::new("line_break"); let mut segment = Segment::new("line_break");

View File

@ -3,16 +3,15 @@ mod directory;
mod line_break; mod line_break;
mod nodejs; mod nodejs;
use crate::context::Context;
use crate::segment::Segment; use crate::segment::Segment;
use clap::ArgMatches;
use std::path::Path;
pub fn handle(module: &str, current_dir: &Path, args: &ArgMatches) -> Option<Segment> { pub fn handle(module: &str, context: &Context) -> Option<Segment> {
match module { match module {
"dir" | "directory" => directory::segment(current_dir, args), "dir" | "directory" => directory::segment(context),
"char" | "character" => character::segment(current_dir, args), "char" | "character" => character::segment(context),
"node" | "nodejs" => nodejs::segment(current_dir, args), "node" | "nodejs" => nodejs::segment(context),
"line_break" => line_break::segment(current_dir, args), "line_break" => line_break::segment(context),
_ => panic!("Unknown module: {}", module), _ => panic!("Unknown module: {}", module),
} }

View File

@ -1,21 +1,22 @@
use super::Segment;
use ansi_term::Color; use ansi_term::Color;
use clap::ArgMatches;
use std::fs::{self, DirEntry}; use std::fs::{self, DirEntry};
use std::path::Path;
use std::process::Command; use std::process::Command;
use super::Segment;
use crate::context::Context;
/// Creates a segment with the current Node.js version /// Creates a segment with the current Node.js version
/// ///
/// Will display the Node.js version if any of the following criteria are met: /// Will display the Node.js version if any of the following criteria are met:
/// - Current directory contains a `.js` file /// - Current directory contains a `.js` file
/// - Current directory contains a `node_modules` directory /// - Current directory contains a `node_modules` directory
/// - Current directory contains a `package.json` file /// - Current directory contains a `package.json` file
pub fn segment(current_dir: &Path, _args: &ArgMatches) -> Option<Segment> { pub fn segment(context: &Context) -> Option<Segment> {
const NODE_CHAR: &str = ""; const NODE_CHAR: &str = "";
const SECTION_COLOR: Color = Color::Green; const SECTION_COLOR: Color = Color::Green;
let mut segment = Segment::new("node"); let mut segment = Segment::new("node");
let current_dir = &context.current_dir;
let files = fs::read_dir(current_dir).unwrap(); let files = fs::read_dir(current_dir).unwrap();
// Early return if there are no JS project files // Early return if there are no JS project files

View File

@ -1,14 +1,12 @@
use clap::ArgMatches; use clap::ArgMatches;
use std::env;
use std::io::{self, Write}; use std::io::{self, Write};
use crate::context::Context;
use crate::modules; use crate::modules;
pub fn prompt(args: ArgMatches) { pub fn prompt(args: ArgMatches) {
let default_prompt = vec!["directory", "nodejs", "line_break", "character"]; let prompt_order = vec!["directory", "nodejs", "line_break", "character"];
let context = Context::new(args);
// TODO: Currently gets the physical directory. Get the logical directory.
let current_path = env::current_dir().expect("Unable to identify current directory.");
// TODO: // TODO:
// - List files in directory // - List files in directory
@ -20,9 +18,9 @@ pub fn prompt(args: ArgMatches) {
// Write a new line before the prompt // Write a new line before the prompt
writeln!(handle).unwrap(); writeln!(handle).unwrap();
default_prompt prompt_order
.iter() .iter()
.map(|module| modules::handle(module, &current_path, &args)) // Compute segments .map(|module| modules::handle(module, &context)) // Compute segments
.flatten() // Remove segments set to `None` .flatten() // Remove segments set to `None`
.enumerate() // Turn segment into tuple with index .enumerate() // Turn segment into tuple with index
.map(|(index, segment)| segment.output_index(index)) // Generate string outputs .map(|(index, segment)| segment.output_index(index)) // Generate string outputs

View File

@ -1,18 +1,26 @@
use clap::{App, Arg}; use clap::{App, Arg};
use starship::context::Context;
use starship::modules; use starship::modules;
use std::path::Path; use std::path::PathBuf;
pub fn render_segment(module: &str, path: &Path) -> String { pub fn render_segment<T>(module: &str, path: T) -> String
render_segment_with_status(module, path, "0") where
T: Into<PathBuf>,
{
render_segment_with_status(module, &path.into(), "0")
} }
pub fn render_segment_with_status(module: &str, path: &Path, status: &str) -> String { pub fn render_segment_with_status<T>(module: &str, path: T, status: &str) -> String
where
T: Into<PathBuf>,
{
// Create an `Arg` with status_code of "0" // Create an `Arg` with status_code of "0"
let args = App::new("starship") let args = App::new("starship")
.arg(Arg::with_name("status_code")) .arg(Arg::with_name("status_code"))
.get_matches_from(vec!["starship", status]); .get_matches_from(vec!["starship", status]);
let context = Context::new_with_dir(args, path.into());
let segment = modules::handle(module, path, &args); let segment = modules::handle(module, &context);
segment.unwrap().output() segment.unwrap().output()
} }