1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
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
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io;
use std::mem;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use json::{self, JsonValue};
use syntax::ast::*;
use syntax::source_map::{FileLoader, SourceFile, SourceMap};
use syntax::source_map::{Span, DUMMY_SP};
use syntax::symbol::Symbol;
use syntax_pos::hygiene::SyntaxContext;

use crate::rewrite::{self, TextRewrite};

#[allow(unused_variables)]
pub trait FileIO {
    /// Called to indicate the end of a rewriting operation.  Any `save_file` or `save_rewrites`
    /// operations since the previous `end_rewrite` (or since the construction of the `FileIO`
    /// object) are part of the logical rewrite.
    fn end_rewrite(&self, sm: &SourceMap) -> io::Result<()> {
        Ok(())
    }

    fn file_exists(&self, path: &Path) -> bool {
        fs::metadata(path).is_ok()
    }

    fn abs_path(&self, path: &Path) -> io::Result<PathBuf> {
        fs::canonicalize(path)
    }

    fn read_file(&self, path: &Path) -> io::Result<String>;
    fn write_file(&self, path: &Path, s: &str) -> io::Result<()>;
    fn save_rewrites(
        &self,
        sm: &SourceMap,
        sf: &SourceFile,
        rws: &[TextRewrite],
        nodes: &[(Span, NodeId)],
    ) -> io::Result<()> {
        Ok(())
    }
    fn save_marks(
        &self,
        krate: &Crate,
        sm: &SourceMap,
        node_id_map: &HashMap<NodeId, NodeId>,
        marks: &HashSet<(NodeId, Symbol)>,
    ) -> io::Result<()> {
        Ok(())
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum OutputMode {
    InPlace,
    Alongside,
    Print,
    PrintDiff,
    Json,
    Marks,
}

impl OutputMode {
    fn overwrites(self) -> bool {
        self == OutputMode::InPlace
    }

    fn write_dest(self, path: &Path) -> Option<PathBuf> {
        match self {
            OutputMode::InPlace => Some(path.to_owned()),
            OutputMode::Alongside => Some(path.with_extension("new")),
            _ => None,
        }
    }

    fn write_rewrites_json(self) -> bool {
        self == OutputMode::Json
    }

    fn write_marks_json(self) -> bool {
        self == OutputMode::Marks
    }
}

struct RealState {
    rewrite_counter: usize,
    rewrites_json: Vec<JsonValue>,
    file_state: HashMap<PathBuf, String>,
}

impl RealState {
    fn new() -> RealState {
        RealState {
            rewrite_counter: 0,
            rewrites_json: Vec::new(),
            file_state: HashMap::new(),
        }
    }
}

pub struct RealFileIO {
    output_modes: Vec<OutputMode>,
    state: Mutex<RealState>,
}

impl RealFileIO {
    pub fn new(modes: Vec<OutputMode>) -> RealFileIO {
        RealFileIO {
            output_modes: modes,
            state: Mutex::new(RealState::new()),
        }
    }
}

impl FileIO for RealFileIO {
    fn end_rewrite(&self, _sm: &SourceMap) -> io::Result<()> {
        let mut state = self.state.lock().unwrap();
        if self
            .output_modes
            .iter()
            .any(|&mode| mode.write_rewrites_json())
        {
            let js = mem::replace(&mut state.rewrites_json, Vec::new());
            let s = json::stringify_pretty(JsonValue::Array(js), 2);
            fs::write(
                Path::new(&format!("rewrites.{}.json", state.rewrite_counter)),
                s,
            )?;
        }
        state.rewrite_counter += 1;
        Ok(())
    }

    fn read_file(&self, path: &Path) -> io::Result<String> {
        let state = self.state.lock().unwrap();
        let path = fs::canonicalize(path)?;
        if let Some(s) = state.file_state.get(&path) {
            Ok(s.clone())
        } else {
            fs::read_to_string(&path)
        }
    }

    fn write_file(&self, path: &Path, s: &str) -> io::Result<()> {
        // Handling for specific cases
        for &mode in &self.output_modes {
            match mode {
                OutputMode::InPlace => {}   // Will write output below
                OutputMode::Alongside => {} // Will write output below
                OutputMode::Print => {
                    println!(" ==== {:?} ====\n{}\n =========", path, s);
                }
                OutputMode::PrintDiff => {
                    let old_s = self.read_file(path)?;
                    println!();
                    println!("--- old/{}", path.display());
                    println!("+++ new/{}", path.display());
                    rewrite::files::print_diff(&old_s, s);
                }
                OutputMode::Json => {}  // Handled in end_rewrite
                OutputMode::Marks => {} // Handled in save_marks
            }
        }

        {
            let mut state = self.state.lock().unwrap();

            // Common handling
            for &mode in &self.output_modes {
                if let Some(dest) = mode.write_dest(path) {
                    info!("writing to {:?}", dest);
                    fs::write(&dest, s)?;
                }
            }

            if !self.output_modes.iter().any(|&mode| mode.overwrites()) {
                // None of the modes actually updated the original file, so we need to record the
                // new content internally.
                let abs_path = fs::canonicalize(path)?;
                state.file_state.insert(abs_path, s.to_owned());
            }
        }

        Ok(())
    }

    fn save_rewrites(
        &self,
        sm: &SourceMap,
        sf: &SourceFile,
        rws: &[TextRewrite],
        nodes: &[(Span, NodeId)],
    ) -> io::Result<()> {
        if !self
            .output_modes
            .iter()
            .any(|&mode| mode.write_rewrites_json())
        {
            return Ok(());
        }

        let mut state = self.state.lock().unwrap();

        // We want to buffer the rewrites so we can emit a single `rewrites.json` at the end
        // instead of making one per modified file.  However, it's hard to safely buffer the
        // TextRewrites themselves, since they contain Spans, and Spans are (possibly) indexes into
        // a thread-local interner.  So we actually convert the rewrites to json here, and buffer
        // the json instead.
        let rw = rewrite::TextRewrite {
            old_span: DUMMY_SP,
            new_span: Span::new(sf.start_pos, sf.end_pos, SyntaxContext::empty()),
            rewrites: rws.to_owned(),
            nodes: nodes.to_owned(),
            adjust: rewrite::TextAdjust::None,
        };
        state
            .rewrites_json
            .push(rewrite::json::encode_rewrite(sm, &rw));
        Ok(())
    }

    fn save_marks(
        &self,
        krate: &Crate,
        _sm: &SourceMap,
        node_id_map: &HashMap<NodeId, NodeId>,
        marks: &HashSet<(NodeId, Symbol)>,
    ) -> io::Result<()> {
        if !self
            .output_modes
            .iter()
            .any(|&mode| mode.write_marks_json())
        {
            return Ok(());
        }

        let s = rewrite::json::stringify_marks(krate, node_id_map, marks);
        let state = self.state.lock().unwrap();
        fs::write(
            Path::new(&format!("marks.{}.json", state.rewrite_counter)),
            s,
        )
    }
}

pub struct ArcFileIO(pub Arc<FileIO + Sync + Send>);

impl FileLoader for ArcFileIO {
    fn file_exists(&self, path: &Path) -> bool {
        self.0.file_exists(path)
    }

    fn abs_path(&self, path: &Path) -> Option<PathBuf> {
        self.0.abs_path(path).ok()
    }

    fn read_file(&self, path: &Path) -> io::Result<String> {
        self.0.read_file(path)
    }
}