]> git.lizzy.rs Git - rust.git/blob - src/librustc_incremental/persist/util.rs
Rollup merge of #33250 - durka:patch-19, r=steveklabnik
[rust.git] / src / librustc_incremental / persist / util.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc::middle::cstore::LOCAL_CRATE;
12 use rustc::ty::TyCtxt;
13
14 use std::fs;
15 use std::io;
16 use std::path::{Path, PathBuf};
17 use syntax::ast;
18
19 pub fn dep_graph_path(tcx: TyCtxt) -> Option<PathBuf> {
20     path(tcx, LOCAL_CRATE, "local")
21 }
22
23 pub fn metadata_hash_path(tcx: TyCtxt, cnum: ast::CrateNum) -> Option<PathBuf> {
24     path(tcx, cnum, "metadata")
25 }
26
27 fn path(tcx: TyCtxt, cnum: ast::CrateNum, suffix: &str) -> Option<PathBuf> {
28     // For now, just save/load dep-graph from
29     // directory/dep_graph.rbml
30     tcx.sess.opts.incremental.as_ref().and_then(|incr_dir| {
31         match create_dir_racy(&incr_dir) {
32             Ok(()) => {}
33             Err(err) => {
34                 tcx.sess.err(
35                     &format!("could not create the directory `{}`: {}",
36                              incr_dir.display(), err));
37                 return None;
38             }
39         }
40
41         let crate_name = tcx.crate_name(cnum);
42         let crate_disambiguator = tcx.crate_disambiguator(cnum);
43         let file_name = format!("{}-{}.{}.bin",
44                                 crate_name,
45                                 crate_disambiguator,
46                                 suffix);
47         Some(incr_dir.join(file_name))
48     })
49 }
50
51 // Like std::fs::create_dir_all, except handles concurrent calls among multiple
52 // threads or processes.
53 fn create_dir_racy(path: &Path) -> io::Result<()> {
54     match fs::create_dir(path) {
55         Ok(()) => return Ok(()),
56         Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => return Ok(()),
57         Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
58         Err(e) => return Err(e),
59     }
60     match path.parent() {
61         Some(p) => try!(create_dir_racy(p)),
62         None => return Err(io::Error::new(io::ErrorKind::Other,
63                                           "failed to create whole tree")),
64     }
65     match fs::create_dir(path) {
66         Ok(()) => Ok(()),
67         Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
68         Err(e) => Err(e),
69     }
70 }
71