Struct cached_path::Cache

source ·
pub struct Cache {
    pub dir: PathBuf,
    /* private fields */
}
Expand description

Fetches and manages resources in a local cache directory.

Fields§

§dir: PathBuf

The root directory of the cache.

Implementations§

Create a new Cache instance.

Create a CacheBuilder.

Examples found in repository?
src/cache.rs (line 208)
207
208
209
    pub fn new() -> Result<Self, Error> {
        Cache::builder().build()
    }
More examples
Hide additional examples
src/lib.rs (line 113)
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
pub fn cached_path(resource: &str) -> Result<PathBuf, Error> {
    let cache = Cache::builder().build()?;
    cache.cached_path(resource)
}

/// Get the cached path to a resource using the given options.
///
/// This is equivalent to calling
/// [`Cache::cached_path_with_options`](crate::cache::Cache#method.cached_path_with_options)
/// with a temporary [`Cache`](crate::cache::Cache) object.
/// Therefore if you're going to be calling this function multiple times,
/// it's more efficient to create and use a single `Cache` instead.
pub fn cached_path_with_options(resource: &str, options: &Options) -> Result<PathBuf, Error> {
    let cache = Cache::builder().build()?;
    cache.cached_path_with_options(resource, options)
}

Get the cached path to a resource.

If the resource is local file, it’s path is returned. If the resource is a static HTTP resource, it will cached locally and the path to the cache file will be returned.

Examples found in repository?
src/lib.rs (line 114)
112
113
114
115
pub fn cached_path(resource: &str) -> Result<PathBuf, Error> {
    let cache = Cache::builder().build()?;
    cache.cached_path(resource)
}

Get the cached path to a resource using the given options.

Examples

Use a particular subdirectory of the cache root:

let path = cache.cached_path_with_options(
    resource,
    &Options::default().subdir(subdir),
).unwrap();

Treat the resource as an archive and extract it. The path returned is the path to the extraction directory:

let path = cache.cached_path_with_options(
    resource,
    &Options::default().extract(),
).unwrap();
assert!(path.is_dir());
Examples found in repository?
src/cache.rs (line 221)
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
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
    pub fn cached_path(&self, resource: &str) -> Result<PathBuf, Error> {
        self.cached_path_with_options(resource, &Options::default())
    }

    /// Get the cached path to a resource using the given options.
    ///
    /// # Examples
    ///
    /// Use a particular subdirectory of the cache root:
    ///
    /// ```rust,no_run
    /// # use cached_path::{Cache, Options};
    /// # let cache = Cache::new().unwrap();
    /// # let subdir = "target";
    /// # let resource = "README.md";
    /// let path = cache.cached_path_with_options(
    ///     resource,
    ///     &Options::default().subdir(subdir),
    /// ).unwrap();
    /// ```
    ///
    /// Treat the resource as an archive and extract it. The path returned is the
    /// path to the extraction directory:
    ///
    /// ```rust,no_run
    /// # use cached_path::{Cache, Options};
    /// # let cache = Cache::new().unwrap();
    /// # let subdir = "target";
    /// # let resource = "README.md";
    /// let path = cache.cached_path_with_options(
    ///     resource,
    ///     &Options::default().extract(),
    /// ).unwrap();
    /// assert!(path.is_dir());
    /// ```
    pub fn cached_path_with_options(
        &self,
        resource: &str,
        options: &Options,
    ) -> Result<PathBuf, Error> {
        let cached_path: PathBuf;
        let mut extraction_dir: Option<PathBuf> = None;

        if !resource.starts_with("http") {
            // If resource doesn't look like a URL, treat as local path, but return
            // an error if the path doesn't exist.
            info!("Treating {} as local file", resource);
            cached_path = PathBuf::from(resource);

            if !cached_path.is_file() {
                return Err(Error::ResourceNotFound(String::from(resource)));
            }

            if options.extract {
                // If we need to extract, we extract into a unique subdirectory of the cache directory
                // so as not to mess with the file system outside of the cache directory.
                // To make sure that we use a unique directory for each "version" of this local
                // resource, we treat the last modified time as an ETag.
                let resource_last_modified = fs::metadata(resource)?
                    .modified()
                    .ok()
                    .and_then(|sys_time| sys_time.elapsed().ok())
                    .map(|duration| format!("{}", duration.as_secs()));
                extraction_dir = Some(self.resource_to_filepath(
                    resource,
                    &resource_last_modified,
                    options.subdir.as_deref(),
                    Some("-extracted"),
                ));
            }
        } else {
            // This is a remote resource, so fetch it to the cache.
            let meta = self.fetch_remote_resource(resource, options.subdir.as_deref())?;

            // Check if we need to extract.
            if options.extract {
                extraction_dir = Some(meta.get_extraction_path());
            }

            cached_path = meta.resource_path;
        }

        if let Some(dirpath) = extraction_dir {
            // Extract archive.
            debug!("Treating {} as archive", resource);

            fs::create_dir_all(dirpath.parent().unwrap())?;

            // Need to acquire a lock here to make sure we don't try to extract
            // the same archive in parallel from multiple processes.
            debug!("Acquiring lock on extraction directory for {}", resource);
            let lock_path = format!("{}.lock", dirpath.to_str().unwrap());
            let filelock = OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .open(lock_path)?;
            filelock.lock_exclusive()?;
            debug!("Lock on extraction directory acquired for {}", resource);

            if !dirpath.is_dir() {
                info!("Extracting {} to {:?}", resource, dirpath);
                let format = ArchiveFormat::parse_from_extension(resource)?;
                extract_archive(&cached_path, &dirpath, &format)?;
            }

            filelock.unlock()?;
            debug!("Lock released on extraction directory for {}", resource);

            Ok(dirpath)
        } else {
            Ok(cached_path)
        }
    }

    /// A convenience method to get the cached path to a resource using the given
    /// cache subdirectory (relative to the cache root).
    ///
    /// This is equivalent to:
    ///
    /// ```rust,no_run
    /// # use cached_path::{Cache, Options};
    /// # let cache = Cache::new().unwrap();
    /// # let subdir = "target";
    /// # let resource = "README.md";
    /// let path = cache.cached_path_with_options(
    ///     resource,
    ///     &Options::default().subdir(subdir),
    /// ).unwrap();
    /// ```
    #[deprecated(
        since = "0.4.4",
        note = "Please use Cache::cached_path_with_options() instead"
    )]
    pub fn cached_path_in_subdir(
        &self,
        resource: &str,
        subdir: Option<&str>,
    ) -> Result<PathBuf, Error> {
        let options = Options::new(subdir, false);
        self.cached_path_with_options(resource, &options)
    }
More examples
Hide additional examples
src/lib.rs (line 126)
124
125
126
127
pub fn cached_path_with_options(resource: &str, options: &Options) -> Result<PathBuf, Error> {
    let cache = Cache::builder().build()?;
    cache.cached_path_with_options(resource, options)
}
👎Deprecated since 0.4.4: Please use Cache::cached_path_with_options() instead

A convenience method to get the cached path to a resource using the given cache subdirectory (relative to the cache root).

This is equivalent to:

let path = cache.cached_path_with_options(
    resource,
    &Options::default().subdir(subdir),
).unwrap();

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more