Skip to content

Commit

Permalink
Remove lazy_static; improve API and docs.
Browse files Browse the repository at this point in the history
  • Loading branch information
gregschmit committed Jul 9, 2023
1 parent 3c57c34 commit 82c67b4
Show file tree
Hide file tree
Showing 11 changed files with 100 additions and 106 deletions.
7 changes: 0 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ categories = ["command-line-utilities", "development-tools", "development-tools:
[dependencies]
clap = {version = "4", features = ["derive"]}
const_format = "0.2"
lazy_static = "1"

[[bin]]
name = "omake"
Expand Down
21 changes: 12 additions & 9 deletions src/bin/main/_main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ use clap::Parser;

use args::Args;

use omake::{Context, DefaultLogger, Env, Logger, Makefile};
use omake::context::Context;
use omake::logger::{DefaultLogger, Logger};
use omake::makefile::Makefile;
use omake::vars::Env;

/// An ordered list of filenames used to search for a makefile.
const MAKEFILE_SEARCH: [&str; 6] = [
Expand Down Expand Up @@ -73,8 +76,8 @@ fn find_makefile() -> Option<PathBuf> {
}

/// Print an error message and exit with code 2.
fn exit_with(msg: impl AsRef<str>, logger: &DefaultLogger, context: Option<&Context>) -> ! {
logger.error(msg, context);
fn exit_with(logger: &DefaultLogger, msg: impl AsRef<str>, context: Option<Context>) -> ! {
logger.error(msg, context.as_ref());
std::process::exit(2)
}

Expand All @@ -93,7 +96,7 @@ fn main() {
} else {
// Remember the current directory to return to.
let cwd = env::current_dir()
.unwrap_or_else(|e| exit_with(format!("Failed to get cwd ({}).", e), &logger, None));
.unwrap_or_else(|e| exit_with(&logger, format!("Failed to get cwd ({}).", e), None));

// Change to the specified directory.
let dir = args
Expand All @@ -102,14 +105,14 @@ fn main() {
.fold(PathBuf::new(), |dir, d| dir.join(d));
logger.info(format!("Chdir to `{}`.", dir.display()), None);
env::set_current_dir(&dir)
.unwrap_or_else(|e| exit_with(format!("Chdir failed: {}.", e), &logger, None));
.unwrap_or_else(|e| exit_with(&logger, format!("Chdir failed: {}.", e), None));

Some(cwd)
};

// Determine the makefile to read.
let makefile_fn = match args.file {
None => find_makefile().unwrap_or_else(|| exit_with("No makefile found.", &logger, None)),
None => find_makefile().unwrap_or_else(|| exit_with(&logger, "No makefile found.", None)),
Some(ref file) => PathBuf::from(file),
};

Expand All @@ -132,19 +135,19 @@ fn main() {
Box::new(DefaultLogger {}),
env::vars().collect::<Env>().into(),
) {
Err(e) => exit_with(e.msg, &logger, Some(&e.context)),
Err(e) => exit_with(&logger, e.msg, Some(e.context)),
Ok(m) => m,
};

// Execute the makefile.
if let Err(e) = makefile.execute(args.targets) {
exit_with(e.msg, &logger, Some(&e.context));
exit_with(&logger, e.msg, Some(e.context));
}

// Go back to the original directory, if we changed directory previously.
if let Some(cwd) = original_dir {
logger.info(format!("Chdir back to `{}`.", cwd.display()), None);
env::set_current_dir(&cwd)
.unwrap_or_else(|e| exit_with(format!("Chdir failed: {}.", e), &logger, None));
.unwrap_or_else(|e| exit_with(&logger, format!("Chdir failed: {}.", e), None));
}
}
4 changes: 2 additions & 2 deletions src/bin/main/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
use clap::Parser;
use const_format::formatcp;

use omake::Opts;
use omake::makefile::Opts;

/// Represents the `clap`-based arguments provided by this binary.
/// The `clap`-based arguments provided by this binary.
#[derive(Clone, Debug, Parser)]
#[clap(
name = "make (oxidized)",
Expand Down
21 changes: 8 additions & 13 deletions src/lib/_lib.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
//! # omake (Oxidized Make)
//!
//! This is the library component of `omake`, generally oriented towards the main binary of this
//! crate, but should be designed to be used by other applications.
//! This is the library component of the `omake` project, responsible for parsing and executing
//! makefiles.
mod context;
mod error;
mod expand;
mod logger;
mod makefile;
mod vars;

pub use context::Context;
pub use logger::{DefaultLogger, Logger, ERROR, INFO, WARN};
pub use makefile::{Makefile, Opts};
pub use vars::Env;
pub mod context;
pub mod error;
pub mod expand;
pub mod logger;
pub mod makefile;
pub mod vars;
5 changes: 2 additions & 3 deletions src/lib/context.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
//! Simple implementation of a `Context` struct designed to track parsing/execution location.
//! Tracking mechanism for makefiles; generally useful for errors, logging, etc.
use std::path::PathBuf;

/// Represents parsing/execution context, specifically, which file and where in the file something
/// is happening.
/// Track a file path, content, and location within the file (line/column).
#[derive(Clone, Debug)]
pub struct Context {
pub path: Option<PathBuf>,
Expand Down
12 changes: 5 additions & 7 deletions src/lib/error.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
//! Error type for the parser/executor.
use std::error::Error;
use std::fmt;

use crate::context::Context;
use crate::logger::{DefaultLogger, Logger, ERROR};

/// Represents a generic error in a makefile, including context.
/// An error in the parsing or execution of a makefile.
#[derive(Debug)]
pub struct MakeError {
pub msg: String,
Expand All @@ -22,12 +23,9 @@ impl MakeError {

impl Error for MakeError {}

/// Not really used, but needed so `MakeError` can implement `Error`.
impl fmt::Display for MakeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
DefaultLogger {}.format_log(&self.msg, ERROR, Some(&self.context))
)
write!(f, "{e:?}", e = &self)
}
}
14 changes: 7 additions & 7 deletions src/lib/expand.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
//! Implementation of variable expansion.
use crate::vars::Vars;

/// Represents a frame on the stack inside the `expand` function. This is used for tracking the
/// previous buffer when expanding potentially nested expressions (i.e., either `$()` or `${}`).
/// Single variable expansions (e.g., `$X`) are handled inline without creating a frame since they
/// cannot possibly have nested expressions.
/// A stack frame used to track the previous buffer when expanding potentially nested expressions
/// (i.e., either `$()` or `${}`). Single variable expansions (e.g., `$X`) are handled inline
/// without creating a frame since they cannot possibly have nested expressions.
struct Frame {
pub previous_buffer: String,
/// Track which character opened this stack frame (should be parenthesis or brace).
/// Which character opened this stack frame (parenthesis or brace)?
pub opening_delimiter: char,
}

/// The primary public interface for running variable expansion on an input string, given a
/// collection of `vars`.
/// Run variable expansion on an input string, given a collection of `vars`.
///
/// The goal here is to be `O(n)`. This works by iterating over the input string and storing plain
/// characters into a buffer until we hit either:
Expand Down
19 changes: 11 additions & 8 deletions src/lib/logger.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Generic logging facility with a default implementation.
use crate::context::Context;

pub const INFO: &str = "INFO";
Expand All @@ -6,30 +8,28 @@ pub const ERROR: &str = "ERROR";

const MAX_SEVERITY_LENGTH: usize = 5;

#[derive(Clone, Debug)]
pub struct DefaultLogger {}

pub trait Logger: Clone + std::fmt::Debug {
/// Generic trait any logger must implement.
pub trait Logger {
/// Write the message somewhere.
fn write(&self, msg: String);

/// Log an `INFO` message.
fn info(&self, msg: impl AsRef<str>, context: Option<&Context>) {
self.write(self.format_log(msg, INFO, context));
self.write(self.format_log(INFO, msg, context));
}

/// Log a `WARN` message.
fn warn(&self, msg: impl AsRef<str>, context: Option<&Context>) {
self.write(self.format_log(msg, WARN, context));
self.write(self.format_log(WARN, msg, context));
}

/// Log an `ERROR` message.
fn error(&self, msg: impl AsRef<str>, context: Option<&Context>) {
self.write(self.format_log(msg, ERROR, context));
self.write(self.format_log(ERROR, msg, context));
}

/// Formatter for all log messages.
fn format_log(&self, msg: impl AsRef<str>, level: &str, context: Option<&Context>) -> String {
fn format_log(&self, level: &str, msg: impl AsRef<str>, context: Option<&Context>) -> String {
// Format log level and context label/line.
let level_display = format!("{:0width$}", level, width = MAX_SEVERITY_LENGTH);
let context_label = context
Expand All @@ -56,6 +56,9 @@ pub trait Logger: Clone + std::fmt::Debug {
}
}

/// Uses the default implementation and outputs to `stderr`.
pub struct DefaultLogger {}

/// By default, print to `stderr`.
impl Logger for DefaultLogger {
fn write(&self, msg: String) {
Expand Down
4 changes: 3 additions & 1 deletion src/lib/makefile.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Primary public interface for parsing/executing a makefile.
mod opts;
mod rule_map;

Expand Down Expand Up @@ -29,7 +31,7 @@ const COMMENT_INDICATOR: char = '#';
// breaks: Vec<usize>,
// }

/// The internal representation of a makefile.
/// Represents a makefile.
#[derive(Debug)]
pub struct Makefile<L: Logger> {
pub opts: Opts,
Expand Down
Loading

0 comments on commit 82c67b4

Please sign in to comment.