ianwremmel
8/6/2017 - 4:29 PM

codemod: add header banner

codemod: add header banner

/**
 * Adds a copyright banner to all files, removing any copyright banner that may
 * have already existed.
 *
 * Note: You'll need to run `eslint --fix` afterwards to remove the stray
 * whitespace that this transform adds.
 */
module.exports = function transform({source}, {jscodeshift}) {
  const j = jscodeshift;
  // apply trim to remove any leading whitespace that may already exist
  let root = jscodeshift(source.trim());

  const banner = j.commentBlock(`!\n * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.\n `);

  root
    .find(j.Program)
    .forEach((path) => {
      const body = path.node.body;
      const first = body[0];

      if (first.comments && (first.comments[0].value.startsWith(`!`) || first.comments[0].value.startsWith(`*!`))) {
        first.comments.shift();
      }
    });

  root = jscodeshift(root.toSource().trim());

  root
    .find(j.Program)
    .forEach((path) => {
      const comments = path.node.comments = path.node.comments || [];
      comments.push(banner);

      const body = path.node.body;
      body.unshift(` `);
    });

  return `${root.toSource().trim()}\n`;
};