|
| 1 | +use std::{collections::HashMap, fs, path::Path}; |
| 2 | + |
| 3 | +use fluaterm::{YELLOW, END}; |
| 4 | + |
| 5 | +use crate::run_task; |
| 6 | +use crate::validate_all; |
| 7 | +use crate::parse; |
| 8 | +use crate::RuntimeState; |
| 9 | + |
| 10 | +// Run sth from the samfile |
| 11 | +pub fn run_sam_file(command: &str) { |
| 12 | + let mut state = RuntimeState { |
| 13 | + cwd: std::env::current_dir().unwrap(), |
| 14 | + env: HashMap::new(), |
| 15 | + }; |
| 16 | + |
| 17 | + let content = match std::fs::read_to_string(".samengine/samfile") { |
| 18 | + Ok(c) => c, |
| 19 | + Err(e) => { |
| 20 | + eprintln!("Error while reading samfile: {}", e); |
| 21 | + return; |
| 22 | + } |
| 23 | + }; |
| 24 | + |
| 25 | + let tasks = parse(&content); |
| 26 | + |
| 27 | + // Check for cycled dependencies |
| 28 | + validate_all(&tasks); |
| 29 | + |
| 30 | + // Map which one was already visited |
| 31 | + let mut visited = std::collections::HashSet::new(); |
| 32 | + |
| 33 | + // Execute the Task |
| 34 | + run_task(&tasks, command, &mut visited, &mut state); |
| 35 | +} |
| 36 | + |
| 37 | +fn has_gitignore(dir: &str) -> bool { |
| 38 | + Path::new(dir).join(".gitignore").exists() |
| 39 | +} |
| 40 | + |
| 41 | +fn read_gitignore(dir: &str) -> Option<String> { |
| 42 | + let path = std::path::Path::new(dir).join(".gitignore"); |
| 43 | + |
| 44 | + fs::read_to_string(path).ok() |
| 45 | +} |
| 46 | + |
| 47 | +fn is_samfile_ignored(gitignore_content: &str) -> bool { |
| 48 | + gitignore_content |
| 49 | + .lines() |
| 50 | + .any(|line| line.trim() == "samfile") |
| 51 | +} |
| 52 | + |
| 53 | +// Create new samfile |
| 54 | +pub fn init() { |
| 55 | + let dir = std::path::Path::new(".samengine"); |
| 56 | + let file = dir.join("samfile"); |
| 57 | + |
| 58 | + // check first if exists |
| 59 | + if dir.exists() && file.exists() { |
| 60 | + println!("samefile already exists — aborting init"); |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + println!("Creating a new samfile!"); |
| 65 | + |
| 66 | + // Create .samengine Directory |
| 67 | + std::fs::create_dir_all(dir) |
| 68 | + .expect("failed to create directory"); |
| 69 | + |
| 70 | + std::fs::write( |
| 71 | + &file, |
| 72 | + "# A new samfile, write your scripts here" |
| 73 | + ) |
| 74 | + .expect("failed to create file"); |
| 75 | + |
| 76 | + let dir2 = std::env::current_dir() |
| 77 | + .unwrap() |
| 78 | + .to_str() |
| 79 | + .unwrap() |
| 80 | + .to_string(); |
| 81 | + |
| 82 | + // Check if there is a gitignore |
| 83 | + if has_gitignore(&dir2) { |
| 84 | + if let Some(content) = read_gitignore(&dir2) { |
| 85 | + if is_samfile_ignored(&content) { |
| 86 | + println!("samfile is ignored by git"); |
| 87 | + } else { |
| 88 | + println!("{}WARN: samfile is NOT ignored{}", YELLOW, END); |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | +} |
0 commit comments