From 6b3235737567de8b0c00885a653b6fd432083ca9 Mon Sep 17 00:00:00 2001 From: kyu08 <49891479+kyu08@users.noreply.github.com> Date: Sat, 30 Nov 2024 16:48:47 +0900 Subject: [PATCH] feat(runner): support pnpm (#334) * feat(runner): support pnpm * parse package.json` * refactor: get_commands_from_history * refactor: RunnerType::to_runner * refactor(make): search command in Make struct before show and execute it * runner(pnpm): command_to_run, to_commands * runner(pnpm): execute * wip add ut * add(test): parse_package_json * JsPackageManager::new * move test data to test_data directory --- .gitignore | 1 + CREDITS | 233 +++++++++++++++++++++ Cargo.lock | 61 ++++++ Cargo.toml | 2 + Makefile | 25 +-- src/model/js_package_manager.rs | 218 +++++++++++++++++++ src/model/make.rs | 69 ++++-- src/model/mod.rs | 1 + src/model/pnpm.rs | 49 ++++- src/model/runner.rs | 21 +- src/model/runner_type.rs | 24 ++- src/usecase/tui/app.rs | 58 +++-- test_data/Makefile | 29 +++ {makefiles => test_data/makefiles}/test.mk | 1 - test_data/package.json | 16 ++ test_data/pnpm-lock.yaml | 0 16 files changed, 719 insertions(+), 89 deletions(-) create mode 100644 src/model/js_package_manager.rs create mode 100644 test_data/Makefile rename {makefiles => test_data/makefiles}/test.mk (99%) create mode 100644 test_data/package.json create mode 100644 test_data/pnpm-lock.yaml diff --git a/.gitignore b/.gitignore index b54601ae..48521447 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target /test_dir +fzf-make diff --git a/CREDITS b/CREDITS index 506b6e37..417ef611 100644 --- a/CREDITS +++ b/CREDITS @@ -1120,3 +1120,236 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +================================================================ + +json-spanned-value +https://github.com/MaulingMonkey/json-spanned-value +---------------------------------------------------------------- +MIT License + +Copyright (C) 2020 MaulingMonkey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +================================================================ + +codespan +https://github.com/brendanzab/codespan +---------------------------------------------------------------- + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/Cargo.lock b/Cargo.lock index 5fab436f..2df7cc26 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -80,6 +80,25 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "codespan" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3362992a0d9f1dd7c3d0e89e0ab2bb540b7a95fea8cd798090e758fda2899b5e" +dependencies = [ + "codespan-reporting", +] + +[[package]] +name = "codespan-reporting" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +dependencies = [ + "termcolor", + "unicode-width 0.1.13", +] + [[package]] name = "colored" version = "2.1.0" @@ -188,9 +207,11 @@ name = "fzf-make" version = "0.38.0" dependencies = [ "anyhow", + "codespan", "colored", "crossterm", "fuzzy-matcher", + "json-spanned-value", "portable-pty", "pretty_assertions", "ratatui", @@ -296,6 +317,16 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +[[package]] +name = "json-spanned-value" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb343fa4e3b1b22b344937deedac88da995abf139c2232cbeaa436c38380a210" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "lazy_static" version = "1.4.0" @@ -584,6 +615,18 @@ dependencies = [ "syn 2.0.89", ] +[[package]] +name = "serde_json" +version = "1.0.133" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", +] + [[package]] name = "serde_spanned" version = "0.6.7" @@ -746,6 +789,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "termios" version = "0.2.2" @@ -951,6 +1003,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +dependencies = [ + "windows-sys 0.52.0", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index 866ac9b9..66d65e93 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,3 +24,5 @@ toml = "0.8.19" serde = {version = "1.0.204", features = ["derive"]} simple-home-dir = "0.4.0" pretty_assertions = "1.4.1" +json-spanned-value = "0.2.2" +codespan = "0.11.1" diff --git a/Makefile b/Makefile index 1d0a80d3..f03e832e 100644 --- a/Makefile +++ b/Makefile @@ -60,7 +60,7 @@ spell-check: tool-spell-check .PHONY: run run: - @cargo run + @cargo build && mv ./target/debug/fzf-make ./test_data && cd ./test_data && ./fzf-make .PHONY: build build: @@ -77,26 +77,3 @@ build: .PHONY: build-release build-release: @cargo build --verbose --release - -# Targets for test -include ./makefiles/test.mk - -.PHONY: toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target2 -toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target2: - @echo "this is toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target." - - -.PHONY: toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target -toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target: - @echo "this is toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target." - -.PHONY: echo-greeting -echo-greeting: - @echo hello fzf-make! - -.PHONY: cmd -cmd: - @read -p "Do something? y/n:" ans; \ - if [ "$$ans" = y ]; then \ - echo "Doing something..."; \ - fi diff --git a/src/model/js_package_manager.rs b/src/model/js_package_manager.rs new file mode 100644 index 00000000..e52638d4 --- /dev/null +++ b/src/model/js_package_manager.rs @@ -0,0 +1,218 @@ +use super::{command, pnpm, runner, runner_type}; +use crate::file::path_to_content; +use codespan::Files; +use json_spanned_value::{self as jsv, spanned}; +use std::{fs, path::PathBuf}; + +const METADATA_FILE_NAME: &str = "package.json"; +const METADATA_COMMAND_KEY: &str = "scripts"; +const PNPM_LOCKFILE_NAME: &str = "pnpm-lock.yaml"; + +#[allow(dead_code)] +#[derive(Clone, Debug, PartialEq)] +enum JsPackageManager { + Pnpm, + Yarn, +} + +impl JsPackageManager { + fn new(file_names: Vec) -> Option { + for file_name in file_names { + if file_name == PNPM_LOCKFILE_NAME { + return Some(JsPackageManager::Pnpm); + } + } + None + } + + fn to_runner_type(&self) -> runner_type::RunnerType { + match self { + JsPackageManager::Pnpm => runner_type::RunnerType::Pnpm, + JsPackageManager::Yarn => todo!(), + } + } + + fn to_runner( + &self, + command_file_path: PathBuf, + commands: Vec, + ) -> runner::Runner { + match self { + JsPackageManager::Pnpm => { + runner::Runner::PnpmCommand(pnpm::Pnpm::new(command_file_path, commands)) + } + JsPackageManager::Yarn => todo!(), + } + } +} + +pub fn get_js_package_manager_runner(current_dir: PathBuf) -> Option { + let entries = fs::read_dir(current_dir.clone()).unwrap(); + let file_names = entries + .map(|e| e.unwrap().file_name().into_string().unwrap()) + .collect(); + + match JsPackageManager::new(file_names) { + Some(js_package_manager) => { + let commands = match path_to_content::path_to_content(PathBuf::from(METADATA_FILE_NAME)) + { + Ok(c) => parse_package_json(&c, &js_package_manager), + Err(_) => return None, + }; + Some(js_package_manager.to_runner(current_dir.join(METADATA_FILE_NAME), commands)) + } + None => None, + } +} + +fn parse_package_json( + content: &str, + js_package_manager: &JsPackageManager, +) -> Vec { + let mut files = Files::new(); + let file = files.add(METADATA_FILE_NAME, content); + let json_object: spanned::Object = match jsv::from_str(content) { + Ok(e) => e, + Err(_) => return vec![], + }; + + let mut result = vec![]; + for (k, v) in json_object { + if k.as_str() != METADATA_COMMAND_KEY { + continue; + } + + // object is the content of "scripts" key + if let Some(object) = v.as_object() { + for (k, _) in object { + let name = k.to_string(); + let line_number = + files.line_index(file, k.start() as u32).number().to_usize() as u32; + + result.push(command::Command { + runner_type: js_package_manager.to_runner_type(), + name, + file_name: PathBuf::from(METADATA_FILE_NAME), + line_number, + }); + } + }; + break; + } + + result +} + +#[cfg(test)] +mod test { + use crate::model::runner_type; + use pretty_assertions::assert_eq; + + use super::*; + + #[test] + fn test_parse_package_json() { + struct Case { + title: &'static str, + file_content: &'static str, + expected: Vec, + } + + let cases = vec![ + Case { + title: "valid json can be parsed successfully", + file_content: r#"{ + "name": "project", + "version": "1.0.0", + "private": true, + "scripts": { + "build": "echo build", + "start": "echo start", + "test": "echo test" + }, + "devDependencies": { + "@babel/cli": "7.12.10" + }, + "dependencies": { + "firebase": "^8.6.8" + } +} + "#, + expected: vec![ + command::Command { + runner_type: runner_type::RunnerType::Pnpm, + name: "build".to_string(), + file_name: "package.json".into(), + line_number: 6, + }, + command::Command { + runner_type: runner_type::RunnerType::Pnpm, + name: "start".to_string(), + file_name: "package.json".into(), + line_number: 7, + }, + command::Command { + runner_type: runner_type::RunnerType::Pnpm, + name: "test".to_string(), + file_name: "package.json".into(), + line_number: 8, + }, + ], + }, + Case { + title: "empty vec(empty string)", + file_content: "", + expected: vec![], + }, + Case { + title: "empty vec(invalid json)", + file_content: "not a json format", + expected: vec![], + }, + ]; + + for case in cases { + assert_eq!( + case.expected, + parse_package_json(case.file_content, &JsPackageManager::Pnpm), + "\nfailed: 🚨{:?}🚨\n", + case.title, + ); + } + } + + #[test] + fn test_new() { + struct Case { + title: &'static str, + file_names: Vec, + expected: Option, + } + + let cases = vec![ + Case { + title: "pnpm", + file_names: vec![ + ".gitignore".to_string(), + "Makefile".to_string(), + "pnpm-lock.yaml".to_string(), + ], + expected: Some(JsPackageManager::Pnpm), + }, + Case { + title: "no js package manager found", + file_names: vec![ + ".gitignore".to_string(), + "Makefile".to_string(), + "cargo.toml".to_string(), + ], + expected: None, + }, + ]; + + for case in cases { + let result = JsPackageManager::new(case.file_names); + assert_eq!(case.expected, result, "\nfailed: 🚨{:?}🚨\n", case.title) + } + } +} diff --git a/src/model/make.rs b/src/model/make.rs index 9cd7ef75..b77b2c4e 100644 --- a/src/model/make.rs +++ b/src/model/make.rs @@ -16,8 +16,18 @@ pub struct Make { } impl Make { - pub fn command_to_run(command: &command::Command) -> String { - format!("make {}", command.name) + /// It is possible to implement this method as an associated function because it takes a + /// command as an argument. However, if it is an associated function, it can be called + /// from anywhere, so it is better to make it a method to limit the context. + pub fn command_to_run(&self, command: &command::Command) -> Result { + // To ensure that the command exists, it is necessary to check the command name. + // If implementation is wrong, developers can notice it here. + let command = match self.get_command(command.clone()) { + Some(c) => c, + None => return Err(anyhow!("command not found")), + }; + + Ok(format!("make {}", command.name)) } pub fn new(current_dir: PathBuf) -> Result { @@ -27,6 +37,40 @@ impl Make { Make::new_internal(Path::new(&makefile_name).to_path_buf()) } + pub fn to_commands(&self) -> Vec { + let mut result: Vec = vec![]; + result.append(&mut self.targets.0.to_vec()); + for include_file in &self.include_files { + Vec::append(&mut result, &mut include_file.to_commands()); + } + + result + } + + pub fn execute(&self, command: &command::Command) -> Result<()> { + let command = match self.get_command(command.clone()) { + Some(c) => c, + None => return Err(anyhow!("command not found")), + }; + + let child = process::Command::new("make") + .stdin(process::Stdio::inherit()) + .arg(&command.name) + .spawn(); + + match child { + Ok(mut child) => match child.wait() { + Ok(_) => Ok(()), + Err(e) => Err(anyhow!("failed to run: {}", e)), + }, + Err(e) => Err(anyhow!("failed to spawn: {}", e)), + } + } + + fn get_command(&self, command: command::Command) -> Option<&command::Command> { + self.targets.0.iter().find(|c| **c == command) + } + // I gave up writing tests using temp_dir because it was too difficult (it was necessary to change the implementation to some extent). // It is not difficult to ensure that it works with manual tests, so I will not do it for now. fn new_internal(path: PathBuf) -> Result { @@ -46,16 +90,6 @@ impl Make { }) } - pub fn to_commands(&self) -> Vec { - let mut result: Vec = vec![]; - result.append(&mut self.targets.0.to_vec()); - for include_file in &self.include_files { - Vec::append(&mut result, &mut include_file.to_commands()); - } - - result - } - fn specify_makefile_name(current_dir: PathBuf, target_path: String) -> Option { // By default, when make looks for the makefile, it tries the following names, in order: GNUmakefile, makefile and Makefile. // https://www.gnu.org/software/make/manual/make.html#Makefile-Names @@ -84,17 +118,6 @@ impl Make { None } - pub fn execute(&self, command: &command::Command) -> Result<()> { - process::Command::new("make") - .stdin(process::Stdio::inherit()) - .arg(&command.name) - .spawn() - .expect("Failed to execute process") - .wait() - .expect("Failed to execute process"); - Ok(()) - } - #[cfg(test)] pub fn new_for_test() -> Make { use super::runner_type; diff --git a/src/model/mod.rs b/src/model/mod.rs index 2e5d0263..05b13bf9 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -1,6 +1,7 @@ pub(super) mod command; mod file_util; pub(crate) mod histories; +pub(super) mod js_package_manager; pub(super) mod make; pub(super) mod pnpm; pub(super) mod runner; diff --git a/src/model/pnpm.rs b/src/model/pnpm.rs index 8d150053..0a24de5c 100644 --- a/src/model/pnpm.rs +++ b/src/model/pnpm.rs @@ -1,8 +1,55 @@ use super::command; -use std::path::PathBuf; +use anyhow::{anyhow, Result}; +use std::{path::PathBuf, process}; #[derive(Clone, Debug, PartialEq)] pub struct Pnpm { pub path: PathBuf, commands: Vec, } + +impl Pnpm { + pub fn command_to_run(&self, command: &command::Command) -> Result { + // To ensure that the command exists, it is necessary to check the command name. + // If implementation is wrong, developers can notice it here. + let command = match self.get_command(command.clone()) { + Some(c) => c, + None => return Err(anyhow!("command not found")), + }; + + Ok(format!("pnpm run {}", command.name)) + } + + pub fn to_commands(&self) -> Vec { + self.commands.clone() + } + + pub fn new(path: PathBuf, commands: Vec) -> Pnpm { + Pnpm { path, commands } + } + + fn get_command(&self, command: command::Command) -> Option<&command::Command> { + self.commands.iter().find(|c| **c == command) + } + + pub fn execute(&self, command: &command::Command) -> Result<()> { + let command = match self.get_command(command.clone()) { + Some(c) => c, + None => return Err(anyhow!("command not found")), + }; + + let child = process::Command::new("pnpm") + .stdin(process::Stdio::inherit()) + .arg("run") + .arg(&command.name) + .spawn(); + + match child { + Ok(mut child) => match child.wait() { + Ok(_) => Ok(()), + Err(e) => Err(anyhow!("failed to run: {}", e)), + }, + Err(e) => Err(anyhow!("failed to spawn: {}", e)), + } + } +} diff --git a/src/model/runner.rs b/src/model/runner.rs index 9a8028ae..1b3bfed5 100644 --- a/src/model/runner.rs +++ b/src/model/runner.rs @@ -3,7 +3,6 @@ use anyhow::Result; use colored::Colorize; use std::path::PathBuf; -#[allow(dead_code)] #[derive(Debug, Clone, PartialEq)] pub enum Runner { MakeCommand(make::Make), @@ -14,29 +13,35 @@ impl Runner { pub fn list_commands(&self) -> Vec { match self { Runner::MakeCommand(make) => make.to_commands(), - Runner::PnpmCommand(_) => todo!(), + Runner::PnpmCommand(pnpm) => pnpm.to_commands(), } } pub fn path(&self) -> PathBuf { match self { Runner::MakeCommand(make) => make.path.clone(), - Runner::PnpmCommand(_) => todo!(), + Runner::PnpmCommand(pnpm) => pnpm.path.clone(), } } pub fn show_command(&self, command: &command::Command) { - let command_to_run = match self { - Runner::MakeCommand(_) => make::Make::command_to_run(command), - Runner::PnpmCommand(_) => todo!(), + let command_or_error_message = match self { + Runner::MakeCommand(make) => make.command_to_run(command), + Runner::PnpmCommand(pnpm) => pnpm.command_to_run(command), }; - println!("{}", (command_to_run).truecolor(161, 220, 156)); + + println!( + "{}", + command_or_error_message + .unwrap_or_else(|e| e.to_string()) + .truecolor(161, 220, 156) + ); } pub fn execute(&self, command: &command::Command) -> Result<()> { match self { Runner::MakeCommand(make) => make.execute(command), - Runner::PnpmCommand(_) => todo!(), + Runner::PnpmCommand(pnpm) => pnpm.execute(command), } } } diff --git a/src/model/runner_type.rs b/src/model/runner_type.rs index 967883b4..4492c193 100644 --- a/src/model/runner_type.rs +++ b/src/model/runner_type.rs @@ -2,25 +2,29 @@ use super::runner; use serde::{Deserialize, Serialize}; use std::fmt; -#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)] +#[derive(Hash, PartialEq, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum RunnerType { Make, Pnpm, } +impl std::cmp::Eq for RunnerType {} + impl RunnerType { pub fn to_runner(&self, runners: &Vec) -> Option { - match self { - RunnerType::Make => { - for r in runners { - if matches!(r, runner::Runner::MakeCommand(_)) { - return Some(r.clone()); - } - } - None + for r in runners { + if self.clone() == RunnerType::from(r) { + return Some(r.clone()); } - RunnerType::Pnpm => todo!("implement and write test"), + } + None + } + + pub fn from(runner: &runner::Runner) -> Self { + match runner { + runner::Runner::MakeCommand(_) => RunnerType::Make, + runner::Runner::PnpmCommand(_) => RunnerType::Pnpm, } } } diff --git a/src/usecase/tui/app.rs b/src/usecase/tui/app.rs index 59504697..2a4dc50f 100644 --- a/src/usecase/tui/app.rs +++ b/src/usecase/tui/app.rs @@ -5,6 +5,7 @@ use crate::{ model::{ command, histories::{self}, + js_package_manager::get_js_package_manager_runner, make::Make, runner, runner_type, }, @@ -101,29 +102,33 @@ impl Model<'_> { result } + /// get command from history and filter commands that no longer exist. fn get_commands_from_history( history_commands: Vec, runners: &Vec, ) -> Vec { - // TODO: Make this more readable and more performant. + // make a hashmap in order to search commands by O(1). + let command_hash_map: HashMap> = { + let mut map: HashMap> = + HashMap::new(); + for runner in runners { + let mut inner_map = HashMap::new(); + for c in runner.list_commands() { + inner_map.insert(c.name.clone(), c); + } + map.insert(runner_type::RunnerType::from(runner), inner_map); + } + + map + }; + let mut commands: Vec = Vec::new(); for history_command in history_commands { - match history_command.runner_type { - runner_type::RunnerType::Make => { - for runner in runners { - if let runner::Runner::MakeCommand(make) = runner { - // PERF: This method is called every time. Memoize should be considered. - for c in make.to_commands() { - if c.name == history_command.name { - commands.push(c); - break; - } - } - } - } + if let Some(inner_map) = command_hash_map.get(&history_command.runner_type) { + if let Some(c) = inner_map.get(&history_command.name) { + commands.push(c.clone()); } - runner_type::RunnerType::Pnpm => todo!(), - }; + } } commands } @@ -336,18 +341,27 @@ impl SelectCommandState<'_> { Ok(d) => d, Err(e) => bail!("Failed to get current directory: {}", e), }; - let makefile = match Make::new(current_dir.clone()) { - Err(e) => return Err(e), - Ok(f) => f, - }; let current_pane = if config.get_focus_history() { CurrentPane::History } else { CurrentPane::Main }; - let runner = { runner::Runner::MakeCommand(makefile) }; - let runners = vec![runner]; + + let runners = { + let mut runners = vec![]; + + match Make::new(current_dir.clone()) { + Err(e) => return Err(e), + Ok(f) => { + runners.push(runner::Runner::MakeCommand(f)); + } + }; + if let Some(js_package_manager) = get_js_package_manager_runner(current_dir.clone()) { + runners.push(js_package_manager); + }; + runners + }; Ok(SelectCommandState { current_dir: current_dir.clone(), diff --git a/test_data/Makefile b/test_data/Makefile new file mode 100644 index 00000000..421c8f1e --- /dev/null +++ b/test_data/Makefile @@ -0,0 +1,29 @@ +export +RUST_BACKTRACE=full + +.PHONY: run2 +run2: + cd test_data && cargo run + +# Targets for test +include ./makefiles/test.mk + +.PHONY: toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target2 +toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target2: + @echo "this is toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target." + + +.PHONY: toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target +toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target: + @echo "this is toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo-long-target." + +.PHONY: echo-greeting +echo-greeting: + @echo hello fzf-make! + +.PHONY: cmd +cmd: + @read -p "Do something? y/n:" ans; \ + if [ "$$ans" = y ]; then \ + echo "Doing something..."; \ + fi diff --git a/makefiles/test.mk b/test_data/makefiles/test.mk similarity index 99% rename from makefiles/test.mk rename to test_data/makefiles/test.mk index 9de43920..260956ec 100644 --- a/makefiles/test.mk +++ b/test_data/makefiles/test.mk @@ -2,4 +2,3 @@ .PHONY: echo-test2-test-mk echo-test2-test-mk: @echo "test2" - diff --git a/test_data/package.json b/test_data/package.json new file mode 100644 index 00000000..a35318f8 --- /dev/null +++ b/test_data/package.json @@ -0,0 +1,16 @@ +{ + "name": "project", + "version": "1.0.0", + "private": true, + "scripts": { + "build": "echo build", + "start": "echo start", + "test": "echo test" + }, + "devDependencies": { + "@babel/cli": "7.12.10" + }, + "dependencies": { + "firebase": "^8.6.8" + } +} diff --git a/test_data/pnpm-lock.yaml b/test_data/pnpm-lock.yaml new file mode 100644 index 00000000..e69de29b