1use super::*;
2
3#[must_use]
13pub fn semver_to_version_code(version: &str) -> u32 {
14 let core: &str = version.trim().split(['-', '+']).next().unwrap_or("");
15 let mut parts: Vec<u32> = Vec::with_capacity(3);
16 for segment in core.split('.') {
17 if let Ok(num) = segment.trim().parse::<u32>() {
18 parts.push(num);
19 } else {
20 parts.push(0);
21 }
22 }
23 let major: u32 = parts.first().copied().unwrap_or(0);
24 let minor: u32 = parts.get(1).copied().unwrap_or(0);
25 let patch: u32 = parts.get(2).copied().unwrap_or(0);
26 let code: u32 = major
27 .saturating_mul(10_000)
28 .saturating_add(minor.saturating_mul(100))
29 .saturating_add(patch);
30 code.max(1)
31}
32
33#[must_use]
43pub fn find_euv_config_path(start_dir: &Path) -> Option<PathBuf> {
44 let anchor: &Path = if start_dir.is_file() {
45 start_dir.parent().unwrap_or(start_dir)
46 } else {
47 start_dir
48 };
49 let mut current: Option<&Path> = Some(anchor);
50 while let Some(dir) = current {
51 let candidate: PathBuf = dir.join(EUV_TOML_NAME);
52 if candidate.is_file() {
53 return Some(candidate);
54 }
55 current = dir.parent();
56 }
57 None
58}
59
60pub fn load_euv_config(start_dir: &Path) -> io::Result<Option<LoadedEuvConfig>> {
70 let Some(config_path) = find_euv_config_path(start_dir) else {
71 return Ok(None);
72 };
73 let raw: String = fs::read_to_string(&config_path)?;
74 let parsed: EuvProjectConfig = parse_euv_toml(&raw)?;
75 let project_root: PathBuf = config_path
76 .parent()
77 .map(Path::to_path_buf)
78 .unwrap_or_else(|| start_dir.to_path_buf());
79 Ok(Some(LoadedEuvConfig::new(
80 config_path,
81 project_root,
82 parsed,
83 )))
84}
85
86pub fn parse_euv_toml(raw: &str) -> io::Result<EuvProjectConfig> {
96 let entries: Vec<(String, String, String)> = collect_toml_entries(raw)?;
97 let mut config: EuvProjectConfig = EuvProjectConfig::default();
98 for (section, key, value) in entries.into_iter() {
99 apply_euv_toml_entry(&mut config, §ion, &key, &value)?;
100 }
101 Ok(config)
102}
103
104pub fn resolve_workspace_metadata(start_dir: &Path) -> io::Result<WorkspaceMetadata> {
114 let anchor: &Path = if start_dir.is_file() {
115 start_dir.parent().unwrap_or(start_dir)
116 } else {
117 start_dir
118 };
119 let manifest_path: PathBuf = find_workspace_cargo_toml(anchor)
120 .ok_or_else(|| Error::new(ErrorKind::NotFound, ERR_CARGO_MANIFEST_NOT_FOUND))?;
121 let workspace_root: PathBuf = manifest_path
122 .parent()
123 .map(Path::to_path_buf)
124 .unwrap_or_else(|| anchor.to_path_buf());
125 let root_raw: String = fs::read_to_string(&manifest_path)?;
126 let root_entries: Vec<(String, String, String)> = collect_toml_entries(&root_raw)?;
127 let ws_version: Option<String> =
128 find_toml_string(&root_entries, SECTION_WORKSPACE_PACKAGE, KEY_VERSION)
129 .or_else(|| find_toml_string(&root_entries, SECTION_PACKAGE, KEY_VERSION));
130 let resolved_version: String = ws_version
131 .clone()
132 .unwrap_or_else(|| FALLBACK_CLI_VERSION.to_string());
133 let version_code: u32 = semver_to_version_code(&resolved_version);
134 let mut packages: Vec<WorkspacePackageInfo> = Vec::new();
135 if let Some(root_pkg) = parse_package_info(
136 &manifest_path,
137 &workspace_root,
138 &root_entries,
139 &resolved_version,
140 ) {
141 packages.push(root_pkg);
142 }
143 let members: Vec<String> =
144 find_toml_string_array(&root_entries, SECTION_WORKSPACE, KEY_MEMBERS);
145 for member_rel in members.into_iter() {
146 let member_dir: PathBuf = workspace_root.join(&member_rel);
147 let member_manifest: PathBuf = member_dir.join(CARGO_TOML_NAME);
148 if !member_manifest.is_file() {
149 continue;
150 }
151 if let Ok(member_raw) = fs::read_to_string(&member_manifest)
152 && let Ok(member_entries) = collect_toml_entries(&member_raw)
153 && let Some(pkg_info) = parse_package_info(
154 &member_manifest,
155 &member_dir,
156 &member_entries,
157 &resolved_version,
158 )
159 {
160 packages.push(pkg_info);
161 }
162 }
163 let lock_path: PathBuf = workspace_root.join(CARGO_LOCK_NAME);
164 let wasm_bindgen_version: Option<String> = if lock_path.is_file() {
165 resolve_cargo_lock_package_version(&lock_path, CRATE_WASM_BINDGEN)
166 } else {
167 None
168 };
169 Ok(WorkspaceMetadata::new(
170 workspace_root,
171 manifest_path,
172 resolved_version,
173 version_code,
174 packages,
175 wasm_bindgen_version,
176 ))
177}
178
179#[must_use]
190pub fn resolve_cargo_lock_package_version(lock_path: &Path, package_name: &str) -> Option<String> {
191 let raw: String = fs::read_to_string(lock_path).ok()?;
192 let mut in_package: bool = false;
193 let mut matched_name: bool = false;
194 for line in raw.lines() {
195 let trimmed: &str = line.trim();
196 if trimmed == TOML_PACKAGE_TABLE_HEADER {
197 in_package = true;
198 matched_name = false;
199 continue;
200 }
201 if !in_package {
202 continue;
203 }
204 if trimmed.starts_with('[') {
205 in_package = false;
206 matched_name = false;
207 continue;
208 }
209 if let Some((raw_key, raw_val)) = trimmed.split_once('=') {
210 let key: &str = raw_key.trim();
211 if key == KEY_NAME {
212 if let Ok(val) = parse_toml_string_value(raw_val.trim()) {
213 matched_name = val == package_name;
214 }
215 } else if key == KEY_VERSION
216 && matched_name
217 && let Ok(ver) = parse_toml_string_value(raw_val.trim())
218 {
219 return Some(ver);
220 }
221 }
222 }
223 None
224}
225
226#[must_use]
238pub fn resolve_effective_version(
239 start_dir: &Path,
240 explicit: Option<&str>,
241 config: Option<&EuvProjectConfig>,
242) -> String {
243 if let Some(ver) = explicit.map(str::trim).filter(|val: &&str| !val.is_empty()) {
244 return ver.to_string();
245 }
246 if let Some(cfg) = config
247 && let Some(ver) = cfg.get_app().try_get_version()
248 && !ver.trim().is_empty()
249 {
250 return ver.trim().to_string();
251 }
252 if let Ok(meta) = resolve_workspace_metadata(start_dir) {
253 return meta.get_version().clone();
254 }
255 FALLBACK_CLI_VERSION.to_string()
256}
257
258#[must_use]
270pub fn resolve_effective_package(
271 workspace: &WorkspaceMetadata,
272 config: Option<&EuvProjectConfig>,
273 explicit: Option<&str>,
274) -> Option<String> {
275 if let Some(pkg) = explicit.map(str::trim).filter(|val: &&str| !val.is_empty()) {
276 return Some(pkg.to_string());
277 }
278 if let Some(cfg) = config
279 && let Some(pkg) = cfg.get_app().try_get_package()
280 && !pkg.trim().is_empty()
281 {
282 return Some(pkg.trim().to_string());
283 }
284 if let Some(example) = workspace.find_package(EXAMPLE_PKG_HINT) {
285 return Some(example.get_name().clone());
286 }
287 if let Some(bin_pkg) = workspace
288 .get_packages()
289 .iter()
290 .find(|pkg: &&WorkspacePackageInfo| pkg.get_has_bin())
291 {
292 return Some(bin_pkg.get_name().clone());
293 }
294 workspace
295 .get_packages()
296 .first()
297 .map(|pkg: &WorkspacePackageInfo| pkg.get_name().clone())
298}
299
300fn find_workspace_cargo_toml(start_dir: &Path) -> Option<PathBuf> {
310 let mut nearest: Option<PathBuf> = None;
311 let mut current: Option<&Path> = Some(start_dir);
312 while let Some(dir) = current {
313 let candidate: PathBuf = dir.join(CARGO_TOML_NAME);
314 if candidate.is_file() {
315 if nearest.is_none() {
316 nearest = Some(candidate.clone());
317 }
318 if let Ok(content) = fs::read_to_string(&candidate)
319 && content
320 .lines()
321 .any(|line: &str| line.trim() == TOML_WORKSPACE_HEADER)
322 {
323 return Some(candidate);
324 }
325 }
326 current = dir.parent();
327 }
328 nearest
329}
330
331fn parse_package_info(
344 manifest_path: &Path,
345 crate_dir: &Path,
346 entries: &[(String, String, String)],
347 workspace_version: &str,
348) -> Option<WorkspacePackageInfo> {
349 let name: String = find_toml_string(entries, SECTION_PACKAGE, KEY_NAME)?;
350 let lib_name: String =
351 find_toml_string(entries, SECTION_LIB, KEY_NAME).unwrap_or_else(|| name.replace('-', "_"));
352 let version: String =
353 if find_toml_bool(entries, SECTION_PACKAGE, KEY_VERSION_WORKSPACE).unwrap_or(false) {
354 workspace_version.to_string()
355 } else {
356 find_toml_string(entries, SECTION_PACKAGE, KEY_VERSION)
357 .unwrap_or_else(|| workspace_version.to_string())
358 };
359 let crate_types: Vec<String> = find_toml_string_array(entries, SECTION_LIB, KEY_CRATE_TYPE);
360 let has_cdylib: bool = crate_types.iter().any(|item: &String| item == TOKEN_CDYLIB);
361 let has_bin_section: bool = entries
362 .iter()
363 .any(|(section, _, _): &(String, String, String)| section == SECTION_BIN_ARRAY);
364 let has_main_file: bool = crate_dir.join(SRC_DIR_NAME).join(MAIN_RS_NAME).is_file();
365 let has_bin: bool = has_bin_section || has_main_file;
366 Some(WorkspacePackageInfo::new(
367 name,
368 lib_name,
369 version,
370 manifest_path.to_path_buf(),
371 crate_dir.to_path_buf(),
372 has_cdylib,
373 has_bin,
374 ))
375}
376
377fn collect_toml_entries(raw: &str) -> io::Result<Vec<(String, String, String)>> {
387 let mut entries: Vec<(String, String, String)> = Vec::new();
388 let mut current_section: String = String::new();
389 let mut pending_key: Option<String> = None;
390 let mut pending_val: String = String::new();
391 let mut pending_brackets: i32 = 0;
392 for (line_idx, raw_line) in raw.lines().enumerate() {
393 let stripped: String = strip_toml_comment(raw_line);
394 let trimmed: &str = stripped.trim();
395 if trimmed.is_empty() {
396 continue;
397 }
398 if let Some(active_key) = pending_key.as_ref() {
399 pending_val.push(' ');
400 pending_val.push_str(trimmed);
401 pending_brackets += bracket_balance(trimmed);
402 if pending_brackets <= 0 {
403 entries.push((
404 current_section.clone(),
405 active_key.clone(),
406 pending_val.trim().to_string(),
407 ));
408 pending_key = None;
409 pending_val.clear();
410 pending_brackets = 0;
411 }
412 continue;
413 }
414 if trimmed.starts_with('[') && trimmed.ends_with(']') {
415 let inner: &str = trimmed[1..trimmed.len() - 1].trim();
416 if inner.is_empty() {
417 return Err(Error::new(
418 ErrorKind::InvalidData,
419 format!("{ERR_INVALID_EUV_TOML} at line {}", line_idx + 1),
420 ));
421 }
422 current_section = inner.to_string();
423 continue;
424 }
425 let Some((lhs, rhs)) = trimmed.split_once('=') else {
426 continue;
427 };
428 let key: &str = lhs.trim();
429 let val: &str = rhs.trim();
430 if key.is_empty() {
431 return Err(Error::new(
432 ErrorKind::InvalidData,
433 format!("{ERR_INVALID_EUV_TOML} at line {}", line_idx + 1),
434 ));
435 }
436 let balance: i32 = bracket_balance(val);
437 if balance > 0 {
438 pending_key = Some(key.to_string());
439 pending_val = val.to_string();
440 pending_brackets = balance;
441 } else {
442 entries.push((current_section.clone(), key.to_string(), val.to_string()));
443 }
444 }
445 if pending_key.is_some() {
446 return Err(Error::new(
447 ErrorKind::InvalidData,
448 format!("{ERR_INVALID_EUV_TOML}: unclosed array"),
449 ));
450 }
451 Ok(entries)
452}
453
454fn apply_euv_toml_entry(
467 config: &mut EuvProjectConfig,
468 section: &str,
469 key: &str,
470 raw_value: &str,
471) -> io::Result<()> {
472 if section == SECTION_APP {
473 let app: &mut EuvAppConfig = config.get_mut_app();
474 if key == KEY_NAME {
475 let _: &mut EuvAppConfig = app.set_name(Some(parse_toml_string_value(raw_value)?));
476 } else if key == KEY_VERSION {
477 let _: &mut EuvAppConfig = app.set_version(Some(parse_toml_string_value(raw_value)?));
478 } else if key == KEY_BUNDLE_ID {
479 let _: &mut EuvAppConfig = app.set_bundle_id(Some(parse_toml_string_value(raw_value)?));
480 } else if key == KEY_PACKAGE {
481 let _: &mut EuvAppConfig = app.set_package(Some(parse_toml_string_value(raw_value)?));
482 } else if key == KEY_ICON {
483 let _: &mut EuvAppConfig =
484 app.set_icon(Some(PathBuf::from(parse_toml_string_value(raw_value)?)));
485 } else if key == KEY_DEFAULT_TARGETS {
486 let _: &mut EuvAppConfig = app.set_default_targets(parse_toml_string_array(raw_value)?);
487 } else if key == KEY_RENDER {
488 let _: &mut EuvAppConfig = app.set_render(Some(parse_toml_string_value(raw_value)?));
489 }
490 } else if section == SECTION_BUILD {
491 let build: &mut EuvBuildConfig = config.get_mut_build();
492 if key == KEY_OUT_DIR {
493 let _: &mut EuvBuildConfig =
494 build.set_out_dir(Some(PathBuf::from(parse_toml_string_value(raw_value)?)));
495 } else if key == KEY_BASE {
496 let _: &mut EuvBuildConfig = build.set_base(Some(parse_toml_string_value(raw_value)?));
497 } else if key == KEY_RAW_WASM {
498 let _: &mut EuvBuildConfig = build.set_raw_wasm(parse_toml_bool_value(raw_value)?);
499 } else if key == KEY_SKIP_WASM_OPT {
500 let _: &mut EuvBuildConfig = build.set_skip_wasm_opt(parse_toml_bool_value(raw_value)?);
501 } else if key == KEY_INCLUDE_CLI {
502 let _: &mut EuvBuildConfig = build.set_include_cli(parse_toml_bool_value(raw_value)?);
503 } else if key == KEY_PARALLEL {
504 let _: &mut EuvBuildConfig = build.set_parallel(parse_toml_bool_value(raw_value)?);
505 } else if key == KEY_ANDROID_API_LEVEL {
506 let parsed_num: u32 = raw_value.trim().parse::<u32>().map_err(|_| {
507 Error::new(
508 ErrorKind::InvalidData,
509 format!("{ERR_INVALID_EUV_TOML}: invalid integer `{raw_value}`"),
510 )
511 })?;
512 let _: &mut EuvBuildConfig = build.set_android_api_level(Some(parsed_num));
513 } else if key == KEY_ANDROID_BUILD_TOOLS {
514 let _: &mut EuvBuildConfig =
515 build.set_android_build_tools(Some(parse_toml_string_value(raw_value)?));
516 } else if key == KEY_IOS_TEAM_ID {
517 let _: &mut EuvBuildConfig =
518 build.set_ios_team_id(Some(parse_toml_string_value(raw_value)?));
519 }
520 } else if section == SECTION_OTA {
521 let ota: &mut EuvOtaConfig = config.get_mut_ota();
522 if key == KEY_PROJECT {
523 let _: &mut EuvOtaConfig = ota.set_project(Some(parse_toml_string_value(raw_value)?));
524 } else if key == KEY_CHANNEL {
525 let _: &mut EuvOtaConfig = ota.set_channel(Some(parse_toml_string_value(raw_value)?));
526 } else if key == KEY_STORE {
527 let _: &mut EuvOtaConfig =
528 ota.set_store(Some(PathBuf::from(parse_toml_string_value(raw_value)?)));
529 } else if key == KEY_SERVER_URL {
530 let _: &mut EuvOtaConfig =
531 ota.set_server_url(Some(parse_toml_string_value(raw_value)?));
532 } else if key == KEY_PROXY_BASE {
533 let _: &mut EuvOtaConfig =
534 ota.set_proxy_base(Some(parse_toml_string_value(raw_value)?));
535 }
536 } else if section == SECTION_DOCS {
537 let docs: &mut EuvDocsConfig = config.get_mut_docs();
538 if key == KEY_SRC {
539 let _: &mut EuvDocsConfig =
540 docs.set_src(Some(PathBuf::from(parse_toml_string_value(raw_value)?)));
541 } else if key == KEY_OUT {
542 let _: &mut EuvDocsConfig =
543 docs.set_out(Some(PathBuf::from(parse_toml_string_value(raw_value)?)));
544 } else if key == KEY_TITLE {
545 let _: &mut EuvDocsConfig = docs.set_title(Some(parse_toml_string_value(raw_value)?));
546 } else if key == KEY_BASE {
547 let _: &mut EuvDocsConfig = docs.set_base(Some(parse_toml_string_value(raw_value)?));
548 } else if key == KEY_WASM {
549 let _: &mut EuvDocsConfig = docs.set_wasm(parse_toml_bool_value(raw_value)?);
550 }
551 }
552 Ok(())
553}
554
555fn find_toml_string(
567 entries: &[(String, String, String)],
568 section: &str,
569 key: &str,
570) -> Option<String> {
571 entries
572 .iter()
573 .find(|(sec, k, _): &&(String, String, String)| sec == section && k == key)
574 .and_then(|(_, _, val): &(String, String, String)| parse_toml_string_value(val).ok())
575}
576
577fn find_toml_bool(entries: &[(String, String, String)], section: &str, key: &str) -> Option<bool> {
589 entries
590 .iter()
591 .find(|(sec, k, _): &&(String, String, String)| sec == section && k == key)
592 .and_then(|(_, _, val): &(String, String, String)| parse_toml_bool_value(val).ok())
593}
594
595fn find_toml_string_array(
607 entries: &[(String, String, String)],
608 section: &str,
609 key: &str,
610) -> Vec<String> {
611 entries
612 .iter()
613 .find(|(sec, k, _): &&(String, String, String)| sec == section && k == key)
614 .and_then(|(_, _, val): &(String, String, String)| parse_toml_string_array(val).ok())
615 .unwrap_or_default()
616}
617
618fn strip_toml_comment(line: &str) -> String {
628 let mut out: String = String::with_capacity(line.len());
629 let mut in_double: bool = false;
630 let mut in_single: bool = false;
631 let mut escaped: bool = false;
632 for ch in line.chars() {
633 if escaped {
634 out.push(ch);
635 escaped = false;
636 continue;
637 }
638 if in_double && ch == '\\' {
639 out.push(ch);
640 escaped = true;
641 continue;
642 }
643 if ch == '"' && !in_single {
644 in_double = !in_double;
645 out.push(ch);
646 continue;
647 }
648 if ch == '\'' && !in_double {
649 in_single = !in_single;
650 out.push(ch);
651 continue;
652 }
653 if ch == '#' && !in_double && !in_single {
654 break;
655 }
656 out.push(ch);
657 }
658 out
659}
660
661fn bracket_balance(text: &str) -> i32 {
671 let mut depth: i32 = 0;
672 let mut in_double: bool = false;
673 let mut in_single: bool = false;
674 let mut escaped: bool = false;
675 for ch in text.chars() {
676 if escaped {
677 escaped = false;
678 continue;
679 }
680 if in_double && ch == '\\' {
681 escaped = true;
682 continue;
683 }
684 if ch == '"' && !in_single {
685 in_double = !in_double;
686 continue;
687 }
688 if ch == '\'' && !in_double {
689 in_single = !in_single;
690 continue;
691 }
692 if !in_double && !in_single {
693 if ch == '[' {
694 depth += 1;
695 } else if ch == ']' {
696 depth -= 1;
697 }
698 }
699 }
700 depth
701}
702
703fn parse_toml_string_value(raw: &str) -> io::Result<String> {
713 let trimmed: &str = raw.trim();
714 if trimmed.len() >= 2 && trimmed.starts_with('\'') && trimmed.ends_with('\'') {
715 return Ok(trimmed[1..trimmed.len() - 1].to_string());
716 }
717 if trimmed.len() >= 2 && trimmed.starts_with('"') && trimmed.ends_with('"') {
718 let inner: &str = &trimmed[1..trimmed.len() - 1];
719 let mut out: String = String::with_capacity(inner.len());
720 let mut chars: Peekable<Chars<'_>> = inner.chars().peekable();
721 while let Some(ch) = chars.next() {
722 if ch == '\\'
723 && let Some(next_ch) = chars.next()
724 {
725 match next_ch {
726 'n' => out.push('\n'),
727 'r' => out.push('\r'),
728 't' => out.push('\t'),
729 '\\' => out.push('\\'),
730 '"' => out.push('"'),
731 other => {
732 out.push('\\');
733 out.push(other);
734 }
735 }
736 } else {
737 out.push(ch);
738 }
739 }
740 return Ok(out);
741 }
742 Err(Error::new(
743 ErrorKind::InvalidData,
744 format!("{ERR_INVALID_EUV_TOML}: expected quoted string, got `{trimmed}`"),
745 ))
746}
747
748fn parse_toml_bool_value(raw: &str) -> io::Result<bool> {
758 let trimmed: &str = raw.trim();
759 if trimmed == TOKEN_TRUE {
760 Ok(true)
761 } else if trimmed == TOKEN_FALSE {
762 Ok(false)
763 } else {
764 Err(Error::new(
765 ErrorKind::InvalidData,
766 format!("{ERR_INVALID_EUV_TOML}: expected boolean, got `{trimmed}`"),
767 ))
768 }
769}
770
771fn parse_toml_string_array(raw: &str) -> io::Result<Vec<String>> {
781 let trimmed: &str = raw.trim();
782 if !trimmed.starts_with('[') || !trimmed.ends_with(']') {
783 return Err(Error::new(
784 ErrorKind::InvalidData,
785 format!("{ERR_INVALID_EUV_TOML}: expected array, got `{trimmed}`"),
786 ));
787 }
788 let inner: &str = trimmed[1..trimmed.len() - 1].trim();
789 if inner.is_empty() {
790 return Ok(Vec::new());
791 }
792 let mut items: Vec<String> = Vec::new();
793 let mut current: String = String::new();
794 let mut in_double: bool = false;
795 let mut in_single: bool = false;
796 let mut escaped: bool = false;
797 for ch in inner.chars() {
798 if escaped {
799 current.push(ch);
800 escaped = false;
801 continue;
802 }
803 if in_double && ch == '\\' {
804 current.push(ch);
805 escaped = true;
806 continue;
807 }
808 if ch == '"' && !in_single {
809 in_double = !in_double;
810 current.push(ch);
811 continue;
812 }
813 if ch == '\'' && !in_double {
814 in_single = !in_single;
815 current.push(ch);
816 continue;
817 }
818 if ch == ',' && !in_double && !in_single {
819 let piece: &str = current.trim();
820 if !piece.is_empty() {
821 items.push(parse_toml_string_value(piece)?);
822 }
823 current.clear();
824 continue;
825 }
826 current.push(ch);
827 }
828 let tail: &str = current.trim();
829 if !tail.is_empty() {
830 items.push(parse_toml_string_value(tail)?);
831 }
832 Ok(items)
833}