Skip to content

Commit

Permalink
feat: working on init functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
matzxrr committed Jan 25, 2024
1 parent ba99518 commit 8ebdde4
Show file tree
Hide file tree
Showing 4 changed files with 124 additions and 20 deletions.
43 changes: 37 additions & 6 deletions dotme-core/src/cmd/init.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use std::time::Duration;
use std::{path::PathBuf, thread};
use dialoguer::Confirm;
use std::path::PathBuf;
use thiserror::Error;

use dialoguer::{theme::ColorfulTheme, Error as DialoguerError, Input};

use console::Term;

use crate::path_utils::base_dirs;
use crate::path_utils::{add_to_bashrc, base_dirs};
use crate::repo::{Repo, RepoError};

#[derive(Debug, Error)]
pub enum InitError {
Expand All @@ -16,6 +17,8 @@ pub enum InitError {
IoError(#[from] std::io::Error),
#[error("Dialoguer Error: {0}")]
DialoguerError(#[from] DialoguerError),
#[error("Repo Error: {0}")]
RepoError(#[from] RepoError),
}

type Result<T> = std::result::Result<T, InitError>;
Expand All @@ -24,7 +27,7 @@ pub fn init() -> Result<()> {
let term = Term::stdout();
term.write_line("\n\nSetting up a new dotfile repo\n")?;
let default_path = get_default_path()?;
let input: String = Input::with_theme(&ColorfulTheme::default())
let repo_location: String = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Repo location")
.default(default_path)
.validate_with(|input: &String| {
Expand All @@ -36,9 +39,23 @@ pub fn init() -> Result<()> {
}
})
.interact_text()?;
let repo_location_path = PathBuf::from(repo_location);

term.write_line(&format!(
"\nCreating bare git repository at '{}'",
repo_location_path.display()
))?;
let repo = Repo::create_bare_repo(repo_location_path.as_path())?;
term.write_line(&format!(
"Bare repostiory created at {}",
repo.repo.path().display()
))?;

add_to_bashrc(repo.repo.path()).unwrap();

let repo_config = repo.repo.config().unwrap();
repo_config.get_bool("showUntrackedFiles").expect("exists");

term.write_line(&format!("\nCreating bare git repository at '{}'", input))?;
thread::sleep(Duration::from_millis(2000));
Ok(())
}

Expand All @@ -50,3 +67,17 @@ fn get_default_path() -> Result<String> {
.ok_or(InitError::DefaultPathError)
.map(ToString::to_string)
}

#[cfg(test)]
mod test_init {
use git2::Repository;

use super::*;

#[test]
fn test_init_repo() {
let repo = Repository::open("/home/magreenberg/.test").unwrap();
let config = repo.config().unwrap();
let _val = config.get_string("GIT_SUBMODULE_IGNORE_UNTRACKED").unwrap();
}
}
25 changes: 11 additions & 14 deletions dotme-core/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
use directories::{BaseDirs, ProjectDirs};
use serde_derive::Deserialize;
use std::io::Error as IoError;
use std::{fmt::Display, fs, path::PathBuf};
use toml::de::Error as TomlError;

use crate::path_utils::{base_dirs, project_dirs, PathUtilsError};

#[derive(Debug)]
pub enum ConfigLoadError {
DirectoryError(&'static str),
IoError(IoError),
DeserializeError(TomlError),
PathUtilsError(PathUtilsError),
}

impl From<IoError> for ConfigLoadError {
Expand All @@ -23,12 +25,19 @@ impl From<TomlError> for ConfigLoadError {
}
}

impl From<PathUtilsError> for ConfigLoadError {
fn from(value: PathUtilsError) -> Self {
ConfigLoadError::PathUtilsError(value)
}
}

impl Display for ConfigLoadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConfigLoadError::DirectoryError(e) => write!(f, "Directory error: {}", e),
ConfigLoadError::IoError(e) => write!(f, "IO Error: {}", e),
ConfigLoadError::DeserializeError(e) => write!(f, "Deserialize Error: {}", e),
ConfigLoadError::PathUtilsError(e) => write!(f, "Path Util Error: {}", e),
}
}
}
Expand Down Expand Up @@ -66,7 +75,7 @@ pub struct Config {
}

impl Config {
fn new(repo: PathBuf, work_tree: PathBuf) -> Self {
pub fn new(repo: PathBuf, work_tree: PathBuf) -> Self {
Self { repo, work_tree }
}
fn load(config_string: &str) -> Result<Config> {
Expand All @@ -83,18 +92,6 @@ impl Config {
}
}

fn project_dirs() -> Result<ProjectDirs> {
ProjectDirs::from("", "", "dotme").ok_or(ConfigLoadError::DirectoryError(
"Cannot get project directories",
))
}

fn base_dirs() -> Result<BaseDirs> {
BaseDirs::new().ok_or(ConfigLoadError::DirectoryError(
"Cannot get base directories",
))
}

/// Loads the dotme config
/// Linux Path: ~/.config/dotme/config.toml
pub fn load_dotme_config() -> Result<Config> {
Expand Down
63 changes: 63 additions & 0 deletions dotme-core/src/path_utils.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
use std::{
fs::{self, OpenOptions},
io::{self, BufReader, Write},
path::Path,
process::Command,
};

use directories::{BaseDirs, ProjectDirs};
use thiserror::Error;

Expand All @@ -20,3 +27,59 @@ pub fn base_dirs() -> Result<BaseDirs> {
"Cannot get base directories",
))
}

/*
Command::new("sh")
.arg("-c")
.arg("echo hello")
.output()
.expect("failed to execute process")
Reading bash file
basename $(readlink /proc/$$/exe)
ps -o comm= -p $$
## My Aliases
alias config='/usr/bin/git --git-dir=$HOME/.cfg/ --work-tree=$HOME'
let mut file = OpenOptions::new()
.write(true)
.append(true)
.open("my-file")
.unwrap();
if let Err(e) = writeln!(file, "A new line!") {
eprintln!("Couldn't write to file: {}", e);
}
*/
pub fn add_to_bashrc(path: &Path) -> Result<()> {
let base_dirs = base_dirs()?;
let home_dirs = base_dirs.home_dir();
let bashrc = home_dirs.join(".bashrc");
let _ = home_dirs.join(".");
let alias = format!(
r"alias config='/usr/bin/git --git-dir={} --work-tree=$HOME'",
path.display()
);

let mut file = OpenOptions::new()
.write(true)
.append(true)
.open(bashrc)
.unwrap();

file.write_all(alias.as_bytes()).unwrap();

Ok(())
}

#[cfg(test)]
mod test_path_utils {
use std::path::PathBuf;

use super::*;

#[test]
fn test_add() {
let path = PathBuf::from("/home/magreenberg/.test");
add_to_bashrc(path.as_path()).unwrap();
}
}
13 changes: 13 additions & 0 deletions dotme-core/src/repo.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::path::Path;

use crate::config::{load_dotme_config, Config};
use crate::path_utils::{self, PathUtilsError};
use git2::Error as Git2Error;
use git2::{ErrorCode, Repository};
use thiserror::Error;
Expand All @@ -15,6 +18,8 @@ pub enum RepoError {
UnknownBranch,
#[error("branch name is not valid utf-8")]
BranchNotUtf8,
#[error("path error: {0}")]
PathUtilError(#[from] PathUtilsError),
}

type Result<T> = std::result::Result<T, RepoError>;
Expand Down Expand Up @@ -69,4 +74,12 @@ impl Repo {
.map(|x| x.to_owned())
.ok_or_else(|| RepoError::BranchNotUtf8)
}

pub fn create_bare_repo(path: &Path) -> Result<Repo> {
let base_dirs = path_utils::base_dirs()?;
let workspace_path = base_dirs.home_dir();
let config = Config::new(path.to_path_buf(), workspace_path.to_path_buf());
let repo = Repository::init_bare(path)?;
Ok(Repo { repo, config })
}
}

0 comments on commit 8ebdde4

Please sign in to comment.