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
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
//! Support for future-incompatible warning reporting.

use crate::core::{Dependency, PackageId, Workspace};
use crate::sources::SourceConfigMap;
use crate::util::{iter_join, CargoResult, Config};
use anyhow::{bail, format_err, Context};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::Write as _;
use std::io::{Read, Write};

pub const REPORT_PREAMBLE: &str = "\
The following warnings were discovered during the build. These warnings are an
indication that the packages contain code that will become an error in a
future release of Rust. These warnings typically cover changes to close
soundness problems, unintended or undocumented behavior, or critical problems
that cannot be fixed in a backwards-compatible fashion, and are not expected
to be in wide use.

Each warning should contain a link for more information on what the warning
means and how to resolve it.
";

/// Current version of the on-disk format.
const ON_DISK_VERSION: u32 = 0;

/// The future incompatibility report, emitted by the compiler as a JSON message.
#[derive(serde::Deserialize)]
pub struct FutureIncompatReport {
    pub future_incompat_report: Vec<FutureBreakageItem>,
}

/// Structure used for collecting reports in-memory.
pub struct FutureIncompatReportPackage {
    pub package_id: PackageId,
    pub items: Vec<FutureBreakageItem>,
}

/// A single future-incompatible warning emitted by rustc.
#[derive(Serialize, Deserialize)]
pub struct FutureBreakageItem {
    /// The date at which this lint will become an error.
    /// Currently unused
    pub future_breakage_date: Option<String>,
    /// The original diagnostic emitted by the compiler
    pub diagnostic: Diagnostic,
}

/// A diagnostic emitted by the compiler as a JSON message.
/// We only care about the 'rendered' field
#[derive(Serialize, Deserialize)]
pub struct Diagnostic {
    pub rendered: String,
    pub level: String,
}

/// The filename in the top-level `target` directory where we store
/// the report
const FUTURE_INCOMPAT_FILE: &str = ".future-incompat-report.json";
/// Max number of reports to save on disk.
const MAX_REPORTS: usize = 5;

/// The structure saved to disk containing the reports.
#[derive(Serialize, Deserialize)]
pub struct OnDiskReports {
    /// A schema version number, to handle older cargo's from trying to read
    /// something that they don't understand.
    version: u32,
    /// The report ID to use for the next report to save.
    next_id: u32,
    /// Available reports.
    reports: Vec<OnDiskReport>,
}

/// A single report for a given compilation session.
#[derive(Serialize, Deserialize)]
struct OnDiskReport {
    /// Unique reference to the report for the `--id` CLI flag.
    id: u32,
    /// Report, suitable for printing to the console.
    report: String,
}

impl Default for OnDiskReports {
    fn default() -> OnDiskReports {
        OnDiskReports {
            version: ON_DISK_VERSION,
            next_id: 1,
            reports: Vec::new(),
        }
    }
}

impl OnDiskReports {
    /// Saves a new report.
    pub fn save_report(
        ws: &Workspace<'_>,
        per_package_reports: &[FutureIncompatReportPackage],
    ) -> OnDiskReports {
        let mut current_reports = match Self::load(ws) {
            Ok(r) => r,
            Err(e) => {
                log::debug!(
                    "saving future-incompatible reports failed to load current reports: {:?}",
                    e
                );
                OnDiskReports::default()
            }
        };
        let report = OnDiskReport {
            id: current_reports.next_id,
            report: render_report(ws, per_package_reports),
        };
        current_reports.next_id += 1;
        current_reports.reports.push(report);
        if current_reports.reports.len() > MAX_REPORTS {
            current_reports.reports.remove(0);
        }
        let on_disk = serde_json::to_vec(&current_reports).unwrap();
        if let Err(e) = ws
            .target_dir()
            .open_rw(
                FUTURE_INCOMPAT_FILE,
                ws.config(),
                "Future incompatibility report",
            )
            .and_then(|file| {
                let mut file = file.file();
                file.set_len(0)?;
                file.write_all(&on_disk)?;
                Ok(())
            })
        {
            crate::display_warning_with_error(
                "failed to write on-disk future incompatible report",
                &e,
                &mut ws.config().shell(),
            );
        }
        current_reports
    }

    /// Loads the on-disk reports.
    pub fn load(ws: &Workspace<'_>) -> CargoResult<OnDiskReports> {
        let report_file = match ws.target_dir().open_ro(
            FUTURE_INCOMPAT_FILE,
            ws.config(),
            "Future incompatible report",
        ) {
            Ok(r) => r,
            Err(e) => {
                if let Some(io_err) = e.downcast_ref::<std::io::Error>() {
                    if io_err.kind() == std::io::ErrorKind::NotFound {
                        bail!("no reports are currently available");
                    }
                }
                return Err(e);
            }
        };

        let mut file_contents = String::new();
        report_file
            .file()
            .read_to_string(&mut file_contents)
            .with_context(|| "failed to read report")?;
        let on_disk_reports: OnDiskReports =
            serde_json::from_str(&file_contents).with_context(|| "failed to load report")?;
        if on_disk_reports.version != ON_DISK_VERSION {
            bail!("unable to read reports; reports were saved from a future version of Cargo");
        }
        Ok(on_disk_reports)
    }

    /// Returns the most recent report ID.
    pub fn last_id(&self) -> u32 {
        self.reports.last().map(|r| r.id).unwrap()
    }

    pub fn get_report(&self, id: u32, config: &Config) -> CargoResult<String> {
        let report = self.reports.iter().find(|r| r.id == id).ok_or_else(|| {
            let available = iter_join(self.reports.iter().map(|r| r.id.to_string()), ", ");
            format_err!(
                "could not find report with ID {}\n\
                 Available IDs are: {}",
                id,
                available
            )
        })?;
        let report = if config.shell().err_supports_color() {
            report.report.clone()
        } else {
            strip_ansi_escapes::strip(&report.report)
                .map(|v| String::from_utf8(v).expect("utf8"))
                .expect("strip should never fail")
        };
        Ok(report)
    }
}

fn render_report(
    ws: &Workspace<'_>,
    per_package_reports: &[FutureIncompatReportPackage],
) -> String {
    let mut per_package_reports: Vec<_> = per_package_reports.iter().collect();
    per_package_reports.sort_by_key(|r| r.package_id);
    let mut rendered = String::new();
    for per_package in &per_package_reports {
        rendered.push_str(&format!(
            "The package `{}` currently triggers the following future \
             incompatibility lints:\n",
            per_package.package_id
        ));
        for item in &per_package.items {
            rendered.extend(
                item.diagnostic
                    .rendered
                    .lines()
                    .map(|l| format!("> {}\n", l)),
            );
        }
        rendered.push('\n');
    }
    if let Some(s) = render_suggestions(ws, &per_package_reports) {
        rendered.push_str(&s);
    }
    rendered
}

fn render_suggestions(
    ws: &Workspace<'_>,
    per_package_reports: &[&FutureIncompatReportPackage],
) -> Option<String> {
    // This in general ignores all errors since this is opportunistic.
    let _lock = ws.config().acquire_package_cache_lock().ok()?;
    // Create a set of updated registry sources.
    let map = SourceConfigMap::new(ws.config()).ok()?;
    let package_ids: BTreeSet<_> = per_package_reports
        .iter()
        .map(|r| r.package_id)
        .filter(|pkg_id| pkg_id.source_id().is_registry())
        .collect();
    let source_ids: HashSet<_> = package_ids
        .iter()
        .map(|pkg_id| pkg_id.source_id())
        .collect();
    let mut sources: HashMap<_, _> = source_ids
        .into_iter()
        .filter_map(|sid| {
            let source = map.load(sid, &HashSet::new()).ok()?;
            Some((sid, source))
        })
        .collect();
    // Query the sources for new versions.
    let mut suggestions = String::new();
    for pkg_id in package_ids {
        let source = match sources.get_mut(&pkg_id.source_id()) {
            Some(s) => s,
            None => continue,
        };
        let dep = Dependency::parse(pkg_id.name(), None, pkg_id.source_id()).ok()?;
        let summaries = source.query_vec(&dep).ok()?;
        let versions = itertools::sorted(
            summaries
                .iter()
                .map(|summary| summary.version())
                .filter(|version| *version > pkg_id.version()),
        );
        let versions = versions.map(|version| version.to_string());
        let versions = iter_join(versions, ", ");
        if !versions.is_empty() {
            writeln!(
                suggestions,
                "{} has the following newer versions available: {}",
                pkg_id, versions
            )
            .unwrap();
        }
    }
    if suggestions.is_empty() {
        None
    } else {
        Some(format!(
            "The following packages appear to have newer versions available.\n\
             You may want to consider updating them to a newer version to see if the \
             issue has been fixed.\n\n{}",
            suggestions
        ))
    }
}