pub trait AppleSdk: Sized + AsRef<Path> {
fn from_directory(path: &Path) -> Result<Self, Error>;
fn is_symlink(&self) -> bool;
fn platform(&self) -> &Platform;
fn version(&self) -> Option<&SdkVersion>;
fn supports_deployment_target(
&self,
target_name: &str,
target_version: &SdkVersion
) -> Result<bool, Error>;
fn find_in_directory(root: &Path) -> Result<Vec<Self>, Error> { ... }
fn find_command_line_tools_sdks() -> Result<Option<Vec<Self>>, Error> { ... }
fn sdk_path(&self) -> SdkPath { ... }
fn as_sdk_path(&self) -> SdkPath { ... }
fn path(&self) -> &Path { ... }
}Expand description
Defines common behavior for types representing Apple SDKs.
Required Methods§
sourcefn from_directory(path: &Path) -> Result<Self, Error>
fn from_directory(path: &Path) -> Result<Self, Error>
Attempt to construct an instance from a filesystem directory.
Implementations will likely error with Error::PathNotSdk or Error::Io if the input path is not an Apple SDK.
sourcefn is_symlink(&self) -> bool
fn is_symlink(&self) -> bool
Whether this SDK path is a symlink.
sourcefn version(&self) -> Option<&SdkVersion>
fn version(&self) -> Option<&SdkVersion>
sourcefn supports_deployment_target(
&self,
target_name: &str,
target_version: &SdkVersion
) -> Result<bool, Error>
fn supports_deployment_target(
&self,
target_name: &str,
target_version: &SdkVersion
) -> Result<bool, Error>
Whether this SDK supports targeting the given target name at specified OS version.
Provided Methods§
sourcefn find_in_directory(root: &Path) -> Result<Vec<Self>, Error>
fn find_in_directory(root: &Path) -> Result<Vec<Self>, Error>
Find Apple SDKs in a specified directory.
Directory entries are often symlinks pointing to other directories.
SDKs are annotated with an is_symlink field to denote when this is
the case. Callers may want to filter out symlinked SDKs to avoid
duplicates.
Examples found in repository?
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
pub fn find_sdks<T: AppleSdk>(&self) -> Result<Vec<T>, Error> {
T::find_in_directory(&self.sdks_path())
}
}
impl AsRef<Path> for PlatformDirectory {
fn as_ref(&self) -> &Path {
&self.path
}
}
impl AsRef<Platform> for PlatformDirectory {
fn as_ref(&self) -> &Platform {
&self.platform
}
}
impl Deref for PlatformDirectory {
type Target = Platform;
fn deref(&self) -> &Self::Target {
&self.platform
}
}
impl PartialEq for PlatformDirectory {
fn eq(&self, other: &Self) -> bool {
self.path.eq(&other.path)
}
}
impl Eq for PlatformDirectory {}
impl PartialOrd for PlatformDirectory {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.path.partial_cmp(&other.path)
}
}
impl Ord for PlatformDirectory {
fn cmp(&self, other: &Self) -> Ordering {
self.path.cmp(&other.path)
}
}
/// A directory containing Apple platforms, SDKs, and other tools.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DeveloperDirectory {
path: PathBuf,
}
impl AsRef<Path> for DeveloperDirectory {
fn as_ref(&self) -> &Path {
&self.path
}
}
impl From<&Path> for DeveloperDirectory {
fn from(p: &Path) -> Self {
Self {
path: p.to_path_buf(),
}
}
}
impl From<PathBuf> for DeveloperDirectory {
fn from(path: PathBuf) -> Self {
Self { path }
}
}
impl From<&PathBuf> for DeveloperDirectory {
fn from(path: &PathBuf) -> Self {
Self { path: path.clone() }
}
}
impl DeveloperDirectory {
/// Resolve an instance from the `DEVELOPER_DIR` environment variable.
///
/// This environment variable is used by convention to override default search
/// locations for the developer directory.
///
/// If `DEVELOPER_DIR` is defined, the value/path is validated for existence
/// and an error is returned if it doesn't exist.
///
/// If `DEVELOPER_DIR` isn't defined, returns `Ok(None)`.
pub fn from_env() -> Result<Option<Self>, Error> {
if let Some(value) = std::env::var_os("DEVELOPER_DIR") {
let path = PathBuf::from(value);
if path.exists() {
Ok(Some(Self { path }))
} else {
Err(Error::PathNotDeveloper(path))
}
} else {
Ok(None)
}
}
/// Attempt to resolve an instance by running `xcode-select`.
///
/// The output from `xcode-select` is implicitly trusted and no validation
/// of the path is performed.
pub fn from_xcode_select() -> Result<Self, Error> {
let output = Command::new("xcode-select")
.args(["--print-path"])
.stderr(Stdio::null())
.output()
.map_err(Error::XcodeSelectRun)?;
if output.status.success() {
// We should arguably use OsString here. Keep it simple until someone
// complains.
let path = String::from_utf8_lossy(&output.stdout);
let path = PathBuf::from(path.trim());
Ok(Self { path })
} else {
Err(Error::XcodeSelectBadStatus(output.status))
}
}
/// Attempt to resolve an instance from the default Xcode.app location.
///
/// This looks for a system installed `Xcode.app` and for the developer
/// directory within. If found, returns `Some`. If not, returns `None`.
pub fn default_xcode() -> Option<Self> {
let path = PathBuf::from(XCODE_APP_DEFAULT_PATH).join(XCODE_APP_RELATIVE_PATH_DEVELOPER);
if path.exists() {
Some(Self { path })
} else {
None
}
}
/// Finds all `Developer` directories for system installed Xcode applications.
///
/// This is a convenience method for [find_system_xcode_applications()] plus
/// resolving the `Developer` directory and filtering on missing items.
///
/// It will return all available `Developer` directories for all Xcode installs
/// under `/Applications`.
pub fn find_system_xcodes() -> Result<Vec<Self>, Error> {
Ok(find_system_xcode_applications()?
.into_iter()
.filter_map(|p| {
let path = p.join(XCODE_APP_RELATIVE_PATH_DEVELOPER);
if path.exists() {
Some(Self { path })
} else {
None
}
})
.collect::<Vec<_>>())
}
/// Attempt to find a Developer Directory using reasonable semantics.
///
/// This is probably what most end-users want to use for resolving the path to a
/// Developer Directory.
///
/// This is a convenience function for calling other APIs on this type to resolve
/// the default instance.
///
/// In priority order:
///
/// 1. `DEVELOPER_DIR`
/// 2. System Xcode.app application.
/// 3. `xcode-select` output.
///
/// Errors only if `DEVELOPER_DIR` is defined and it points to an invalid path.
/// Errors from running `xcode-select` are ignored.
pub fn find_default() -> Result<Option<Self>, Error> {
if let Some(v) = Self::from_env()? {
Ok(Some(v))
} else if let Some(v) = Self::default_xcode() {
Ok(Some(v))
} else if let Ok(v) = Self::from_xcode_select() {
Ok(Some(v))
} else {
Ok(None)
}
}
/// Find the Developer Directory and error if not found.
///
/// This is a wrapper around [Self::find_default()] that will error if no Developer Directory
/// could be found.
pub fn find_default_required() -> Result<Self, Error> {
if let Some(v) = Self::find_default()? {
Ok(v)
} else {
Err(Error::DeveloperDirectoryNotFound)
}
}
/// The filesystem path to this developer directory.
pub fn path(&self) -> &Path {
&self.path
}
/// The path to the directory containing platforms.
pub fn platforms_path(&self) -> PathBuf {
self.path.join("Platforms")
}
/// Find platform directories within this developer directory.
///
/// Platforms are defined by the presence of a `Platforms` directory under
/// the developer directory. This directory layout is only recognized
/// for modern Xcode layouts.
///
/// Returns all discovered instances inside this developer directory.
///
/// The return order is sorted and deterministic.
pub fn platforms(&self) -> Result<Vec<PlatformDirectory>, Error> {
let platforms_path = self.platforms_path();
let dir = match std::fs::read_dir(platforms_path) {
Ok(v) => Ok(v),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
return Ok(vec![]);
} else {
Err(Error::from(e))
}
}
}?;
let mut res = vec![];
for entry in dir {
let entry = entry?;
if let Ok(platform) = PlatformDirectory::from_path(entry.path()) {
res.push(platform);
}
}
// Make deterministic.
res.sort();
Ok(res)
}
/// Find SDKs within this developer directory.
///
/// This is a convenience method for calling [Self::platforms()] +
/// [PlatformDirectory::find_sdks()] and chaining the results.
pub fn sdks<SDK: AppleSdk>(&self) -> Result<Vec<SDK>, Error> {
Ok(self
.platforms()?
.into_iter()
.map(|platform| Ok(platform.find_sdks()?.into_iter()))
.collect::<Result<Vec<_>, Error>>()?
.into_iter()
.flatten()
.collect::<Vec<_>>())
}
}
/// Obtain the path to SDKs within an Xcode Command Line Tools installation.
///
/// Returns [Some] if we found a path in the expected location or [None] otherwise.
pub fn command_line_tools_sdks_directory() -> Option<PathBuf> {
let sdk_path = PathBuf::from(COMMAND_LINE_TOOLS_DEFAULT_PATH).join("SDKs");
if sdk_path.exists() {
Some(sdk_path)
} else {
None
}
}
/// Attempt to resolve all available Xcode applications in an `Applications` directory.
///
/// This function is a convenience method for iterating a directory
/// and filtering for `Xcode*.app` entries.
///
/// No guarantee is made about whether the directory constitutes a working
/// Xcode application.
///
/// The results are sorted according to the directory name. However, `Xcode.app` always
/// sorts first so the default application name is always preferred.
pub fn find_xcode_apps(applications_dir: &Path) -> Result<Vec<PathBuf>, Error> {
let dir = match std::fs::read_dir(applications_dir) {
Ok(v) => Ok(v),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
return Ok(vec![]);
} else {
Err(Error::from(e))
}
}
}?;
let mut res = dir
.into_iter()
.map(|entry| {
let entry = entry?;
let name = entry.file_name();
let file_name = name.to_string_lossy();
if file_name.starts_with("Xcode") && file_name.ends_with(".app") {
Ok(Some(entry.path()))
} else {
Ok(None)
}
})
.collect::<Result<Vec<_>, Error>>()?
.into_iter()
.flatten()
.collect::<Vec<_>>();
// Make deterministic.
res.sort_by(|a, b| match (a.file_name(), b.file_name()) {
(Some(x), _) if x == "Xcode.app" => Ordering::Less,
(_, Some(x)) if x == "Xcode.app" => Ordering::Greater,
(_, _) => a.cmp(b),
});
Ok(res)
}
/// Find all system installed Xcode applications.
///
/// This is a convenience method for [find_xcode_apps()] looking under `/Applications`.
/// This location is typically where Xcode is installed.
pub fn find_system_xcode_applications() -> Result<Vec<PathBuf>, Error> {
find_xcode_apps(&PathBuf::from("/Applications"))
}
/// Represents an SDK version string.
///
/// This type attempts to apply semantic versioning onto SDK version strings
/// without pulling in additional crates.
///
/// The version string is not validated for correctness at construction time:
/// any string can be stored.
///
/// The string is interpreted as a `X.Y` or `X.Y.Z` semantic version string
/// where each component is an integer.
///
/// For ordering, an invalid string is interpreted as the version `0.0.0` and
/// therefore should always sort less than a well-formed version.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SdkVersion {
value: String,
}
impl Display for SdkVersion {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.value.fmt(f)
}
}
impl AsRef<str> for SdkVersion {
fn as_ref(&self) -> &str {
&self.value
}
}
impl From<String> for SdkVersion {
fn from(value: String) -> Self {
Self { value }
}
}
impl From<&str> for SdkVersion {
fn from(s: &str) -> Self {
Self::from(s.to_string())
}
}
impl From<&String> for SdkVersion {
fn from(s: &String) -> Self {
Self::from(s.to_string())
}
}
impl SdkVersion {
fn normalized_version(&self) -> Result<(u8, u8, u8), Error> {
let ints = self
.value
.split('.')
.map(|x| u8::from_str(x).map_err(|_| Error::VersionParse(self.value.to_string())))
.collect::<Result<Vec<_>, Error>>()?;
match ints.len() {
1 => Ok((ints[0], 0, 0)),
2 => Ok((ints[0], ints[1], 0)),
3 => Ok((ints[0], ints[1], ints[2])),
_ => Err(Error::VersionParse(self.value.to_string())),
}
}
/// Resolve a version string that adheres to Rust's semantic version string format.
///
/// The returned string will have the form `X.Y.Z` where all components are
/// integers.
pub fn semantic_version(&self) -> Result<String, Error> {
let (x, y, z) = self.normalized_version()?;
Ok(format!("{x}.{y}.{z}"))
}
}
impl PartialOrd for SdkVersion {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
let a = self.normalized_version().unwrap_or((0, 0, 0));
let b = other.normalized_version().unwrap_or((0, 0, 0));
a.partial_cmp(&b)
}
}
impl Ord for SdkVersion {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
/// Represents an SDK path with metadata parsed from the path.
#[derive(Clone, Debug)]
pub struct SdkPath {
/// The filesystem path.
pub path: PathBuf,
/// The platform this SDK belongs to.
pub platform: Platform,
/// The version of the SDK.
///
/// Only present if the version occurred in the directory name. Use
/// [AppleSdk] to parse SDK directories to reliably obtain the SDK version.
pub version: Option<SdkVersion>,
}
impl Display for SdkPath {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"{} (version: {}) SDK at {}",
self.platform.filesystem_name(),
if let Some(version) = &self.version {
version.value.as_str()
} else {
"unknown"
},
self.path.display()
))
}
}
impl SdkPath {
pub fn from_path(path: impl AsRef<Path>) -> Result<Self, Error> {
let path = path.as_ref().to_path_buf();
let s = path
.file_name()
.ok_or_else(|| Error::PathNotSdk(path.clone()))?
.to_str()
.ok_or_else(|| Error::PathNotSdk(path.clone()))?;
let (prefix, sdk) = s
.rsplit_once('.')
.ok_or_else(|| Error::PathNotSdk(path.clone()))?;
if sdk != "sdk" {
return Err(Error::PathNotSdk(path));
}
// prefix can be a platform name (e.g. `MacOSX`) or a platform name + version
// (e.g. `MacOSX12.4`).
let (platform_name, version) = if let Some(first_digit) = prefix
.chars()
.enumerate()
.find_map(|(i, c)| if c.is_numeric() { Some(i) } else { None })
{
let (name, version) = prefix.split_at(first_digit);
(name, Some(version.to_string().into()))
} else {
(prefix, None)
};
let platform = Platform::from_str(platform_name)?;
Ok(Self {
path,
platform,
version,
})
}
}
/// Defines common behavior for types representing Apple SDKs.
pub trait AppleSdk: Sized + AsRef<Path> {
/// Attempt to construct an instance from a filesystem directory.
///
/// Implementations will likely error with [Error::PathNotSdk] or
/// [Error::Io] if the input path is not an Apple SDK.
fn from_directory(path: &Path) -> Result<Self, Error>;
/// Find Apple SDKs in a specified directory.
///
/// Directory entries are often symlinks pointing to other directories.
/// SDKs are annotated with an `is_symlink` field to denote when this is
/// the case. Callers may want to filter out symlinked SDKs to avoid
/// duplicates.
fn find_in_directory(root: &Path) -> Result<Vec<Self>, Error> {
let dir = match std::fs::read_dir(root) {
Ok(v) => Ok(v),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
return Ok(vec![]);
} else {
Err(Error::from(e))
}
}
}?;
let mut res = vec![];
for entry in dir {
let entry = entry?;
match Self::from_directory(&entry.path()) {
Ok(sdk) => {
res.push(sdk);
}
Err(Error::PathNotSdk(_)) => {}
Err(err) => return Err(err),
}
}
Ok(res)
}
/// Locate SDKs installed as part of the Xcode Command Line Tools.
///
/// This is a convenience method for looking for SDKs in the `SDKs` directory
/// under the default install path for the Xcode Command Line Tools.
///
/// Returns `Ok(None)` if the Xcode Command Line Tools are not present in
/// this directory or doesn't have an `SDKs` directory.
fn find_command_line_tools_sdks() -> Result<Option<Vec<Self>>, Error> {
if let Some(path) = command_line_tools_sdks_directory() {
Ok(Some(Self::find_in_directory(&path)?))
} else {
Ok(None)
}
}More examples
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
pub fn search<SDK: AppleSdk>(&self) -> Result<Vec<SDK>, Error> {
let mut sdks = vec![];
// Track searched locations to avoid redundant work.
let mut searched_platform_dirs = HashSet::new();
let mut searched_sdks_dirs = HashSet::new();
for location in &self.locations {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SearchingLocation(location.clone()));
}
// Expand each location to SDKs.
let resolved = location.resolve_location()?;
let candidate_sdks = match &resolved {
SdkSearchResolvedLocation::None => {
vec![]
}
SdkSearchResolvedLocation::PlatformDirectories(dirs) => dirs
.iter()
// Apply platform filter.
.filter(|dir| {
if let Some(wanted_platform) = &self.platform {
if &dir.platform == wanted_platform {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::PlatformDirectoryInclude(dir.path.clone()));
}
true
} else {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::PlatformDirectoryExclude(dir.path.clone()));
}
false
}
} else {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::PlatformDirectoryInclude(dir.path.clone()));
}
true
}
})
// Apply duplicate search filter.
.filter(|dir| {
if searched_platform_dirs.contains(dir.path()) {
false
} else {
searched_platform_dirs.insert(dir.path().to_path_buf());
true
}
})
.map(|dir| dir.find_sdks::<SDK>())
.collect::<Result<Vec<_>, Error>>()?
.into_iter()
.flatten()
.collect::<Vec<_>>(),
SdkSearchResolvedLocation::SdksDirectory(path) => {
if searched_sdks_dirs.contains(path) {
vec![]
} else {
searched_sdks_dirs.insert(path.clone());
SDK::find_in_directory(path)?
}
}
SdkSearchResolvedLocation::SdkDirectory(path)
| SdkSearchResolvedLocation::SdkDirectoryUnfiltered(path) => {
vec![SDK::from_directory(path)?]
}
};
let mut added_count = 0;
for sdk in candidate_sdks {
let include = if resolved.apply_sdk_filter() {
self.filter_sdk(&sdk)?
} else {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SdkFilterSkip(sdk.sdk_path()));
}
true
};
if include {
sdks.push(sdk);
added_count += 1;
}
}
if location.is_terminal() && added_count > 0 {
break;
}
}
// Sorting should be stable with None variant. But we can avoid the
// overhead.
if self.sorting != SdkSorting::None {
sdks.sort_by(|a, b| self.sorting.compare_version(a.version(), b.version()))
}
Ok(sdks)
}sourcefn find_command_line_tools_sdks() -> Result<Option<Vec<Self>>, Error>
fn find_command_line_tools_sdks() -> Result<Option<Vec<Self>>, Error>
Locate SDKs installed as part of the Xcode Command Line Tools.
This is a convenience method for looking for SDKs in the SDKs directory
under the default install path for the Xcode Command Line Tools.
Returns Ok(None) if the Xcode Command Line Tools are not present in
this directory or doesn’t have an SDKs directory.
sourcefn sdk_path(&self) -> SdkPath
fn sdk_path(&self) -> SdkPath
Obtain an SdkPath represent this SDK.
Examples found in repository?
More examples
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
pub fn search<SDK: AppleSdk>(&self) -> Result<Vec<SDK>, Error> {
let mut sdks = vec![];
// Track searched locations to avoid redundant work.
let mut searched_platform_dirs = HashSet::new();
let mut searched_sdks_dirs = HashSet::new();
for location in &self.locations {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SearchingLocation(location.clone()));
}
// Expand each location to SDKs.
let resolved = location.resolve_location()?;
let candidate_sdks = match &resolved {
SdkSearchResolvedLocation::None => {
vec![]
}
SdkSearchResolvedLocation::PlatformDirectories(dirs) => dirs
.iter()
// Apply platform filter.
.filter(|dir| {
if let Some(wanted_platform) = &self.platform {
if &dir.platform == wanted_platform {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::PlatformDirectoryInclude(dir.path.clone()));
}
true
} else {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::PlatformDirectoryExclude(dir.path.clone()));
}
false
}
} else {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::PlatformDirectoryInclude(dir.path.clone()));
}
true
}
})
// Apply duplicate search filter.
.filter(|dir| {
if searched_platform_dirs.contains(dir.path()) {
false
} else {
searched_platform_dirs.insert(dir.path().to_path_buf());
true
}
})
.map(|dir| dir.find_sdks::<SDK>())
.collect::<Result<Vec<_>, Error>>()?
.into_iter()
.flatten()
.collect::<Vec<_>>(),
SdkSearchResolvedLocation::SdksDirectory(path) => {
if searched_sdks_dirs.contains(path) {
vec![]
} else {
searched_sdks_dirs.insert(path.clone());
SDK::find_in_directory(path)?
}
}
SdkSearchResolvedLocation::SdkDirectory(path)
| SdkSearchResolvedLocation::SdkDirectoryUnfiltered(path) => {
vec![SDK::from_directory(path)?]
}
};
let mut added_count = 0;
for sdk in candidate_sdks {
let include = if resolved.apply_sdk_filter() {
self.filter_sdk(&sdk)?
} else {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SdkFilterSkip(sdk.sdk_path()));
}
true
};
if include {
sdks.push(sdk);
added_count += 1;
}
}
if location.is_terminal() && added_count > 0 {
break;
}
}
// Sorting should be stable with None variant. But we can avoid the
// overhead.
if self.sorting != SdkSorting::None {
sdks.sort_by(|a, b| self.sorting.compare_version(a.version(), b.version()))
}
Ok(sdks)
}
/// Whether an SDK matches our search filter.
///
/// This is exposed as a convenience method to allow custom implementations of
/// SDK searching using the filtering logic on this type.
pub fn filter_sdk<SDK: AppleSdk>(&self, sdk: &SDK) -> Result<bool, Error> {
let sdk_path = sdk.sdk_path();
if let Some(wanted_platform) = &self.platform {
if sdk.platform() != wanted_platform {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SdkFilterExclude(
sdk_path,
format!(
"platform {} != {}",
sdk.platform().filesystem_name(),
wanted_platform.filesystem_name()
),
));
}
return Ok(false);
}
}
if let Some(min_version) = &self.minimum_version {
if let Some(sdk_version) = sdk.version() {
if sdk_version < min_version {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SdkFilterExclude(
sdk_path,
format!(
"SDK version {sdk_version} < minimum version {min_version}"
),
));
}
return Ok(false);
}
} else {
// SDKs without a version always fail.
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SdkFilterExclude(
sdk_path,
format!(
"Unknown SDK version fails to meet minimum version {min_version}"
),
));
}
return Ok(false);
}
}
if let Some(max_version) = &self.maximum_version {
if let Some(sdk_version) = sdk.version() {
if sdk_version > max_version {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SdkFilterExclude(
sdk_path,
format!(
"SDK version {sdk_version} > maximum version {max_version}"
),
));
}
return Ok(false);
}
} else {
// SDKs without a version always fail.
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SdkFilterExclude(
sdk_path,
format!(
"Unknown SDK version fails to meet maximum version {max_version}"
),
));
}
return Ok(false);
}
}
if let Some((target, version)) = &self.deployment_target {
if !sdk.supports_deployment_target(target, version)? {
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SdkFilterExclude(
sdk_path,
format!("does not support deployment target {target}:{version}"),
));
}
return Ok(false);
}
}
if let Some(cb) = &self.progress_callback {
cb(SdkSearchEvent::SdkFilterMatch(sdk_path));
}
Ok(true)
}sourcefn as_sdk_path(&self) -> SdkPath
fn as_sdk_path(&self) -> SdkPath
sdk_path insteadsourcefn path(&self) -> &Path
fn path(&self) -> &Path
Obtain the filesystem path to this SDK.