Struct apple_sdk::PlatformDirectory
source · pub struct PlatformDirectory { /* private fields */ }Expand description
Represents an Apple Platform directory.
This is just a thin abstraction over a filesystem path and a Platform instance.
Equivalence and sorting are implemented in terms of the path component only. The assumption here is the Platform is fully derived from the filesystem path and this derivation is deterministic.
Implementations§
source§impl PlatformDirectory
impl PlatformDirectory
sourcepub fn from_path(path: impl AsRef<Path>) -> Result<Self, Error>
pub fn from_path(path: impl AsRef<Path>) -> Result<Self, Error>
Attempt to construct an instance from a filesystem path.
Examples found in repository?
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
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)
}sourcepub fn path(&self) -> &Path
pub fn path(&self) -> &Path
The filesystem path of this instance.
Examples found in repository?
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)
}sourcepub fn sdks_path(&self) -> PathBuf
pub fn sdks_path(&self) -> PathBuf
The filesystem path to the directory holding SDKs.
The returned path is not validated to exist.
sourcepub fn find_sdks<T: AppleSdk>(&self) -> Result<Vec<T>, Error>
pub fn find_sdks<T: AppleSdk>(&self) -> Result<Vec<T>, Error>
Finds SDKs in this platform directory.
The type of SDK to resolve must be specified by the caller.
This function is a simple wrapper around AppleSdk::find_in_directory() looking
under the Developer/SDKs directory, which is where SDKs are located in platform
directories.
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
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)
}Methods from Deref<Target = Platform>§
sourcepub fn filesystem_name(&self) -> &str
pub fn filesystem_name(&self) -> &str
Obtain the name of this platform as used in filesystem paths.
This is just the platform part of the name without the trailing
.platform. This string appears in the *.platform directory names
as well as in SDK directory names preceding the trailing .sdk and
optional SDK version.
Examples found in repository?
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 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
fn eq(&self, other: &Self) -> bool {
self.filesystem_name().eq(other.filesystem_name())
}
}
impl Eq for Platform {}
impl TryFrom<&str> for Platform {
type Error = Error;
fn try_from(s: &str) -> Result<Self, Self::Error> {
Self::from_str(s)
}
}
impl Platform {
/// Attempt to construct an instance from a filesystem path to a platform directory.
///
/// The argument should be the path of a `*.platform` directory. e.g.
/// `/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform`.
///
/// Will return [Error::PathNotPlatform] if this does not appear to be a known
/// platform path.
pub fn from_platform_path(p: &Path) -> Result<Self, Error> {
let (name, platform) = p
.file_name()
.ok_or_else(|| Error::PathNotPlatform(p.to_path_buf()))?
.to_str()
.ok_or_else(|| Error::PathNotPlatform(p.to_path_buf()))?
.split_once('.')
.ok_or_else(|| Error::PathNotPlatform(p.to_path_buf()))?;
if platform == "platform" {
Self::from_str(name)
} else {
Err(Error::PathNotPlatform(p.to_path_buf()))
}
}
/// Attempt to construct an instance from a target triple.
///
/// The argument should be a target triple of a Rust toolchain. e.g.
/// `x86_64-apple-darwin`.
///
/// Will return [Error::UnknownTarget] if this does not appear to be a known
/// target triple.
pub fn from_target_triple(target: &str) -> Result<Self, Error> {
let platform = match target {
target if target.ends_with("-apple-darwin") => Self::MacOsX,
"i386-apple-ios" | "x86_64-apple-ios" => Self::IPhoneSimulator,
target if target.ends_with("-apple-ios-sim") => Platform::IPhoneSimulator,
target if target.ends_with("-apple-ios") => Platform::IPhoneOs,
target if target.ends_with("-apple-ios-macabi") => Platform::IPhoneOs,
"i386-apple-watchos" => Self::WatchSimulator,
target if target.ends_with("-apple-watchos-sim") => Self::WatchSimulator,
target if target.ends_with("-apple-watchos") => Platform::WatchOs,
"x86_64-apple-tvos" => Self::AppleTvSimulator,
target if target.ends_with("-apple-tvos") => Platform::AppleTvOs,
_ => return Err(Error::UnknownTarget(target.to_string())),
};
Ok(platform)
}
/// Obtain the name of this platform as used in filesystem paths.
///
/// This is just the platform part of the name without the trailing
/// `.platform`. This string appears in the `*.platform` directory names
/// as well as in SDK directory names preceding the trailing `.sdk` and
/// optional SDK version.
pub fn filesystem_name(&self) -> &str {
match self {
Self::AppleTvOs => "AppleTVOS",
Self::AppleTvSimulator => "AppleTVSimulator",
Self::DriverKit => "DriverKit",
Self::IPhoneOs => "iPhoneOS",
Self::IPhoneSimulator => "iPhoneSimulator",
Self::MacOsX => "MacOSX",
Self::WatchOs => "WatchOS",
Self::WatchSimulator => "WatchSimulator",
Self::Unknown(v) => v,
}
}
/// Obtain the directory name of this platform.
///
/// This simply appends `.platform` to [Self::filesystem_name()].
pub fn directory_name(&self) -> String {
format!("{}.platform", self.filesystem_name())
}
/// Obtain the path of this platform relative to a developer directory root.
pub fn path_in_developer_directory(&self, developer_directory: impl AsRef<Path>) -> PathBuf {
developer_directory
.as_ref()
.join("Platforms")
.join(self.directory_name())
}
}
/// Represents an Apple Platform directory.
///
/// This is just a thin abstraction over a filesystem path and a [Platform] instance.
///
/// Equivalence and sorting are implemented in terms of the path component
/// only. The assumption here is the [Platform] is fully derived from the filesystem
/// path and this derivation is deterministic.
pub struct PlatformDirectory {
/// The filesystem path to this directory.
path: PathBuf,
/// The platform within this directory.
platform: Platform,
}
impl PlatformDirectory {
/// Attempt to construct an instance from a filesystem path.
pub fn from_path(path: impl AsRef<Path>) -> Result<Self, Error> {
let path = path.as_ref().to_path_buf();
let platform = Platform::from_platform_path(&path)?;
Ok(Self { path, platform })
}
/// The filesystem path of this instance.
pub fn path(&self) -> &Path {
&self.path
}
/// The filesystem path to the directory holding SDKs.
///
/// The returned path is not validated to exist.
pub fn sdks_path(&self) -> PathBuf {
self.path.join("Developer").join("SDKs")
}
/// Finds SDKs in this platform directory.
///
/// The type of SDK to resolve must be specified by the caller.
///
/// This function is a simple wrapper around [AppleSdk::find_in_directory()] looking
/// under the `Developer/SDKs` directory, which is where SDKs are located in platform
/// directories.
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()
))
}More examples
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
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 {} < minimum version {}",
sdk_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 {} > maximum version {}",
sdk_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)
}sourcepub fn directory_name(&self) -> String
pub fn directory_name(&self) -> String
Obtain the directory name of this platform.
This simply appends .platform to Self::filesystem_name().
sourcepub fn path_in_developer_directory(
&self,
developer_directory: impl AsRef<Path>
) -> PathBuf
pub fn path_in_developer_directory(
&self,
developer_directory: impl AsRef<Path>
) -> PathBuf
Obtain the path of this platform relative to a developer directory root.
Trait Implementations§
source§impl AsRef<Path> for PlatformDirectory
impl AsRef<Path> for PlatformDirectory
source§impl AsRef<Platform> for PlatformDirectory
impl AsRef<Platform> for PlatformDirectory
source§impl Deref for PlatformDirectory
impl Deref for PlatformDirectory
source§impl Ord for PlatformDirectory
impl Ord for PlatformDirectory
source§impl PartialEq<PlatformDirectory> for PlatformDirectory
impl PartialEq<PlatformDirectory> for PlatformDirectory
source§impl PartialOrd<PlatformDirectory> for PlatformDirectory
impl PartialOrd<PlatformDirectory> for PlatformDirectory
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
self and other) and is used by the <=
operator. Read moreimpl Eq for PlatformDirectory
Auto Trait Implementations§
impl RefUnwindSafe for PlatformDirectory
impl Send for PlatformDirectory
impl Sync for PlatformDirectory
impl Unpin for PlatformDirectory
impl UnwindSafe for PlatformDirectory
Blanket Implementations§
source§impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.