DEV Community

Ramu Narasinga
Ramu Narasinga

Posted on

Next.js Codebase Analysis <> create-next-app <> index.ts explained — Part 1.12

In the previous article, I wrote about a safe guarding technique used to avoid project name conflicts. This article is a continuation to that explaining isFolderEmpty

I was wondering why there was no console.log in the previous article and there was only a process.exit when there was a naming conflict and further digging and exploration, the following is the code used in function isFolderEmpty

/* eslint-disable import/no-extraneous-dependencies */
import { green, blue } from 'picocolors'
import fs from 'fs'
import path from 'path'

export function isFolderEmpty(root: string, name: string): boolean {
  const validFiles = [
    '.DS_Store',
    '.git',
    '.gitattributes',
    '.gitignore',
    '.gitlab-ci.yml',
    '.hg',
    '.hgcheck',
    '.hgignore',
    '.idea',
    '.npmignore',
    '.travis.yml',
    'LICENSE',
    'Thumbs.db',
    'docs',
    'mkdocs.yml',
    'npm-debug.log',
    'yarn-debug.log',
    'yarn-error.log',
    'yarnrc.yml',
    '.yarn',
  ]

  // Just conflicts? why not filesConflicts?
  // It is inferred that we are dealing with files,
  // I guess, there's no need to add 
  const conflicts = fs.readdirSync(root).filter(
    (file) =>
      // validFiles are exempt from the logging
      !validFiles.includes(file) &&
      // Support IntelliJ IDEA-based editors
      !/\.iml$/.test(file)
  )

  if (conflicts.length > 0) {
    console.log(
      `The directory ${green(name)} contains files that could conflict:`
    )
    console.log()
    // Logs the files and directories
    for (const file of conflicts) {
      try {
        const stats = fs.lstatSync(path.join(root, file))
        if (stats.isDirectory()) {
          console.log(`  ${blue(file)}/`)
        } else {
          console.log(`  ${file}`)
        }
      } catch {
        console.log(`  ${file}`)
      }
    }
    console.log()
    console.log(
      'Either try using a new directory name, or remove the files listed above.'
    )
    console.log()
    return false
  }

  return true
}
Enter fullscreen mode Exit fullscreen mode

I wrote the comments explaining what the code does, it is quite obvious.

You can read more about fs.lstatSync and fs.readdirSync and these comments are available at: https://github.com/TThroo-Dev/opensource-codebase-analysis/commit/5307bee9219e1e1681b1ec4e79a46564f49fdf8c

Conclusion:
This article explains isFolderEmpty helper function used in index.ts in create-next-app. You can make your logs colorful using picocolors

I am building a platform that explains best practices used in open source by elite programmers. Join the waitlist and I will send you the link to the tutorials once they are ready.

If you have any questions, feel free to reach out to me at ramu.narasinga@gmail.com

Top comments (0)