### Start Container Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Container.html Asynchronously starts the container instance. Returns a `Result` indicating success or failure. ```rust pub async fn start(&self) -> Result<()> ``` -------------------------------- ### Create and Start Exec Instance Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Creates and starts an execution instance within a container. This allows running commands inside a container and streaming the output. ```APIDOC ## POST /containers/{container_id}/exec ### Description Creates a new exec instance that will be executed in a container. ### Method POST ### Endpoint /containers/{container_id}/exec ### Path Parameters - **container_id** (string) - Required - The ID of the container where the command will be executed. ### Request Body - **opts** (ExecContainerOptions) - Required - Options for the exec instance. - **cmd** (array of strings) - Required - The command to execute. - **attach_stdout** (boolean) - Optional - Whether to attach to the stdout of the command. - **attach_stderr** (boolean) - Optional - Whether to attach to the stderr of the command. ### Request Example ```json { "cmd": ["ls", "-l"], "attach_stdout": true, "attach_stderr": true } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created exec instance. ### Response Example ```json { "id": "exec_instance_id" } ``` ``` -------------------------------- ### Exec::start Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Exec.html Starts this exec instance returning a multiplexed tty stream. ```APIDOC ## POST /exec/{id}/start ### Description Starts this exec instance returning a multiplexed tty stream. ### Method POST ### Endpoint /exec/{id}/start ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the exec instance. ### Response #### Success Response (200) - **Stream** (impl Stream>) - A stream of TtyChunk results. ``` -------------------------------- ### POST /containers/{id}/start Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Starts a stopped container instance. ```APIDOC ## POST /containers/{id}/start ### Description Start the container instance. ### Method POST ### Endpoint /containers/{id}/start ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the container to start. ### Response #### Success Response (200) - **()** - Indicates successful start. #### Response Example ```json {} ``` ``` -------------------------------- ### Start Exec Instance Stream Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Starts an existing exec instance and returns a multiplexed TTY stream. Takes ownership of the Docker reference to avoid tying the stream's lifetime to the `self` instance. ```rust pub fn start(&self) -> impl Stream> + 'docker { // We must take ownership of the docker reference to not needlessly tie the stream to the // lifetime of `self`. let docker = self.docker; // We convert `self.id` into the (owned) endpoint outside of the stream to not needlessly // tie the stream to the lifetime of `self`. let endpoint = format!("/exec/{}/start", &self.id); Box::pin( async move { let stream = Box::pin(docker.stream_post( endpoint, Some(("{}".into(), mime::APPLICATION_JSON)), None::>, )); Ok(tty::decode(stream)) } .try_flatten_stream(), ) } ``` -------------------------------- ### Uri Construction Examples Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Uri.html Demonstrates various ways to parse and construct Uri objects. ```APIDOC ## Uri Examples ### Parsing from String ```rust use http::Uri; let uri = "/foo/bar?baz".parse::().unwrap(); assert_eq!(uri.path(), "/foo/bar"); assert_eq!(uri.query(), Some("baz")); assert_eq!(uri.host(), None); let uri = "https://www.rust-lang.org/install.html".parse::().unwrap(); assert_eq!(uri.scheme_str(), Some("https")); assert_eq!(uri.host(), Some("www.rust-lang.org")); assert_eq!(uri.path(), "/install.html"); ``` ``` -------------------------------- ### Start Docker Exec Instance Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Exec.html Starts the exec instance, returning a multiplexed TTY stream. This operation is typically used to stream output from the executed command. ```rust pub fn start(&self) -> impl Stream> + 'docker ``` -------------------------------- ### Parse URI strings Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Uri.html Examples demonstrating how to parse different URI formats and access their query components. ```rust let uri: Uri = "http://example.org/hello/world?key=value".parse().unwrap(); assert_eq!(uri.query(), Some("key=value")); ``` ```rust let uri: Uri = "/hello/world?key=value&foo=bar".parse().unwrap(); assert_eq!(uri.query(), Some("key=value&foo=bar")); ``` ```rust let uri: Uri = "/hello/world".parse().unwrap(); assert!(uri.query().is_none()); ``` -------------------------------- ### Manage Docker Containers Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Provides methods to list, get, and create container instances. ```rust pub async fn list( &self, opts: &ContainerListOptions, ) -> Result> { let mut path = vec!["/containers/json".to_owned()]; if let Some(query) = opts.serialize() { path.push(query) } self.docker .get_json::>(&path.join("?")) .await } ``` ```rust pub fn get( &self, name: S, ) -> Container<'docker> where S: Into, { Container::new(self.docker, name) } ``` ```rust pub async fn create( &self, opts: &ContainerOptions, ) -> Result { let body: Body = opts.serialize()?.into(); let mut path = vec!["/containers/create".to_owned()]; if let Some(ref name) = opts.name { path.push( form_urlencoded::Serializer::new(String::new()) .append_pair("name", name) .finish(), ); } self.docker .post_json(&path.join("?"), Some((body, mime::APPLICATION_JSON))) .await } ``` -------------------------------- ### Manage Container Lifecycle Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Methods to start, stop, or restart the container instance. ```rust pub async fn start(&self) -> Result<()> { self.docker .post(&format!("/containers/{}/start", self.id)[..], None) .await?; Ok(()) } ``` ```rust pub async fn stop( &self, wait: Option, ) -> Result<()> { let mut path = vec![format!("/containers/{}/stop", self.id)]; if let Some(w) = wait { let encoded = form_urlencoded::Serializer::new(String::new()) .append_pair("t", &w.as_secs().to_string()) .finish(); path.push(encoded) } self.docker.post(&path.join("?"), None).await?; Ok(()) } ``` ```rust pub async fn restart( &self, wait: Option, ) -> Result<()> { let mut path = vec![format!("/containers/{}/restart", self.id)]; if let Some(w) = wait { let encoded = form_urlencoded::Serializer::new(String::new()) .append_pair("t", &w.as_secs().to_string()) .finish(); path.push(encoded) } self.docker.post(&path.join("?"), None).await?; Ok(()) } ``` -------------------------------- ### Set Container Entrypoint Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Specifies the entrypoint for the container. This is the executable that will be run when the container starts. ```rust pub fn entrypoint( &mut self, entrypoint: &str, ) -> &mut Self { self.params.insert("Entrypoint", json!(entrypoint)); self } ``` -------------------------------- ### GET /images Source: https://docs.rs/shiplift/0.7.0/index.html Lists the Docker images available on the daemon. ```APIDOC ## GET /images ### Description Retrieves a list of images currently managed by the Docker daemon. ### Method GET ### Endpoint /images ### Parameters #### Query Parameters - **options** (ImageListOptions) - Optional - Configuration options for filtering or listing images. ### Request Example let docker = shiplift::Docker::new(); docker.images().list(&Default::default()).await; ### Response #### Success Response (200) - **images** (Vec) - A list of image objects containing metadata such as repo_tags. ``` -------------------------------- ### GET /services Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Services.html Lists the Docker services available on the current Docker host. ```APIDOC ## GET /services ### Description Lists the Docker services on the current Docker host. ### Method GET ### Endpoint /services ### Parameters #### Query Parameters - **opts** (ServiceListOptions) - Required - Options for filtering or configuring the service list request. ### Response #### Success Response (200) - **ServicesRep** (Object) - A collection of Docker services. ``` -------------------------------- ### Rust binary_search example Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Illustrates `binary_search` on a sorted slice. It shows successful finds, cases where the element is not found, and handling multiple matches. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Execute Command in Container Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Starts a command execution within the container and returns a stream of output. ```rust pub fn exec( &self, opts: &ExecContainerOptions, ) -> impl Stream> + Unpin + 'docker { Exec::create_and_start(self.docker, &self.id, opts) } ``` -------------------------------- ### List Docker Images Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Demonstrates how to initialize the Docker client and list available images. ```rust # async { let docker = shiplift::Docker::new(); match docker.images().list(&Default::default()).await { Ok(images) => { for image in images { println!("{:?}", image.repo_tags); } }, Err(e) => eprintln!("Something bad happened! {}", e), } # }; ``` -------------------------------- ### Get URI Query String Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Uri.html Extract the query string from a URI. The query string starts after the '?' and is terminated by a '#' or the end of the URI. ```Rust abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1 |-------------------| | query ``` -------------------------------- ### Get tar Mime Type Source: https://docs.rs/shiplift/0.7.0/shiplift/transport/fn.tar.html Use this function to retrieve the Mime type for tar archives. No setup or imports are required beyond the shiplift crate. ```rust pub fn tar() -> Mime ``` -------------------------------- ### Iterate over exact slice chunks from the end (rchunks_exact) Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `rchunks_exact` to get an iterator over slices of exactly `chunk_size`, starting from the end. Elements not fitting into a full chunk are available via `remainder()`. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['l']); ``` -------------------------------- ### Iterate over slice chunks from the end (rchunks) Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `rchunks` to get an iterator over mutable slices of a specified size, starting from the end. The last chunk may be smaller if the slice length is not divisible by `chunk_size`. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### Get Element Offset in Slice Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Shows how to find the index of an element reference within a slice using `element_offset`. This method uses pointer arithmetic and does not compare elements. It returns `None` if the element reference does not point to the start of an element. ```rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### Mutably iterate over slice chunks from the end (rchunks_mut) Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `rchunks_mut` to get an iterator over mutable slices of a specified size, starting from the end. This allows in-place modification of slice elements within chunks. The last chunk may be smaller. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[3, 2, 2, 1, 1]); ``` -------------------------------- ### Mutably iterate over exact slice chunks from the end (rchunks_exact_mut) Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `rchunks_exact_mut` to get an iterator over mutable slices of exactly `chunk_size`, starting from the end. Elements not fitting into a full chunk are available via `into_remainder()`. This allows for optimized in-place modifications. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_exact_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[0, 2, 2, 1, 1]); ``` -------------------------------- ### Docker Initialization Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Docker.html Methods for creating new Docker instances to interact with the Docker daemon. ```APIDOC ## Docker Initialization ### Description Methods for creating new Docker instances to interact with the Docker daemon. ### `Docker::new()` #### Description Constructs a new `Docker` instance for a Docker host listening at a URL specified by the `DOCKER_HOST` environment variable, falling back on `unix:///var/run/docker.sock`. ### `Docker::unix(socket_path)` #### Description Creates a new `Docker` instance for a Docker host listening on a given Unix socket. ### `Docker::host(host)` #### Description Constructs a new `Docker` instance for a Docker host listening at the given host URL. ``` -------------------------------- ### Stream GET Request Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Initiates a streaming GET request to a specified endpoint, returning a stream of byte chunks. ```rust fn stream_get<'a>( &'a self, endpoint: impl AsRef + Unpin + 'a, ) -> impl Stream> + 'a { let headers = Some(Vec::default()); self.transport .stream_chunks(Method::GET, endpoint, Option::<(Body, Mime)>::None, headers) } ``` -------------------------------- ### Configure Nested Container Options Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Demonstrates setting nested configuration options like log drivers. ```rust /// Test container options that are nested 3 levels deep. #[test] fn container_options_nested() { let options = ContainerOptionsBuilder::new("test_image") .log_driver("fluentd") .build(); assert_eq!( r#"{"HostConfig":{"LogConfig":{"Type":"fluentd"}},"Image":"test_image"}"#, options.serialize().unwrap() ); } ``` -------------------------------- ### Stream GET Request Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Fetches data from a specified endpoint using a streaming GET request, returning a stream of byte chunks. ```APIDOC ## GET /api/stream ### Description Retrieves data from the specified endpoint using a streaming GET request. This is suitable for large responses where processing data in chunks is necessary. The response is a stream of byte chunks. ### Method GET ### Endpoint `/api/stream` ### Parameters #### Path Parameters - **endpoint** (string) - Required - The API endpoint to fetch data from. ### Response #### Success Response (200) - **Stream>** - A stream yielding byte chunks (`Bytes`) or errors (`Result`). ### Response Example ``` // Each item in the stream is a chunk of bytes ``` ``` -------------------------------- ### Configure Container Volumes From Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Sets the volumes to mount from other containers. ```rust pub fn volumes_from( &mut self, volumes: Vec<&str>, ) -> &mut Self { self.params.insert("HostConfig.VolumesFrom", json!(volumes)); self } ``` -------------------------------- ### Create Build Options Builder Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Initializes a new BuildOptionsBuilder with the specified Dockerfile path. The path is expected to be a directory containing a Dockerfile. ```rust pub fn builder(path: S) -> BuildOptionsBuilder where S: Into, { BuildOptionsBuilder::new(path) } ``` -------------------------------- ### Configure Registry Authentication Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Demonstrates various methods for registry authentication, including tokens and username/password combinations. ```rust /// Test registry auth with token #[test] fn registry_auth_token() { let options = RegistryAuth::token("abc"); assert_eq!( base64::encode(r#"{"identitytoken":"abc"}"#), options.serialize() ); } ``` ```rust /// Test registry auth with username and password #[test] fn registry_auth_password_simple() { let options = RegistryAuth::builder() .username("user_abc") .password("password_abc") .build(); assert_eq!( base64::encode(r#"{"username":"user_abc","password":"password_abc"}"#), options.serialize() ); } ``` ```rust /// Test registry auth with all fields #[test] fn registry_auth_password_all() { let options = RegistryAuth::builder() .username("user_abc") .password("password_abc") .email("email_abc") .server_address("https://example.org") .build(); assert_eq!( base64::encode( r#"{"username":"user_abc","password":"password_abc","email":"email_abc","serveraddress":"https://example.org"}"# ), options.serialize() ); } ``` -------------------------------- ### Implement Default for ServiceOptions Source: https://docs.rs/shiplift/0.7.0/shiplift/builder/struct.ServiceOptions.html Returns the default value for ServiceOptions. This provides a sensible starting point for the options. ```rust fn default() -> ServiceOptions ``` -------------------------------- ### Remove and Get Last Element of Slice Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `split_off_last` to remove the last element from an immutable slice and get a reference to it. Returns `None` if the slice is empty. ```rust let mut slice: &[_] = &['a', 'b', 'c']; let last = slice.split_off_last().unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(last, &'c'); ``` -------------------------------- ### Build and Serialize Logs Options (with chrono) Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Demonstrates building log options with a `chrono` timestamp and serializing them. Asserts that the serialized output contains the expected key-value pairs. ```rust let mut since = std::time::SystemTime::now(); since.sub_assign(std::time::Duration::from_secs(60)); let options = LogsOptionsBuilder::default() .follow(true) .stdout(true) .stderr(true) .timestamps(true) .tail("all") .since(&since) .build(); let serialized = options.serialize().unwrap(); assert!(serialized.contains("follow=true")); assert!(serialized.contains("stdout=true")); assert!(serialized.contains("stderr=true")); assert!(serialized.contains("timestamps=true")); assert!(serialized.contains("tail=all")); assert!(serialized.contains("since=2147483647")); ``` -------------------------------- ### Slice Starts With Method Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Determines if a slice begins with a specified prefix (needle). An empty needle always returns true. ```APIDOC ## GET /slice/starts_with ### Description Returns `true` if the slice starts with the given `needle` slice. ### Method GET ### Endpoint `/slice/starts_with` ### Parameters #### Query Parameters - **needle** (array) - Required - The slice to check as a prefix. ### Request Example ```json { "slice": [10, 40, 30], "needle": [10, 40] } ``` ### Response #### Success Response (200) - **result** (boolean) - `true` if the slice starts with the needle, `false` otherwise. #### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Remove and Get First Element of Slice Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `split_off_first` to remove the first element from an immutable slice and get a reference to it. Returns `None` if the slice is empty. ```rust let mut slice: &[_] = &['a', 'b', 'c']; let first = slice.split_off_first().unwrap(); assert_eq!(slice, &['b', 'c']); assert_eq!(first, &'a'); ``` -------------------------------- ### Configure Container Port Publishing Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Demonstrates how to publish container ports using ContainerOptionsBuilder. ```rust #[test] fn container_options_publish() { let options = ContainerOptionsBuilder::new("test_image") .publish(80, "tcp") .build(); assert_eq!( r#"{"ExposedPorts":{"80/tcp":{}},"HostConfig":{},"Image":"test_image"}"#, options.serialize().unwrap() ); // try exposing two let options = ContainerOptionsBuilder::new("test_image") .publish(80, "tcp") .publish(81, "tcp") .build(); assert_eq!( r#"{"ExposedPorts":{"80/tcp":{},"81/tcp":{}},"HostConfig":{},"Image":"test_image"}"#, options.serialize().unwrap() ); } ``` -------------------------------- ### Perform GET Request Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html A private utility function to perform an HTTP GET request to a specified endpoint on the Docker daemon. It handles the transport layer details. ```rust // // Utility functions to make requests // async fn get( &self, endpoint: &str, ) -> Result { self.transport .request(Method::GET, endpoint, Payload::None, Headers::None) .await } // ... other methods ``` -------------------------------- ### List Docker Images with Shiplift Source: https://docs.rs/shiplift/0.7.0/index.html Initializes a Docker client and lists available images, printing their repository tags to the console. ```rust let docker = shiplift::Docker::new(); match docker.images().list(&Default::default()).await { Ok(images) => { for image in images { println!("{:?}", image.repo_tags); } }, Err(e) => eprintln!("Something bad happened! {}", e), } ``` -------------------------------- ### Get Mutable Element or Subslice by Index Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `get_mut` to obtain a mutable reference to an element or subslice. Returns `None` if the index is out of bounds. This is the mutable counterpart to `get`. ```rust let x = &mut [0, 1, 2]; if let Some(elem) = x.get_mut(1) { *elem = 42; } assert_eq!(x, &[0, 42, 2]); ``` -------------------------------- ### Get Element or Subslice by Index Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html The `get` method safely retrieves a reference to an element or subslice using various index types. It returns `None` if the index is out of bounds. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Configure Service Options Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Builder for service options including registry authentication and parameter serialization. ```rust pub struct ServiceOptions { auth: Option, params: HashMap<&'static str, Value>, } impl ServiceOptions { pub fn builder() -> ServiceOptionsBuilder { ServiceOptionsBuilder::default() } pub fn serialize(&self) -> Result { serde_json::to_string(&self.params).map_err(Error::from) } pub(crate) fn auth_header(&self) -> Option { self.auth.clone().map(|a| a.serialize()) } } #[derive(Default)] pub struct ServiceOptionsBuilder { auth: Option, params: HashMap<&'static str, Result>, } impl ServiceOptionsBuilder { pub fn name( &mut self, name: S, ) -> &mut Self where S: AsRef, { ``` -------------------------------- ### Build Options Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Configuration parameters for building Docker images. ```APIDOC ## Build Options ### Description Configuration parameters used when building a Docker image. ### Parameters #### Request Body - **rm** (bool) - Optional - Remove intermediate containers after a successful build. - **forcerm** (bool) - Optional - Always remove intermediate containers. - **networkmode** (string) - Optional - Network mode to use for the build (e.g., bridge, host, none). - **memory** (u64) - Optional - Memory limit for the build process. - **cpushares** (u32) - Optional - CPU shares (relative weight). ``` -------------------------------- ### Remove and Get Last Mutable Element of Slice Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `split_off_last_mut` to remove the last element from a mutable slice and get a mutable reference to it. Returns `None` if the slice is empty. ```rust let mut slice: &mut [_] = &mut ['a', 'b', 'c']; let last = slice.split_off_last_mut().unwrap(); *last = 'd'; assert_eq!(slice, &['a', 'b']); assert_eq!(last, &'d'); ``` -------------------------------- ### Remove and Get First Mutable Element of Slice Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `split_off_first_mut` to remove the first element from a mutable slice and get a mutable reference to it. Returns `None` if the slice is empty. ```rust let mut slice: &mut [_] = &mut ['a', 'b', 'c']; let first = slice.split_off_first_mut().unwrap(); *first = 'd'; assert_eq!(slice, &['b', 'c']); assert_eq!(first, &'d'); ``` -------------------------------- ### PullOptions Builder and Serialization Source: https://docs.rs/shiplift/0.7.0/shiplift/builder/struct.PullOptions.html Methods for initializing a PullOptions builder and serializing the configuration into a string format. ```APIDOC ## PullOptions ### Description Represents configuration options for pulling images. Provides a builder interface and serialization methods. ### Methods - **builder()** -> PullOptionsBuilder: Returns a new instance of a builder for options. - **serialize(&self)** -> Option: Serializes options as a string. Returns None if no options are defined. ``` -------------------------------- ### Initialize Images Interface Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Images.html Creates a new Images interface instance. Requires a reference to the Docker client. ```rust pub fn new(docker: &'docker Docker) -> Self ``` -------------------------------- ### Get Mutable Reference to Last Chunk of Slice Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `last_chunk_mut` to get a mutable reference to the last N elements of a slice. Returns `None` if the slice is shorter than N. ```rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_chunk_mut::<2>() { last[0] = 10; last[1] = 20; } assert_eq!(x, &[0, 10, 20]); assert_eq!(None, x.last_chunk_mut::<4>()); ``` -------------------------------- ### Build Image Source: https://docs.rs/shiplift/0.7.0/shiplift/builder/struct.BuildOptionsBuilder.html Constructs and returns the BuildOptions based on the configured builder. ```rust pub fn build(&self) -> BuildOptions ``` -------------------------------- ### GET /uri/query Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Uri.html Retrieves the query string of the URI. ```APIDOC ## GET /uri/query ### Description Returns the query string of the URI, excluding the leading '?' character. ### Method GET ### Response #### Success Response (200) - **query** (Option<&str>) - The query string if present. ``` -------------------------------- ### Create Service Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Service.html Creates a new service using the provided ServiceOptions. ```rust pub async fn create(&self, opts: &ServiceOptions) -> Result ``` -------------------------------- ### GET /uri/port Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Uri.html Retrieves the port component of the URI. ```APIDOC ## GET /uri/port ### Description Returns the port subcomponent of the authority. Can be accessed as a Port object or directly as a u16. ### Method GET ### Response #### Success Response (200) - **port** (Option) - The port number if present. ``` -------------------------------- ### Build Docker Container Options Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Use this builder to construct `ContainerOptions` for creating Docker containers. It allows setting various parameters. ```rust pub fn build(&self) -> BuildOptions { BuildOptions { path: self.path.clone(), params: self.params.clone(), } } ``` -------------------------------- ### Initialize Container Options Builder Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Creates a new instance of the ContainerOptionsBuilder with the specified image name. ```rust let mut builder = ContainerOptionsBuilder::new("my_image:latest"); ``` -------------------------------- ### GET /uri/host Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Uri.html Retrieves the host component of the URI. ```APIDOC ## GET /uri/host ### Description Returns the host subcomponent of the authority as a string slice. The host is case-insensitive. ### Method GET ### Response #### Success Response (200) - **host** (Option<&str>) - The host component if present. ``` -------------------------------- ### GET /uri/authority Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Uri.html Retrieves the authority component of the URI. ```APIDOC ## GET /uri/authority ### Description Returns the authority component of the URI, which includes the host and port. Note that the username:password component is deprecated. ### Method GET ### Response #### Success Response (200) - **authority** (Option<&Authority>) - The authority component if present. ``` -------------------------------- ### Initialize Networks Interface Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Networks.html Exports an interface for interacting with Docker Networks. Requires a reference to the Docker client. ```rust pub fn new(docker: &'docker Docker) -> Self> ``` -------------------------------- ### GET /uri/scheme Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Uri.html Retrieves the scheme component of the URI. ```APIDOC ## GET /uri/scheme ### Description Returns the scheme of the URI as an Option<&Scheme>. The scheme is returned in its canonical lowercase form. ### Method GET ### Response #### Success Response (200) - **scheme** (Option<&Scheme>) - The scheme component if present. ``` -------------------------------- ### TagOptions Builder and Serialization Source: https://docs.rs/shiplift/0.7.0/shiplift/builder/struct.TagOptions.html Information on how to build TagOptions instances and serialize them. ```APIDOC ## Implementations for TagOptions ### `pub fn builder() -> TagOptionsBuilder` Returns a new instance of a builder for options. ### `pub fn serialize(&self) -> Option` Serializes options as a string. Returns `None` if no options are defined. ``` -------------------------------- ### Get Raw Pointer to Vec Buffer Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Use `as_ptr` to get a raw pointer to the vector's buffer. The caller must ensure the vector outlives the pointer and that the memory is not mutated through this pointer. This method guarantees it does not materialize a reference for aliasing purposes. ```rust let x = vec![1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(*x_ptr.add(i), 1 << i); } } ``` ```rust unsafe { let mut v = vec![0, 1, 2]; let ptr1 = v.as_ptr(); let _ = ptr1.read(); let ptr2 = v.as_mut_ptr().offset(2); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1` // because it mutated a different element: let _ = ptr1.read(); } ``` -------------------------------- ### Create Docker Network Options Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html NetworkCreateOptions and its builder allow defining network configurations like driver and labels, serialized as JSON. ```rust pub struct NetworkCreateOptions { params: HashMap<&'static str, Value>, } impl NetworkCreateOptions { pub fn builder(name: &str) -> NetworkCreateOptionsBuilder { NetworkCreateOptionsBuilder::new(name) } pub fn serialize(&self) -> Result { serde_json::to_string(&self.params).map_err(Error::from) } pub fn parse_from<'a, K, V>( &self, params: &'a HashMap, body: &mut serde_json::Map, ) where &'a HashMap: IntoIterator, K: ToString + Eq + Hash, V: Serialize, { for (k, v) in params.iter() { let key = k.to_string(); let value = serde_json::to_value(v).unwrap(); body.insert(key, value); } } } ``` ```rust pub struct NetworkCreateOptionsBuilder { params: HashMap<&'static str, Value>, } impl NetworkCreateOptionsBuilder { pub(crate) fn new(name: &str) -> Self { let mut params = HashMap::new(); params.insert("Name", json!(name)); NetworkCreateOptionsBuilder { params } } pub fn driver( &mut self, name: &str, ) -> &mut Self { if !name.is_empty() { self.params.insert("Driver", json!(name)); } self } pub fn label( &mut self, labels: HashMap, ) -> &mut Self { self.params.insert("Labels", json!(labels)); self } ``` -------------------------------- ### rchunks Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Returns an iterator over chunk_size elements starting at the end. ```APIDOC ## rchunks ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. ### Parameters - **chunk_size** (usize) - Required - The size of the chunks to split the slice into. ### Panics Panics if `chunk_size` is zero. ``` -------------------------------- ### GET /images/get Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Exports a collection of named images into a tarball. ```APIDOC ## GET /images/get ### Description Exports a collection of named images, either by name, name:tag, or image id, into a tarball. ### Method GET ### Endpoint /images/get ### Parameters #### Query Parameters - **names** (array) - Required - List of image names or IDs to export. ``` -------------------------------- ### Network::new Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Network.html Creates a new Network interface instance. ```APIDOC ## Network::new ### Description Exports an interface exposing operations against a network instance. ### Method `pub fn new(docker: &'docker Docker, id: S) -> Self` ### Parameters * `docker` (&'docker Docker) - The Docker client instance. * `id` (S: Into) - The ID of the network to manage. ``` -------------------------------- ### POST /build Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Builds a new Docker image from a directory path. ```APIDOC ## POST /build ### Description Builds a new Docker image from a specified directory path. ### Method POST ### Endpoint /build ``` -------------------------------- ### as_rchunks_mut Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Splits the slice into a slice of N-element arrays starting from the end. ```APIDOC ## as_rchunks_mut ### Description Splits the slice into a slice of `N`-element arrays, starting at the end of the slice, and a remainder slice with length strictly less than `N`. ### Panics Panics if `N` is zero. ``` -------------------------------- ### Create Container Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Containers.html Creates a new container instance using the provided options. ```APIDOC ## POST /containers ### Description Returns a builder interface for creating a new container instance. ### Method POST ### Parameters #### Request Body - **opts** (ContainerOptions) - Required - Configuration options for the new container. ### Response #### Success Response (200) - **info** (ContainerCreateInfo) - Information regarding the created container. ``` -------------------------------- ### Build and Serialize Logs Options (without chrono) Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Demonstrates building log options with a Unix timestamp and serializing them. Asserts that the serialized output contains the expected key-value pairs. This version is used when the `chrono` feature is not enabled. ```rust let options = LogsOptionsBuilder::default() .follow(true) .stdout(true) .stderr(true) .timestamps(true) .tail("all") .since(2_147_483_647) .build(); let serialized = options.serialize().unwrap(); assert!(serialized.contains("follow=true")); assert!(serialized.contains("stdout=true")); assert!(serialized.contains("stderr=true")); assert!(serialized.contains("timestamps=true")); assert!(serialized.contains("tail=all")); assert!(serialized.contains("since=2147483647")); ``` -------------------------------- ### get Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Returns a reference to an element or subslice based on the provided index. ```APIDOC ## get(&self, index: I) ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element; if given a range, returns the subslice. ### Parameters #### Request Body - **index** (I: SliceIndex<[T]>) - Required - The index or range to access. ### Response - **Option<&>::Output>** - The element or subslice, or None if out of bounds. ``` -------------------------------- ### GET /containers/{id}/logs Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Retrieves a stream of logs from a container. ```APIDOC ## GET /containers/{id}/logs ### Description Returns a stream of logs emitted by the container instance. ### Method GET ### Endpoint /containers/{id}/logs ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the container. #### Query Parameters - **LogsOptions** (object) - Options for retrieving logs (e.g., timestamps, tail, follow). - **stdout** (boolean) - Optional - Include stdout logs. - **stderr** (boolean) - Optional - Include stderr logs. - **since** (integer) - Optional - Return logs since a specific timestamp. - **until** (integer) - Optional - Return logs until a specific timestamp. - **tail** (string) - Optional - Number of lines to show from the end of the logs. - **follow** (boolean) - Optional - Follow log stream. - **timestamps** (boolean) - Optional - Include timestamps. ### Response #### Success Response (200) - **tty.TtyChunk** (stream) - A stream of log chunks. #### Response Example ``` This is a log line from stdout. This is another log line from stderr. ``` ``` -------------------------------- ### Initialize Container Interface Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Creates a new container instance interface. ```rust /// Exports an interface exposing operations against a container instance pub fn new( docker: &'docker Docker, id: S, ) -> Self where S: Into, { Container { docker, id: id.into(), } ``` -------------------------------- ### GET /images/search Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Searches for Docker images by a specific search term. ```APIDOC ## GET /images/search ### Description Search for docker images by term. ### Method GET ### Endpoint /images/search ### Parameters #### Query Parameters - **term** (string) - Required - The search term to filter images. ``` -------------------------------- ### Configure Container Port Exposure Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Demonstrates how to expose container ports and map them to host ports using ContainerOptionsBuilder. ```rust #[test] fn container_options_expose() { let options = ContainerOptionsBuilder::new("test_image") .expose(80, "tcp", 8080) .build(); assert_eq!( r#"{"ExposedPorts":{"80/tcp":{}},"HostConfig":{"PortBindings":{"80/tcp":[{"HostPort":"8080"}]}},"Image":"test_image"}"#, options.serialize().unwrap() ); // try exposing two let options = ContainerOptionsBuilder::new("test_image") .expose(80, "tcp", 8080) .expose(81, "tcp", 8081) .build(); assert_eq!( r#"{"ExposedPorts":{"80/tcp":{},"81/tcp":{}},"HostConfig":{"PortBindings":{"80/tcp":[{"HostPort":"8080"}],"81/tcp":[{"HostPort":"8081"}]}},"Image":"test_image"}"#, options.serialize().unwrap() ); } ``` -------------------------------- ### Exec::get Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Exec.html Gets a reference to operations for an existing exec instance. ```APIDOC ## GET /exec/{id} ### Description Get a reference to a set of operations available to an already created exec instance. It’s in the caller’s responsibility to ensure that the exec instance with the specified ID actually exists. Use `Exec::create` to ensure the exec instance is created beforehand. ### Method GET ### Endpoint /exec/{id} ### Parameters #### Path Parameters - **id** (S) - Required - The ID of the exec instance. #### Query Parameters - **docker** (Docker) - Required - A reference to the Docker client. ### Response #### Success Response (200) - **Exec** (Exec) - A reference to the exec instance. ``` -------------------------------- ### Create a Docker Service Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Creates a new Docker service using provided options. Requires serialization of options and setting authentication headers. ```rust pub async fn create( &self, opts: &ServiceOptions, ) -> Result { let body: Body = opts.serialize()?.into(); let path = vec!["/service/create".to_owned()]; let headers = opts .auth_header() .map(|a| iter::once(("X-Registry-Auth", a))); self.docker .post_json_headers( &path.join("?"), Some((body, mime::APPLICATION_JSON)), headers, ) .await } ``` -------------------------------- ### CPU Configuration Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Methods for configuring CPU limits and weights for containers. ```APIDOC ## POST /websites/rs_shiplift_0_7_0 ### Description Configures CPU allocation for a container. ### Method POST ### Endpoint /websites/rs_shiplift_0_7_0 ### Parameters #### Request Body - **nano_cpus** (u64) - Optional - CPU quota in units of 10^-9 CPUs. Set to 0 for no limit. - **cpus** (f64) - Optional - CPU quota in units of CPUs. This is a wrapper around `nano_cpus`. - **cpu_shares** (u32) - Optional - CPU weight relative to other containers. ### Request Example ```json { "nano_cpus": 500000000, "cpu_shares": 1024 } ``` ### Response #### Success Response (200) - **params** (object) - The updated container parameters including CPU settings. #### Response Example ```json { "params": { "HostConfig.NanoCpus": 500000000, "HostConfig.CpuShares": 1024 } } ``` ``` -------------------------------- ### GET Request Source: https://docs.rs/shiplift/0.7.0/src/shiplift/lib.rs.html Fetches data from a specified endpoint and deserializes it into a given type. ```APIDOC ## GET /api/resource ### Description Retrieves a resource from the specified endpoint. The response is deserialized into the specified generic type `T`. ### Method GET ### Endpoint `/api/resource` ### Parameters #### Query Parameters - **endpoint** (string) - Required - The API endpoint to fetch data from. ### Response #### Success Response (200) - **T** (object) - The deserialized response data of type `T`. ### Response Example ```json { "example_field": "example_value" } ``` ``` -------------------------------- ### Build Docker Image Source: https://docs.rs/shiplift/0.7.0/shiplift/struct.Images.html Builds a new Docker image by reading a Dockerfile from a specified directory. Returns a stream of build output values. ```rust pub fn build( &self, opts: &BuildOptions, ) -> impl Stream> + Unpin + 'docker ``` -------------------------------- ### Try Reserve Exact Capacity Example Source: https://docs.rs/shiplift/0.7.0/shiplift/tty/enum.TtyChunk.html Demonstrates using `try_reserve_exact` to attempt reserving the minimum required capacity for a vector. This method also returns a `Result` for error handling. ```rust let mut vec = vec![1]; vec.try_reserve_exact(10); assert!(vec.capacity() >= 11); ``` -------------------------------- ### Get Authentication Header Source: https://docs.rs/shiplift/0.7.0/src/shiplift/builder.rs.html Retrieves the authentication header string if authentication is configured. ```rust pub(crate) fn auth_header(&self) -> Option { self.auth.clone().map(|a| a.serialize()) } ```