Skip to content

Commit

Permalink
- calculate relative url for protobufs.
Browse files Browse the repository at this point in the history
  • Loading branch information
laststylebender14 committed Jun 13, 2024
1 parent 8d0964c commit 3e1207e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
24 changes: 22 additions & 2 deletions src/cli/generator.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::fs;
use std::path::Path;
use std::{env, fs};

use inquire::Confirm;

Expand All @@ -9,12 +9,27 @@ use crate::core::generator::{Generator, GeneratorConfig, GeneratorInput, InputSo
use crate::core::proto_reader::ProtoReader;
use crate::core::resource_reader::ResourceReader;
use crate::core::runtime::TargetRuntime;
use pathdiff::diff_paths;

/// Checks if file or folder already exists or not.
fn is_exists(path: &str) -> bool {
fs::metadata(path).is_ok()
}

/// Expects both paths to be absolute and returns a relative path from `from` to `to`.
fn to_relative(from: &str, to: &str) -> Option<String> {
let mut from_path = Path::new(from).to_path_buf();
let to_path = Path::new(to).to_path_buf();

// Ensure `from` is a directory by getting its parent if it is a file
if from_path.is_file() {
from_path = from_path.parent()?.to_path_buf();
}

// Calculate the relative path from `from_path` to `to_path`
diff_paths(&to_path, &from_path).map(|p| p.to_string_lossy().to_string())
}

pub struct ConfigConsoleGenerator {
config_path: String,
runtime: TargetRuntime,
Expand Down Expand Up @@ -109,7 +124,12 @@ impl ConfigConsoleGenerator {
});
}
ImportSource::Proto => {
let metadata = proto_reader.read(&src).await?;
let mut metadata = proto_reader.read(&src).await?;
if let Some(relative_path_to_proto) =
to_relative(&config.output.file, &src)
{
metadata.path = relative_path_to_proto;
}
generator_type_inputs.push(GeneratorInput::Proto { metadata });
}
}
Expand Down
6 changes: 5 additions & 1 deletion src/core/generator/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::marker::PhantomData;
use std::path::Path;
use std::{env, marker::PhantomData};

use path_clean::PathClean;
use schemars::JsonSchema;
Expand All @@ -26,6 +26,10 @@ fn resolve(path: &str, parent_dir: Option<&Path>) -> anyhow::Result<String> {
if let Ok(abs_path) = std::fs::canonicalize(&joined_path) {
return Ok(abs_path.to_string_lossy().to_string());
}
if let Ok(cwd) = env::current_dir() {
return Ok(cwd.join(joined_path).clean().to_string_lossy().to_string());
}

Ok(joined_path.clean().to_string_lossy().to_string())
}

Expand Down

0 comments on commit 3e1207e

Please sign in to comment.