Skip to content

Commit

Permalink
rename project, adding cache mechanism (#12)
Browse files Browse the repository at this point in the history
* rename project, adding cache mechanism

* refactor code and finalize cachin evaluation

* fix caching evaluation and manifest creation
  • Loading branch information
Rizary authored Jan 25, 2021
1 parent 7020163 commit 19f77cf
Show file tree
Hide file tree
Showing 18 changed files with 640 additions and 288 deletions.
263 changes: 172 additions & 91 deletions Cargo.lock

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "allfmt"
name = "prjfmt"
version = "0.1.0"
authors = ["Andika Demas Riyandi <[email protected]>"]
edition = "2018"
Expand All @@ -13,12 +13,15 @@ console = "0.13"
curl = "0.4"
dialoguer = "0.7"
env_logger = { version = "0.8", default-features = false }
filetime = "0.2"
glob = "0.3"
hex = "0.4"
human-panic = "1.0"
log = "0.4"
parking_lot = "0.11"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sha-1 = "0.9.2"
structopt = "0.3"
toml = "0.5"
walkdir = "2.3"
Expand Down
14 changes: 8 additions & 6 deletions devshell.nix
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ with pkgs;
#
# Documentation: https://github.com/numtide/devshell
mkDevShell {
name = "allfmt";
name = "prjfmt";
motd = ''
Welcome to the allfmt development environment.
Welcome to the prjfmt development environment.
'';
commands = [ ];

Expand All @@ -17,23 +17,25 @@ mkDevShell {
export LD_INCLUDE_PATH="$DEVSHELL_DIR/include"
export LD_LIBRARY_PATH="$DEVSHELL_DIR/lib"
export PKG_CONFIG_PATH="$DEVSHELL_DIR/lib/pkgconfig"
export GO111MODULE=on
unset GOPATH GOROOT
'';
};

env = { };

packages = [
# Build tools
allfmt.rust
prjfmt.rust

# Code formatters
haskellPackages.ormolu
haskellPackages.cabal-install
haskellPackages.ghc
nixpkgs-fmt
go
# gopls
# gopkgs
# gocode
gopls
gopkgs
gocode
];
}
3 changes: 1 addition & 2 deletions examples/monorepo/haskell/Main.hs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
module Main where

main :: IO ()
main =
putStrLn "Hello, Haskell!"
main = putStrLn "Hello, Riyan!"
File renamed without changes.
18 changes: 9 additions & 9 deletions flake.lock

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

4 changes: 2 additions & 2 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@
};
in
{
legacyPackages = pkgs.allfmt;
legacyPackages = pkgs.prjfmt;

packages = flake-utils.lib.flattenTree pkgs.allfmt;
packages = flake-utils.lib.flattenTree pkgs.prjfmt;

devShell = import ./devshell.nix { inherit pkgs; };

Expand Down
2 changes: 1 addition & 1 deletion overlay.nix
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
final: prev:
{
allfmt = rec {
prjfmt = rec {
rust = prev.callPackage ./rust { };
};
}
20 changes: 11 additions & 9 deletions src/command/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@ use anyhow::Context;
use console::style;
use log::info;
use std::fs;
use std::path::Path;
use std::path::PathBuf;

pub fn init_fmt() -> anyhow::Result<()> {
info!("Creating new allfmt configuration...");

let file = &format!("fmt.toml");
let file_path = Path::new(file);
pub fn init_prjfmt(path: Option<PathBuf>) -> anyhow::Result<()> {
info!("Creating new prjfmt configuration...");
let file = match path {
Some(loc) => loc,
None => PathBuf::from("."),
};
let file_path = file.as_path().join("prjfmt.toml");
// TODO: detect if file exists
fs::write(
file_path,
r#"# fmt is the universal code formatter - https://github.com/numtide/fmt
file_path.as_path(),
r#"# prjfmt is the universal code formatter - https://github.com/numtide/prjfmt
[formats.<Language>]
includes = [ "*.<language-extension>" ]
excludes = []
Expand All @@ -31,7 +33,7 @@ args = []
)
})?;

let msg = format!("Generated allfmt template at ./.");
let msg = format!("Generated prjfmt template at {}", file_path.display());
CLOG.info(&msg);
Ok(())
}
28 changes: 11 additions & 17 deletions src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,28 @@

mod init;

use self::init::init_fmt;
use self::init::init_prjfmt;
use std::path::PathBuf;

use log::info;

#[derive(Debug)]
struct Initialize {}

#[derive(Debug, StructOpt)]
/// The various kinds of commands that `allfmt` can execute.
/// The various kinds of commands that `prjfmt` can execute.
pub enum Command {
#[structopt(name = "--init")]
/// init a new project with a default config
Init,
#[structopt(name = "--dry-run")]
/// creating formating plan
Dry,
Init {
/// path to file or folder
path: Option<PathBuf>,
},
}

/// Run a command with the given logger!
pub fn run_all_fmt(command: Command) -> anyhow::Result<()> {
pub fn run_prjfmt_cli(command: Command) -> anyhow::Result<()> {
match command {
Command::Init => {
info!("creating fmt.toml");
init_fmt()
}
Command::Dry => {
println!("running dry-run");
Ok(())
Command::Init { path } => {
info!("creating prjfmt.toml");
init_prjfmt(path)
}
}
}
6 changes: 3 additions & 3 deletions src/customlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};

#[repr(u8)]
#[derive(Debug, Clone, Copy)]
/// The log level for allfmt
/// The log level for prjfmt
// Important! the least verbose must be at
// the top and the most verbose at the bottom
pub enum LogLevel {
Expand Down Expand Up @@ -66,7 +66,7 @@ impl CustomLogOutput {
(level as u8) <= self.log_level.load(Ordering::SeqCst)
}

/// Sets the log level for allfmt
/// Sets the log level for prjfmt
pub fn set_log_level(&self, log_level: LogLevel) {
self.log_level.store(log_level as u8, Ordering::SeqCst);
}
Expand Down Expand Up @@ -101,7 +101,7 @@ impl CustomLogOutput {
pub fn error(&self, message: &str) {
if self.is_log_enabled(LogLevel::Error) {
let err = format!(
"{}{}: {}",
"{} {}: {}",
emoji::ERROR,
style("[ERR]").bold().dim(),
message
Expand Down
10 changes: 5 additions & 5 deletions src/emoji.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! Emoji contants used by `allfmt`.
//! Emoji contants used by `prjfmt`.
#![allow(missing_docs)]

use console::Emoji;

pub static FOLDER: Emoji = Emoji("📂 ", "");
pub static WARN: Emoji = Emoji("⚠️ ", ":-)");
pub static ERROR: Emoji = Emoji("⛔ ", "");
pub static INFO: Emoji = Emoji("ℹ️ ", "");
pub static FOLDER: Emoji = Emoji("📂", "");
pub static WARN: Emoji = Emoji("⚠️", ":-)");
pub static ERROR: Emoji = Emoji("⛔", "");
pub static INFO: Emoji = Emoji("ℹ️", "");
49 changes: 49 additions & 0 deletions src/formatters/check.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use super::tool::FileMeta;
use crate::formatters::manifest::RootManifest;
use crate::formatters::tool::{create_command_context, CmdContext};
use crate::CLOG;
use anyhow::{anyhow, Error, Result};
use std::collections::BTreeSet;
use std::path::PathBuf;
use std::vec::Vec;

/// Checking content of cache's file and current prjfmt runs
pub fn check_prjfmt(
prjfmt_toml: &PathBuf,
cmd_context: &Vec<CmdContext>,
cache: &RootManifest,
) -> Result<Vec<CmdContext>> {
let cache_context = cache.manifest.values().map(|b| b).into_iter();
let results = cmd_context.into_iter().zip(cache_context);

let cache_context: Vec<CmdContext> = results
.clone()
.map(|(a, b)| {
Ok(CmdContext {
command: a.command.clone(),
args: a.args.clone(),
metadata: a.metadata.difference(&b.metadata).cloned().collect(),
})
})
.collect::<Result<Vec<CmdContext>, Error>>()?;

if cache_context.iter().all(|f| f.metadata.is_empty()) {
CLOG.warn(&format!("No changes found in {}", prjfmt_toml.display()));
return Ok(Vec::new());
}

CLOG.warn(&format!("The following file has changed or newly added:"));
for cmd in &cache_context {
if !cmd.metadata.is_empty() {
for p in &cmd.metadata {
CLOG.warn(&format!(
" - {} last modification time: {}",
p.path.display(),
p.mtimes
));
}
}
}
// return Err(anyhow!("prjfmt failed to run."));
Ok(cache_context)
}
Loading

0 comments on commit 19f77cf

Please sign in to comment.