t_rex/
insert.rs

1use std::{
2    fs,
3    fs::{DirEntry, OpenOptions},
4    path::Path,
5};
6
7use anyhow::{anyhow, bail, Result};
8use console::style;
9
10use crate::utils::{
11    entry_to_file_name, get_padding_digits, get_sorted_files_in_dir, is_valid_name, num_prefix,
12    rename_files_from_index,
13};
14
15pub fn process_insert(page_path: String) -> Result<()> {
16    let page_path = Path::new(&page_path);
17    let page_path_string = page_path.to_string_lossy().to_string();
18    let page_name_os_str = page_path.file_name().ok_or_else(|| {
19        anyhow!(
20            "Couldn't get the file name of the given page path '{}'!",
21            page_path_string
22        )
23    })?;
24    let page_name_string = page_name_os_str.to_string_lossy().to_string();
25
26    if !is_valid_name(&page_name_string) {
27        bail!(
28            "Invalid file name from the given filepath '{}!",
29            page_path_string
30        );
31    };
32    let mut parent_path = page_path.parent().unwrap_or_else(|| Path::new("."));
33    if &parent_path.to_string_lossy() == "" {
34        parent_path = Path::new(".");
35    }
36    let insert_prefix = num_prefix(&page_name_string)?;
37
38    let all_files = get_sorted_files_in_dir(parent_path)?;
39    let (digits_used, digits_needed) = get_padding_digits(&all_files);
40
41    let (after_files, before_files): (Vec<DirEntry>, Vec<DirEntry>) =
42        all_files.into_iter().partition(|f| {
43            num_prefix(&entry_to_file_name(f)).unwrap_or_else(|_| {
44                panic!("invalid file {} in sorted files", entry_to_file_name(f))
45            }) >= insert_prefix
46        });
47
48    let mut renamed_count =
49        rename_files_from_index(after_files, Some(insert_prefix), parent_path, digits_needed)?;
50    if digits_used < digits_needed {
51        renamed_count += rename_files_from_index(before_files, None, parent_path, digits_needed)?;
52    }
53    println!("Successfully renamed {} files!", renamed_count);
54
55    let create_error = |err| {
56        anyhow!(
57            "Error creating the new Docusaurus file '{}' - {}",
58            page_path.to_string_lossy(),
59            err
60        )
61    };
62    let fixed_path = parent_path.join(page_name_os_str);
63    let mut insert_text = "page";
64    if fixed_path.extension().is_none() {
65        fs::create_dir(fixed_path).map_err(create_error)?;
66        insert_text = "directory";
67    } else {
68        OpenOptions::new()
69            .write(true)
70            .create_new(true)
71            .open(fixed_path)
72            .map_err(create_error)?;
73    }
74    println!(
75        "{}",
76        style(format!("Successfully inserted a new {}!", insert_text))
77            .green()
78            .bold()
79            .dim()
80    );
81
82    Ok(())
83}