From 3e1207ec49f8e5178c11627eb318d7e3e8013f0b Mon Sep 17 00:00:00 2001 From: Ranjit Mahadik <43403528+ranjitmahadik@users.noreply.github.com> Date: Thu, 13 Jun 2024 16:44:23 +0530 Subject: [PATCH] - calculate relative url for protobufs. --- src/cli/generator.rs | 24 ++++++++++++++++++++++-- src/core/generator/config.rs | 6 +++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/cli/generator.rs b/src/cli/generator.rs index ce74460fad..709c25e6ec 100644 --- a/src/cli/generator.rs +++ b/src/cli/generator.rs @@ -1,5 +1,5 @@ +use std::fs; use std::path::Path; -use std::{env, fs}; use inquire::Confirm; @@ -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 { + 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, @@ -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 }); } } diff --git a/src/core/generator/config.rs b/src/core/generator/config.rs index 15882b7adb..e6cecd0c47 100644 --- a/src/core/generator/config.rs +++ b/src/core/generator/config.rs @@ -1,5 +1,5 @@ -use std::marker::PhantomData; use std::path::Path; +use std::{env, marker::PhantomData}; use path_clean::PathClean; use schemars::JsonSchema; @@ -26,6 +26,10 @@ fn resolve(path: &str, parent_dir: Option<&Path>) -> anyhow::Result { 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()) }