files | Cell 8 | Cell 10 | Search

The fixImports function resolves missing imports in a project by finding matching files based on their syntax structure and updating package.json to include new dependencies. It uses the fs, path, and importer modules to find code files, resolve imports, and update package.json.

Run example

npm run import -- "fix project paths"

fix project paths

var fs = require('fs')
var path = require('path')
var importer = require('../Core')
var {relativeImports} = importer.import("builtin and local modules")
var {glob} = importer.import("glob files")

function fixImports(project) {
    var packagePath = path.join(project, 'package.json')
    var codeFiles = glob('**/*.+(ts|js|ipynb)', project)
    codeFiles.forEach(f => {
        var imports = relativeImports(f)
        
        // TODO: find file based on matching syntax structure
        imports.missing.forEach(i => {
            var match = codeFiles
                .filter(f => path.basename(f) === path.basename(i))[0]
            if(match) {
                var newRelative = './' + path.relative(
                    path.dirname(f), path.join(project, match))
                var fixFile = fs.readFileSync(f).toString()
                fs.writeFileSync(f, fixFile.replace(i, newRelative))
            }
        })
        
        // fix package json
        if(fs.existsSync(packagePath)) {
            var packageJson = JSON.parse(fs.readFileSync(packagePath))
            var toAdd = imports.packages
                .filter(p => typeof packageJson.dependencies[p] === 'undefined'
                        && typeof packageJson.devDependencies[p] === 'undefined')
            toAdd.forEach(a => {
                console.log(`adding ${a}`)
                packageJson.dependencies[a] = 'latest'
            })
            if(toAdd.length > 0) {
                fs.writeFileSync(packagePath,
                                 JSON.stringify(packageJson, null, 4))
            }
        }
    })
}

module.exports = {
    fixImports
}

What the code could have been:

const fs = require('fs');
const path = require('path');
const { importer } = require('../Core');
const { relativeImports, glob } = importer.import('builtin and local modules');

/**
 * Fix imports for a given project by:
 * - Resolving missing imports in code files
 * - Adding missing packages to package.json
 *
 * @param {string} project - Path to the project root
 */
function fixImports(project) {
  const packagePath = path.join(project, 'package.json');
  const codeFiles = glob('**/*.+(ts|js|ipynb)', project);

  // Resolve missing imports in each code file
  codeFiles.forEach((file) => {
    const { missing } = relativeImports(file);

    // Find matching file based on syntax structure (not implemented)
    // const matchingFile = findMatchingFile(codeFiles, missing);
    // if (matchingFile) {
    //   const newRelative = './' + path.relative(
    //     path.dirname(file), path.join(project, matchingFile));
    //   const fixFileContent = fs.readFileSync(file).toString();
    //   fs.writeFileSync(file, fixFileContent.replace(missing, newRelative));
    // }

    // Replace missing imports with relative paths
    missing.forEach((importPath) => {
      const match = codeFiles.find((f) => path.basename(f) === path.basename(importPath));
      if (match) {
        const newRelative = './' + path.relative(
          path.dirname(file), path.join(project, match));
        const fixFileContent = fs.readFileSync(file).toString();
        fs.writeFileSync(file, fixFileContent.replace(importPath, newRelative));
      }
    });

    // Fix package.json to add missing dependencies
    if (fs.existsSync(packagePath)) {
      const packageJson = JSON.parse(fs.readFileSync(packagePath));
      const toAdd = relativeImports(file).packages
       .filter((pkg) => typeof packageJson.dependencies[pkg] === 'undefined'
          && typeof packageJson.devDependencies[pkg] === 'undefined');
      toAdd.forEach((pkg) => {
        console.log(`Adding ${pkg} as dependency`);
        packageJson.dependencies[pkg] = 'latest';
      });
      if (toAdd.length > 0) {
        fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 4));
      }
    }
  });
}

module.exports = {
  fixImports,
};

fixImports Function Breakdown

Purpose

The fixImports function corrects import statements in a project by:

  1. Resolving missing imports by finding matching files based on their syntax structure.
  2. Updating package.json to include new dependencies.

Requirements

Parameters

Function Flow

  1. Get code files: Uses glob to find all code files (TS, JS, and IPYNB) in the project.
  2. Resolve missing imports: For each code file, it finds matching files based on their syntax structure. It updates the import statements to use the new relative paths.
  3. Update package.json: If a package.json file exists, it adds new dependencies to the dependencies object and writes the updated file.
  4. Export: Exports the fixImports function.

Variables and Functions