forc-migrate 0.71.0

Migrate Sway projects to the next breaking change version of Sway.
Documentation
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
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
use std::{
    collections::HashSet,
    path::{Path, PathBuf},
};

use anyhow::{bail, Ok, Result};
use clap::Parser;
use forc_tracing::{println_action_green, println_action_yellow, println_yellow_bold};
use forc_util::{format_diagnostic, fs_locking::is_file_dirty};
use itertools::Itertools;
use sway_ast::Module;
use sway_core::{
    language::lexed::{LexedModule, LexedProgram},
    Engines,
};
use sway_error::formatting::*;
use sway_features::{ExperimentalFeatures, Feature};
use sway_types::{SourceEngine, Span};
use swayfmt::Formatter;

use crate::{
    cli::{
        self,
        shared::{
            compile_package, create_migration_diagnostic, detailed_migration_guide_msg,
            max_feature_name_len, PROJECT_IS_COMPATIBLE,
        },
    },
    get_migration_steps_or_return, instructive_error,
    migrations::{
        ContinueMigrationProcess, DryRun, InteractionResponse, MigrationStep, MigrationStepKind,
        MigrationSteps, Occurrence, ProgramInfo,
    },
};

forc_util::cli_examples! {
    crate::cli::Opt {
        [ Migrate the project in the current path => "forc migrate run"]
        [ Migrate the project located in another path => "forc migrate run --path {path}" ]
        [ Migrate the project offline without downloading any dependencies => "forc migrate run --offline" ]
    }
}

/// Migrate the project.
///
/// Runs the migration steps and and guides you through the migration process.
#[derive(Debug, Parser)]
pub(crate) struct Command {
    #[clap(flatten)]
    pub run: cli::shared::Compile,
}

/// Contains information about lexed [Module]s that are modified
/// during a migration step.
struct ModifiedModules<'a> {
    source_engine: &'a SourceEngine,
    modified_modules_paths: HashSet<PathBuf>,
}

impl<'a> ModifiedModules<'a> {
    fn new(source_engine: &'a SourceEngine, occurrences_spans: &[Span]) -> Self {
        Self {
            source_engine,
            modified_modules_paths: occurrences_spans
                .iter()
                .filter_map(|span| span.source_id().copied())
                .filter(|source_id| !source_engine.is_source_id_autogenerated(source_id))
                .map(|source_id| source_engine.get_path(&source_id))
                .collect(),
        }
    }

    /// Returns the `module`s path, if the `module` was modified.
    fn get_path_if_modified(&self, module: &Module) -> Option<PathBuf> {
        module.source_id().and_then(|source_id| {
            let path = self.source_engine.get_path(&source_id);
            if self.modified_modules_paths.contains(&path) {
                Some(path)
            } else {
                None
            }
        })
    }

    /// Returns the paths of modified modules, that are at the same
    /// time marked as "dirty", means in-use by some other programs
    /// like IDEs.
    fn get_dirty_modified_modules_paths(&self) -> Vec<&PathBuf> {
        self.modified_modules_paths
            .iter()
            .filter(|path| is_file_dirty(path))
            .collect()
    }
}

pub(crate) fn exec(command: Command) -> Result<()> {
    let migration_steps = get_migration_steps_or_return!();
    let engines = Engines::default();
    let build_instructions = command.run;

    let experimental = build_instructions.experimental_features()?;

    let mut program_info = compile_package(&engines, &build_instructions)?;

    // For migrations, we go with the following workflow.
    // We have three possible situations:
    //  - we skip a migration step if it doesn't have any occurrences in code.
    //    We say that the step is *checked*.
    //  - we *check* an instruction migration step if it does have occurrences in code.
    //    We print those occurrences.
    //  - we *migrate* a code transformation step if it does have changes in code.
    //    We rewrite original code files with the changed code.
    //    We print just the number of the applied transformations.
    //
    // Skipping (checked) and checking will move to the next migration step.
    //
    // Migrating will stop the further execution of migration steps **if there are manual migration actions**
    // to be done by developers. In that case, it will ask for manual action and instruct developers to review
    // the changes before continuing migration.
    //
    // Migrating **without manual migration actions** will move to the next migration step **in the same feature**.
    // If that was the last migration step in the feature, the migration will stop, and instruct the developer
    // to review the migrations done in that feature, before continuing to migrate the next experimental feature.

    print_migrating_action(migration_steps);

    let max_len = max_feature_name_len(migration_steps);
    let last_migration_feature = migration_steps
        .last()
        .expect(
            "`get_migration_steps_or_return!` guarantees that the `migration_steps` are not empty",
        )
        .0;
    let mut current_feature_migration_has_code_changes = false;
    let mut num_of_postponed_steps = 0;
    for (feature, migration_steps) in migration_steps.iter() {
        for migration_step in migration_steps.iter() {
            match migration_step.kind {
                MigrationStepKind::Instruction(instruction) => {
                    let occurrences = instruction(&program_info)?;

                    print_instruction_result(
                        &engines,
                        max_len,
                        feature,
                        migration_step,
                        &occurrences,
                    );

                    if !occurrences.is_empty() {
                        println_yellow_bold("If you've already reviewed the above points, you can ignore this info.");
                    }
                }
                MigrationStepKind::CodeModification(
                    modification,
                    manual_migration_actions,
                    continue_migration_process,
                ) => {
                    let occurrences = modification(&mut program_info.as_mut(), DryRun::No)?;

                    output_modified_modules(
                        &build_instructions.manifest_dir()?,
                        &program_info,
                        &occurrences,
                        experimental,
                    )?;

                    let stop_migration_process = print_modification_result(
                        max_len,
                        feature,
                        migration_step,
                        manual_migration_actions,
                        continue_migration_process,
                        &occurrences,
                        InteractionResponse::None,
                        &mut current_feature_migration_has_code_changes,
                    );
                    if stop_migration_process == StopMigrationProcess::Yes {
                        return Ok(());
                    }
                }
                MigrationStepKind::Interaction(
                    instruction,
                    interaction,
                    manual_migration_actions,
                    continue_migration_process,
                ) => {
                    let instruction_occurrences_spans = instruction(&program_info)?;

                    print_instruction_result(
                        &engines,
                        max_len,
                        feature,
                        migration_step,
                        &instruction_occurrences_spans,
                    );

                    // We have occurrences, let's continue with the interaction.
                    if !instruction_occurrences_spans.is_empty() {
                        let (interaction_response, interaction_occurrences_spans) =
                            interaction(&mut program_info.as_mut())?;

                        if interaction_response == InteractionResponse::PostponeStep {
                            num_of_postponed_steps += 1;
                        }

                        output_modified_modules(
                            &build_instructions.manifest_dir()?,
                            &program_info,
                            &interaction_occurrences_spans,
                            experimental,
                        )?;

                        let stop_migration_process = print_modification_result(
                            max_len,
                            feature,
                            migration_step,
                            manual_migration_actions,
                            continue_migration_process,
                            &interaction_occurrences_spans,
                            interaction_response,
                            &mut current_feature_migration_has_code_changes,
                        );
                        if stop_migration_process == StopMigrationProcess::Yes {
                            return Ok(());
                        }
                    }
                }
            };
        }

        // If there were code changes and this is not the last feature,
        // stop for a review before continuing with the next feature.
        if current_feature_migration_has_code_changes {
            if *feature == last_migration_feature {
                print_migration_finished_action(num_of_postponed_steps);
            } else {
                print_continue_migration_action("Review the changed code");
            }

            return Ok(());
        }
    }

    // We've run through all the migration steps.
    // Print the confirmation message, even if there were maybe infos
    // displayed for manual reviews.
    print_migration_finished_action(num_of_postponed_steps);

    Ok(())
}

#[derive(PartialEq, Eq)]
enum StopMigrationProcess {
    Yes,
    No,
}

#[allow(clippy::too_many_arguments)]
fn print_modification_result(
    max_len: usize,
    feature: &Feature,
    migration_step: &MigrationStep,
    manual_migration_actions: &[&str],
    continue_migration_process: ContinueMigrationProcess,
    occurrences: &[Occurrence],
    interaction_response: InteractionResponse,
    current_feature_migration_has_code_changes: &mut bool,
) -> StopMigrationProcess {
    if occurrences.is_empty() {
        if interaction_response == InteractionResponse::PostponeStep {
            print_postponed_action(max_len, feature, migration_step);
        } else {
            print_checked_action(max_len, feature, migration_step);
        }
        StopMigrationProcess::No
    } else {
        print_changing_code_action(max_len, feature, migration_step);

        // Print the confirmation.
        println!(
            "Source code successfully changed ({} change{}).",
            occurrences.len(),
            plural_s(occurrences.len())
        );

        // Check if we can proceed with the next migration step,
        // or we have a mandatory stop, or a stop for completing manual actions.
        match continue_migration_process {
            ContinueMigrationProcess::Never => {
                print_continue_migration_action("Review the changed code");

                StopMigrationProcess::Yes
            }
            ContinueMigrationProcess::IfNoManualMigrationActionsNeeded => {
                if !migration_step.has_manual_actions() {
                    // Mark the feature as having made code changes in the migration, and proceed with the
                    // next migration step *within the same feature*, if any.
                    *current_feature_migration_has_code_changes = true;

                    StopMigrationProcess::No
                } else {
                    // Display the manual migration actions and stop the further execution of the migration steps.
                    println!();
                    println!("You still need to manually:");
                    manual_migration_actions
                        .iter()
                        .for_each(|help| println!("- {help}"));
                    println!();
                    println!("{}", detailed_migration_guide_msg(feature));
                    print_continue_migration_action("Do the above manual changes");

                    StopMigrationProcess::Yes
                }
            }
        }
    }
}

fn print_instruction_result(
    engines: &Engines,
    max_len: usize,
    feature: &Feature,
    migration_step: &MigrationStep,
    occurrences: &[Occurrence],
) {
    if occurrences.is_empty() {
        print_checked_action(max_len, feature, migration_step);
    } else {
        print_review_action(max_len, feature, migration_step);

        if let Some(diagnostic) =
            create_migration_diagnostic(engines.se(), feature, migration_step, occurrences)
        {
            format_diagnostic(&diagnostic);
        }
    }
}

/// Outputs modified modules, if any, to their original files.
///
/// A module is considered modified, if any of the [Span]s in `occurrences_spans`
/// has that module as its source.
fn output_modified_modules(
    manifest_dir: &Path,
    program_info: &ProgramInfo,
    occurrences: &[Occurrence],
    experimental: ExperimentalFeatures,
) -> Result<()> {
    if occurrences.is_empty() {
        return Ok(());
    }

    let modified_modules = ModifiedModules::new(
        program_info.engines.se(),
        &occurrences
            .iter()
            .map(|o| o.span.clone())
            .collect::<Vec<_>>(),
    );

    check_that_modified_modules_are_not_dirty(&modified_modules)?;

    output_changed_lexed_program(
        manifest_dir,
        &modified_modules,
        &program_info.lexed_program,
        experimental,
    )?;

    Ok(())
}

fn check_that_modified_modules_are_not_dirty(modified_modules: &ModifiedModules) -> Result<()> {
    let dirty_modules = modified_modules.get_dirty_modified_modules_paths();
    if !dirty_modules.is_empty() {
        bail!(instructive_error("Files cannot be changed, because they are open in an editor and contain unsaved changes.",
            &[
                "The below files are open in an editor and contain unsaved changes:".to_string(),
            ]
            .into_iter()
            .chain(dirty_modules.iter().map(|file| format!(" - {}", file.display())))
            .chain(vec!["Please save the open files before running the migrations.".to_string()])
            .collect::<Vec<_>>()
        ));
    }
    Ok(())
}

fn output_changed_lexed_program(
    manifest_dir: &Path,
    modified_modules: &ModifiedModules,
    lexed_program: &LexedProgram,
    experimental: ExperimentalFeatures,
) -> Result<()> {
    fn output_modules_rec(
        manifest_dir: &Path,
        modified_modules: &ModifiedModules,
        lexed_module: &LexedModule,
        experimental: ExperimentalFeatures,
    ) -> Result<()> {
        if let Some(path) = modified_modules.get_path_if_modified(&lexed_module.tree.value) {
            let mut formatter = Formatter::from_dir(manifest_dir, experimental)?;

            let code = formatter.format_module(&lexed_module.tree.clone())?;

            std::fs::write(path, code)?;
        }

        for (_, lexed_submodule) in lexed_module.submodules.iter() {
            output_modules_rec(
                manifest_dir,
                modified_modules,
                &lexed_submodule.module,
                experimental,
            )?;
        }

        Ok(())
    }

    output_modules_rec(
        manifest_dir,
        modified_modules,
        &lexed_program.root,
        experimental,
    )
}

fn print_migrating_action(migration_steps: MigrationSteps) {
    println_action_green(
        "Migrating",
        &format!(
            "Breaking change feature{} {}",
            plural_s(migration_steps.len()),
            sequence_to_str(
                &migration_steps
                    .iter()
                    .map(|(feature, _)| feature.name())
                    .collect_vec(),
                Enclosing::None,
                4
            ),
        ),
    );
}

fn print_changing_code_action(max_len: usize, feature: &Feature, migration_step: &MigrationStep) {
    println_action_yellow(
        "Changing",
        &full_migration_step_title(max_len, feature, migration_step),
    );
}

fn print_checked_action(max_len: usize, feature: &Feature, migration_step: &MigrationStep) {
    println_action_green(
        "Checked",
        &full_migration_step_title(max_len, feature, migration_step),
    );
}

fn print_review_action(max_len: usize, feature: &Feature, migration_step: &MigrationStep) {
    println_action_yellow(
        "Review",
        &full_migration_step_title(max_len, feature, migration_step),
    );
}

fn print_postponed_action(max_len: usize, feature: &Feature, migration_step: &MigrationStep) {
    println_action_yellow(
        "Postponed",
        &full_migration_step_title(max_len, feature, migration_step),
    );
}

fn print_migration_finished_action(num_of_postponed_steps: usize) {
    if num_of_postponed_steps > 0 {
        println_action_green(
            "Finished",
            &format!(
                "Run `forc migrate` at a later point to resolve {} postponed migration step{}",
                num_to_str(num_of_postponed_steps),
                plural_s(num_of_postponed_steps),
            ),
        )
    } else {
        println_action_green("Finished", PROJECT_IS_COMPATIBLE);
    }
}

fn print_continue_migration_action(txt: &str) {
    println_action_yellow(
        "Continue",
        &format!("{txt} and re-run `forc migrate` to finish the migration process"),
    );
}

/// Returns the [MigrationStep::title] prefixed by its [Feature::name].
fn full_migration_step_title(
    max_len: usize,
    feature: &Feature,
    migration_step: &MigrationStep,
) -> String {
    let feature_name_len = max_len + 2;
    format!(
        "{:<feature_name_len$}  {}",
        format!("[{}]", feature.name()),
        migration_step.title
    )
}