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
use crate::{
    ra_ap_syntax::AstNode,
    semver::{SemVerError, Version as SemverVersion},
    utils::{normalize, Error, INTERNAL_ERR},
    Semantics, Version,
};

use log::{debug, info, trace};
use oclif::term::{OUT_YELLOW, TERM_OUT};
use ra_ap_base_db::{FileId, SourceDatabase, SourceDatabaseExt};
use ra_ap_hir::Crate;
use ra_ap_ide_db::symbol_index::SymbolsDatabase;
use ra_ap_paths::AbsPathBuf;
use ra_ap_project_model::{CargoConfig, ProjectManifest, ProjectWorkspace};
use ra_ap_rust_analyzer::cli::load_cargo::{load_workspace, LoadCargoConfig};
use ra_ap_text_edit::TextEdit;
use rust_visitor::Visitor;

use std::{
    collections::HashMap as Map,
    fs::{read_to_string, write},
    path::Path,
};

mod context;
mod helpers;
mod visitor_impl;

pub(crate) use context::Context;

pub struct Runner {
    pub(crate) minimum: Option<SemverVersion>,
    pub(crate) versions: Vec<Version>,
    version: SemverVersion,
}

impl Runner {
    pub fn new() -> Self {
        Self {
            minimum: None,
            versions: vec![],
            version: SemverVersion::parse("0.0.0").expect(INTERNAL_ERR),
        }
    }

    pub fn minimum(mut self, version: &str) -> Result<Self, SemVerError> {
        self.minimum = Some(SemverVersion::parse(version)?);
        Ok(self)
    }

    pub fn version(mut self, version: Version) -> Self {
        self.versions.push(version);
        self
    }
}

impl Runner {
    fn get_version(&self) -> Option<&Version> {
        self.versions.iter().find(|x| x.version == self.version)
    }
}

#[doc(hidden)]
pub fn run(
    root: &Path,
    dep: &str,
    mut runner: Runner,
    from: SemverVersion,
    to: SemverVersion,
) -> Result<(), Error> {
    info!("Workspace root: {}", root.display());

    if let Some(min) = &runner.minimum {
        if from < *min {
            return Err(Error::NotMinimum(dep.into(), min.to_string()));
        }
    }

    runner.version = to;
    let version = runner.get_version();

    let peers = if let Some(version) = version {
        let mut peers = vec![dep.to_string()];
        peers.extend(version.peers.clone());
        peers
    } else {
        return Ok(TERM_OUT.write_line(&format!(
            "Upgrader for crate {} has not described any changes for {} version",
            OUT_YELLOW.apply_to(dep),
            OUT_YELLOW.apply_to(runner.version),
        ))?);
    };

    // Loading project
    let manifest = ProjectManifest::discover_single(&AbsPathBuf::assert(root.into())).unwrap();

    let no_progress = &|_| {};

    let mut cargo_config = CargoConfig::default();
    cargo_config.no_sysroot = true;

    let mut workspace = ProjectWorkspace::load(manifest, &cargo_config, no_progress)?;
    let bs = workspace.run_build_scripts(&cargo_config, no_progress)?;
    workspace.set_build_scripts(bs);

    let load_cargo_config = LoadCargoConfig {
        load_out_dirs_from_check: true,
        with_proc_macro: true,
        prefill_caches: false,
    };
    let (host, vfs, _) = load_workspace(workspace, &load_cargo_config).unwrap();

    // Preparing running wrapper
    let db = host.raw_database();
    let semantics = Semantics::new(db);

    let mut changes = Map::<FileId, TextEdit>::new();
    let mut context = Context::new(runner, semantics);

    // Run init hook
    context.init(&from)?;

    trace!("Crate graph: {:#?}", db.crate_graph());

    // Loop to find and eager load the dep we are upgrading
    for krate in Crate::all(db) {
        if let Some(name) = krate.display_name(db) {
            debug!("Checking if we need to preload: {}", name);

            if let Some(peer) = peers
                .iter()
                .find(|x| **x == normalize(&format!("{}", name)))
            {
                context.preloader.load(peer, db, &krate);
            }
        }
    }

    // Actual loop to walk through the source code
    for source_root_id in db.local_roots().iter() {
        let source_root = db.source_root(*source_root_id);
        let krates = db.source_root_crates(*source_root_id);

        // Get all crates for this source root and skip if no root files of those crates
        // are in the root path we are upgrading.
        if !krates
            .iter()
            .filter_map(|crate_id| {
                let krate: Crate = (*crate_id).into();
                source_root.path_for_file(&krate.root_file(db))
            })
            .filter_map(|path| path.as_path())
            .any(|path| {
                debug!("Checking if path in workspace: {}", path.display());
                path.as_ref().starts_with(root)
            })
        {
            continue;
        }

        for file_id in source_root.iter() {
            let file = vfs.file_path(file_id);
            info!("Walking: {}", file.as_path().expect(INTERNAL_ERR).display());

            let source_file = context.semantics.parse(file_id);
            trace!("Syntax: {:#?}", source_file.syntax());

            context.walk(source_file.syntax());

            let edit = context.upgrader.finish();
            debug!("Changes to be made: {:#?}", edit);

            changes.insert(file_id, edit);
        }
    }

    // Apply changes
    for (file_id, edit) in changes {
        let full_path = vfs.file_path(file_id);
        let full_path = full_path.as_path().expect(INTERNAL_ERR);

        let mut file_text = read_to_string(&full_path)?;

        edit.apply(&mut file_text);
        write(&full_path, file_text)?;
    }

    // TODO: Modify Cargo.toml

    Ok(())
}