1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4use anyhow::Error;
5use fidl::endpoints::{ClientEnd, ProtocolMarker};
67use glob::glob;
89/// Connects to a protocol served at a path that matches a glob pattern.
10///
11/// Returns a proxy to the first path that matches a pattern in `glob_paths`,
12/// or None if no matching paths exist.
13pub fn connect_in_paths<T: ProtocolMarker>(glob_paths: &[&str]) -> Result<Option<T::Proxy>, Error> {
14let proxy = glob_paths
15 .iter()
16 .map(|glob_path| {
17let found_path = glob(glob_path)?.find_map(Result::ok);
18match found_path {
19Some(path) => {
20let (client, server) = zx::Channel::create();
21 fdio::service_connect(path.to_string_lossy().as_ref(), server)?;
22let client_end = ClientEnd::<T>::new(client);
23Ok(Some(client_end.into_proxy()))
24 }
25None => Ok(None),
26 }
27 })
28 .collect::<Result<Vec<Option<T::Proxy>>, Error>>()?
29.into_iter()
30 .find(|proxy| proxy.is_some())
31 .flatten();
32Ok(proxy)
33}