use crate::{
errors::PackageError,
imports::ImportsDirectory,
inputs::{InputFile, InputsDirectory, StateFile},
root::{Gitignore, Manifest, README},
source::{LibraryFile, MainFile, SourceDirectory},
};
use serde::Deserialize;
use std::path::Path;
#[derive(Deserialize)]
pub struct Package {
pub name: String,
pub version: String,
pub description: Option<String>,
pub license: Option<String>,
}
impl Package {
pub fn new(package_name: &str) -> Self {
Self {
name: package_name.to_owned(),
version: "0.1.0".to_owned(),
description: None,
license: None,
}
}
pub fn can_initialize(package_name: &str, is_lib: bool, path: &Path) -> bool {
let mut result = true;
let mut existing_files = vec![];
if Manifest::exists_at(path) {
existing_files.push(Manifest::filename());
result = false;
}
if is_lib {
if LibraryFile::exists_at(path) {
existing_files.push(LibraryFile::filename());
result = false;
}
} else {
let input_file = InputFile::new(&package_name);
if input_file.exists_at(path) {
existing_files.push(input_file.filename());
result = false;
}
let state_file = StateFile::new(&package_name);
if state_file.exists_at(path) {
existing_files.push(state_file.filename());
result = false;
}
if MainFile::exists_at(path) {
existing_files.push(MainFile::filename());
result = false;
}
}
if !existing_files.is_empty() {
tracing::error!("File(s) {:?} already exist", existing_files);
}
result
}
pub fn is_initialized(package_name: &str, is_lib: bool, path: &Path) -> bool {
if !Manifest::exists_at(&path) {
return false;
}
if is_lib {
if !LibraryFile::exists_at(&path) {
return false;
}
} else {
let input_file = InputFile::new(&package_name);
if !input_file.exists_at(&path) {
return false;
}
let state_file = StateFile::new(&package_name);
if !state_file.exists_at(&path) {
return false;
}
if !MainFile::exists_at(&path) {
return false;
}
}
true
}
pub fn initialize(package_name: &str, is_lib: bool, path: &Path) -> Result<(), PackageError> {
{
if !Self::can_initialize(package_name, is_lib, path) {
return Err(PackageError::FailedToInitialize(
package_name.to_owned(),
path.as_os_str().to_owned(),
));
}
}
{
Manifest::new(&package_name).write_to(&path)?;
if !Gitignore::exists_at(&path) {
Gitignore::new().write_to(&path)?;
}
if !README::exists_at(&path) {
README::new(package_name).write_to(&path)?;
}
SourceDirectory::create(&path)?;
if is_lib {
LibraryFile::new(&package_name).write_to(&path)?;
} else {
InputsDirectory::create(&path)?;
InputFile::new(&package_name).write_to(&path)?;
StateFile::new(&package_name).write_to(&path)?;
MainFile::new(&package_name).write_to(&path)?;
}
}
{
if !Self::is_initialized(package_name, is_lib, path) {
return Err(PackageError::FailedToInitialize(
package_name.to_owned(),
path.as_os_str().to_owned(),
));
}
}
Ok(())
}
pub fn remove_imported_package(package_name: &str, path: &Path) -> Result<(), PackageError> {
Ok(ImportsDirectory::remove_import(path, package_name)?)
}
}