Skip to content

Commit

Permalink
test: add init command cli test
Browse files Browse the repository at this point in the history
  • Loading branch information
oknozor committed Sep 21, 2020
1 parent 45ac57a commit bd49725
Show file tree
Hide file tree
Showing 10 changed files with 231 additions and 71 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@ tempdir = "^0"
semver = "0.10.0"
moins = "0.4.0"
lazy_static = "1.4.0"
toml = "0.5.6"
clap = { version = "^2", optional = true }

[dev-dependencies]
assert_cmd = "0.10"
predicates = "1"
temp_testdir = "0.2.3"

[features]
Expand Down
10 changes: 8 additions & 2 deletions src/bin/cog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ fn main() -> Result<()> {

let init_subcommand = SubCommand::with_name(INIT)
.settings(SUBCOMMAND_SETTINGS)
.arg(
Arg::with_name("path")
.help("path to init, default")
.default_value("."),
)
.about("Install cog config files");

let on_configured_repo_subcommands =
Expand Down Expand Up @@ -281,8 +286,9 @@ fn main() -> Result<()> {
}

INIT => {
let _subcommand = matches.subcommand_matches(INIT).unwrap();
cocogitto::init()?;
let subcommand = matches.subcommand_matches(INIT).unwrap();
let init_path = subcommand.value_of("path").unwrap(); // safe unwrap via clap default value
cocogitto::init(init_path)?;
}

commit_type => {
Expand Down
2 changes: 1 addition & 1 deletion src/commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub struct CommitMessage {
pub(crate) is_breaking_change: bool,
}

#[derive(Debug, Deserialize, Clone)]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct CommitConfig {
pub changelog_title: String,
pub help_message: String,
Expand Down
62 changes: 55 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ use semver::Version;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::path::{Path, PathBuf};
use std::process::{exit, Command, Stdio};
use tempdir::TempDir;

pub type CommitsMetadata = HashMap<CommitType, CommitConfig>;
Expand All @@ -42,14 +42,62 @@ lazy_static! {
// `Commit` etc. Be ensure that `CocoGitto::new` is called before using this in order to bypass
// unwrapping in case of error.
static ref COMMITS_METADATA: CommitsMetadata = {
let repo = Repository::open().unwrap();
let repo = Repository::open(".").unwrap();
Settings::get(&repo).unwrap().commit_types()
};
}

pub fn init() -> Result<()> {
println!("init command");
todo!();
pub fn init<S: AsRef<Path> + ?Sized>(path: &S) -> Result<()> {
let path = path.as_ref();

if !path.exists() {
std::fs::create_dir(&path)?;
}

let mut is_init_commit = false;
let repository = match Repository::open(&path) {
Ok(repo) => {
println!(
"Found git repository in {}, skipping initialisation",
path.canonicalize()?.display()
);
repo
}
Err(_) => {
let initialisation = Repository::init(&path);
if initialisation.is_ok() {
println!(
"Empty git repository initialized in {}",
path.canonicalize()?.display()
)
}
is_init_commit = true;
initialisation?
}
};

let settings = Settings::default();
let settings_path = path.join("coco.toml");
if settings_path.exists() {
eprint!(
"Found coco.toml in {}, Nothing to do",
path.canonicalize()?.display()
);
exit(1);
} else {
std::fs::write(settings_path, toml::to_string(&settings)?)?;
}

// TODO : add coco only"
repository.add_all()?;
let message = if is_init_commit {
"chore: init commit".to_string()
} else {
"chore: add cocogitto config".to_string()
};

repository.commit(message)?;
Ok(())
}

pub struct CocoGitto {
Expand All @@ -59,7 +107,7 @@ pub struct CocoGitto {

impl CocoGitto {
pub fn get() -> Result<Self> {
let repository = Repository::open()?;
let repository = Repository::open(".")?;
let settings = Settings::get(&repository)?;
let changelog_path = settings
.changelog_path
Expand Down
8 changes: 6 additions & 2 deletions src/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ use std::path::Path;
pub(crate) struct Repository(pub(crate) Git2Repository);

impl Repository {
pub(crate) fn open() -> Result<Repository> {
let repo = Git2Repository::discover(".")?;
pub(crate) fn init<S: AsRef<Path> + ?Sized>(path: &S) -> Result<Repository> {
Ok(Repository(Git2Repository::init(&path)?))
}

pub(crate) fn open<S: AsRef<Path> + ?Sized>(path: &S) -> Result<Repository> {
let repo = Git2Repository::discover(&path)?;
Ok(Repository(repo))
}

Expand Down
14 changes: 13 additions & 1 deletion src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::path::PathBuf;

type CommitsMetadataSettings = HashMap<String, CommitConfig>;

#[derive(Debug, Deserialize)]
#[derive(Debug, Deserialize, Serialize)]
pub(crate) struct Settings {
#[serde(default)]
pub hooks: Vec<String>,
Expand All @@ -19,6 +19,18 @@ pub(crate) struct Settings {
pub changelog_footer: Option<String>,
}

impl Default for Settings {
fn default() -> Self {
Settings {
hooks: vec![],
commit_types: Default::default(),
changelog_path: None,
changelog_header: None,
changelog_footer: None,
}
}
}

impl Settings {
pub(crate) fn get(repository: &Repository) -> Result<Self> {
match repository.get_repo_dir() {
Expand Down
2 changes: 1 addition & 1 deletion src/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl VersionIncrement {

fn get_auto_version(&self, current_version: &Version) -> Result<Version> {
let mut next_version = current_version.clone();
let repository = Repository::open()?;
let repository = Repository::open(".")?;
let changelog_start_oid = repository
.get_latest_tag_oid()
.unwrap_or_else(|_| repository.get_first_commit().unwrap());
Expand Down
57 changes: 57 additions & 0 deletions tests/common.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use anyhow::Result;
use chrono::Utc;
use std::process::{Command, Stdio};

pub fn git_init() -> Result<()> {
let temp_dir = temp_testdir::TempDir::default().permanent();
println!("{:?}", &temp_dir.as_ref());
std::env::set_current_dir(temp_dir.as_ref())?;

println!("on {:?}", std::env::current_dir()?);
println!("git init");

Command::new("git")
.arg("init")
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()?;

Ok(())
}

pub fn git_commit(message: &str) -> Result<()> {
let file_name = Utc::now().timestamp().to_string();
std::fs::write(file_name, "dummy")?;

println!("git add .");
Command::new("git")
.arg("add")
.arg(".")
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()?;

println!("git commit -m \"{}\"", message);
Command::new("git")
.arg("commit")
.arg("-m")
.arg(&format!("\"{}\"", message))
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()?;
Ok(())
}

pub fn _git_tag(tag: &str) -> Result<()> {
Command::new("tag")
.arg(tag)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()?;
Ok(())
}

pub fn create_empty_config() -> Result<()> {
std::fs::File::create("coco.toml")?;
Ok(())
}
59 changes: 2 additions & 57 deletions tests/git_tests.rs
Original file line number Diff line number Diff line change
@@ -1,63 +1,8 @@
use crate::{common::create_empty_config, common::git_commit, common::git_init};
use anyhow::Result;
use chrono::Utc;
use cocogitto::CocoGitto;
use std::process::{Command, Stdio};
use std::time::Duration;

fn git_init() -> Result<()> {
let temp_dir = temp_testdir::TempDir::default().permanent();
println!("{:?}", &temp_dir.as_ref());
std::env::set_current_dir(temp_dir.as_ref())?;

println!("on {:?}", std::env::current_dir()?);
println!("git init");

Command::new("git")
.arg("init")
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()?;

Ok(())
}

fn git_commit(message: &str) -> Result<()> {
std::thread::sleep(Duration::from_millis(100));
let file_name = Utc::now().timestamp().to_string();
std::fs::write(file_name, "dummy")?;

println!("git add .");
Command::new("git")
.arg("add")
.arg(".")
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()?;

println!("git commit -m \"{}\"", message);
Command::new("git")
.arg("commit")
.arg("-m")
.arg(&format!("\"{}\"", message))
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()?;
Ok(())
}

fn _git_tag(tag: &str) -> Result<()> {
Command::new("tag")
.arg(tag)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()?;
Ok(())
}

fn create_empty_config() -> Result<()> {
std::fs::File::create("coco.toml")?;
Ok(())
}
mod common;

#[test]
fn should_open_repo() -> Result<()> {
Expand Down
85 changes: 85 additions & 0 deletions tests/init_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use anyhow::Result;
use assert_cmd::prelude::*;
use std::process::Command;

mod common;

#[test]
#[cfg(not(tarpaulin_include))]
fn init_empty_repo_in_target_dir() -> Result<()> {
let mut command = Command::cargo_bin("cog")?;

command.arg("init").arg("test_repo");

let temp_dir = temp_testdir::TempDir::default();
std::env::set_current_dir(temp_dir.as_ref())?;

command.assert().success();

Ok(())
}

#[test]
#[cfg(not(tarpaulin_include))]
fn init_existing_repo() -> Result<()> {
let temp_dir = temp_testdir::TempDir::default();

let mut command = Command::cargo_bin("cog")?;

command.arg("init").arg("test_repo_existing");

// Create repo with commits
let path = temp_dir.join("test_repo_existing");
std::fs::create_dir(&path)?;
std::env::set_current_dir(&path)?;
common::git_init()?;
common::git_commit("chore: test commit")?;

std::env::set_current_dir(temp_dir.as_ref())?;

command.assert().success();

Ok(())
}

#[test]
#[cfg(not(tarpaulin_include))]
fn fail_if_config_exist() -> Result<()> {
let temp_dir = temp_testdir::TempDir::default();

let mut command = Command::cargo_bin("cog")?;

command.arg("init").arg("test_repo_existing");

// Create repo with commits
let path = temp_dir.join("test_repo_existing");
std::fs::create_dir(&path)?;
std::fs::write(&path.join("coco.toml"), "[hooks]")?;
std::env::set_current_dir(&path)?;
common::git_init()?;
common::git_commit("chore: test commit")?;

std::env::set_current_dir(temp_dir.as_ref())?;

command.assert().failure();

Ok(())
}

#[test]
#[cfg(not(tarpaulin_include))]
fn init_current_dir_with_no_arg() -> Result<()> {
let temp_dir = temp_testdir::TempDir::default();
let path = temp_dir.join("test_repo_no_args");

std::fs::create_dir(&path)?;
let mut command = Command::cargo_bin("cog")?;

command.arg("init");

std::env::set_current_dir(path)?;

command.assert().success();

Ok(())
}

0 comments on commit bd49725

Please sign in to comment.