create-header.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * @module create-header
  3. * @author Toru Nagashima
  4. * @copyright 2016 Toru Nagashima. All rights reserved.
  5. * See LICENSE file in root directory for full license.
  6. */
  7. "use strict"
  8. //------------------------------------------------------------------------------
  9. // Requirements
  10. //------------------------------------------------------------------------------
  11. const ansiStyles = require("ansi-styles")
  12. //------------------------------------------------------------------------------
  13. // Public Interface
  14. //------------------------------------------------------------------------------
  15. /**
  16. * Creates the header text for a given task.
  17. *
  18. * @param {string} nameAndArgs - A task name and arguments.
  19. * @param {object} packageInfo - A package.json's information.
  20. * @param {object} packageInfo.body - A package.json's JSON object.
  21. * @param {string} packageInfo.path - A package.json's file path.
  22. * @param {boolean} isTTY - The flag to color the header.
  23. * @returns {string} The header of a given task.
  24. */
  25. module.exports = function createHeader(nameAndArgs, packageInfo, isTTY) {
  26. if (!packageInfo) {
  27. return `\n> ${nameAndArgs}\n\n`
  28. }
  29. const index = nameAndArgs.indexOf(" ")
  30. const name = (index === -1) ? nameAndArgs : nameAndArgs.slice(0, index)
  31. const args = (index === -1) ? "" : nameAndArgs.slice(index + 1)
  32. const packageName = packageInfo.body.name
  33. const packageVersion = packageInfo.body.version
  34. const scriptBody = packageInfo.body.scripts[name]
  35. const packagePath = packageInfo.path
  36. const color = isTTY ? ansiStyles.gray : { open: "", close: "" }
  37. return `
  38. ${color.open}> ${packageName}@${packageVersion} ${name} ${packagePath}${color.close}
  39. ${color.open}> ${scriptBody} ${args}${color.close}
  40. `
  41. }