console#log TypeScript Examples

The following examples show how to use console#log. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: saveDatapack.ts    From sandstone with MIT License 5 votes vote down vote up
function saveResource<T extends ResourceTypes>(
  rootPath: string | null,
  type: T,
  resource: ResourceTypeMap[T],
  options: SaveOptions & { relativePath?: string },
  getRepresentation: (resource_: ResourceOnlyTypeMap[T], consoleDisplay: boolean) => string,
  getDisplayTitle: (namespace: string, folders: string[], fileName: string) => string,
): Promise<void>[] {
  // This ensure the function is async, and can be await
  const writeFileToDisk = async (info: CustomHandlerFileObject) => {
    const customFileHandler = options?.customFileHandler
    if (!customFileHandler && info.rootPath) {
      // If we don't have a custom file handler, info.rootPath is necessarily not null
      return writeFile(info as SaveFileObject)
    }
    if (customFileHandler) {
      return customFileHandler(info)
    }
    return undefined
  }

  const promises: Promise<void>[] = []

  if (resource.isResource) {
    const [namespace, ...folders] = resource.path

    const basePath = path.join('data', namespace, type)
    const fileName = folders.pop() as string
    const resourceFolder = path.join(basePath, ...folders)

    if (!options.dryRun) {
      if (!options.customFileHandler && rootPath) {
        createDirectory(path.join(rootPath, resourceFolder))
      }

      // Write the commands to the file system
      const isCustomResource = (resource_: unknown): resource_ is CustomResource & { isResource: true } => type.includes('custom')

      let extension = 'json'
      if (isCustomResource(resource)) {
        extension = resource.extension
      }
      if (type === 'functions') {
        extension = 'mcfunction'
      }

      const resourcePath = path.join(options.relativePath ?? resourceFolder, `${fileName}.${extension}`)

      promises.push(
        writeFileToDisk({
          packType: 'datapack',
          type,
          content: getRepresentation(resource as ResourceOnlyTypeMap[T], false),
          rootPath,
          relativePath: resourcePath,
          resource,
          saveOptions: options,
        }),
      )
    }

    if (options.verbose) {
      console.log(chalk`{cyan ## ${getDisplayTitle(namespace, folders, fileName)}}`)
      console.log(getRepresentation(resource as ResourceOnlyTypeMap[T], true))
      console.log()
    }
  }

  for (const r of resource.children.values()) {
    promises.push(
      ...saveResource(rootPath, type, r as ResourceTypeMap[T], options, getRepresentation, getDisplayTitle),
    )
  }

  return promises
}
Example #2
Source File: index.ts    From Aragorn with MIT License 5 votes vote down vote up
log(figlet.textSync('Aragorn Cli'));
Example #3
Source File: index.ts    From Aragorn with MIT License 5 votes vote down vote up
log();
Example #4
Source File: index.ts    From Aragorn with MIT License 5 votes vote down vote up
log(pkg.description);
Example #5
Source File: index.ts    From Aragorn with MIT License 5 votes vote down vote up
log();
Example #6
Source File: saveDatapack.ts    From sandstone with MIT License 4 votes vote down vote up
/**
 * Saves the datapack to the file system.
 *
 * @param functions A mapping between function full names and their commands.
 * @param name The name of the Datapack
 * @param options The save options.
 */
export async function saveDatapack(resources: ResourcesTree, name: string, options: SaveOptions) {
  // This ensure the function is async, and can be await
  const writeFileToDisk = async (info: SaveFileObject) => {
    const func = options?.customFileHandler ?? writeFile
    return func(info)
  }

  const indentation = options.indentation ?? 2

  try {
    const start = Date.now()

    // Files saving promises
    const promises: Promise<void>[] = []

    // Find the save path
    const rootPath: string | null = getDestinationPath(name, options)

    if (options.description !== undefined) {
      packMcMeta.pack.description = options.description as string
    }

    if (options.formatVersion !== undefined) {
      packMcMeta.pack.pack_format = options.formatVersion
    }

    if (!options.dryRun) {
      // Clean the old working directory
      if (rootPath !== null) {
        deleteDirectory(rootPath)
        createDirectory(rootPath)

        // Overwrite it
        promises.push(writeFileToDisk({
          packType: 'datapack',
          type: 'raw',
          resource: packMcMeta,
          content: JSON.stringify(packMcMeta, null, indentation),
          rootPath,
          relativePath: 'pack.mcmeta',
          saveOptions: options,
        }))
      }
    }

    for (const n of resources.namespaces.values()) {
      // Save functions
      for (const f of n.functions.values()) {
        promises.push(...saveResource(
          rootPath,
          'functions',
          f,
          options,

          // To display a function, we join their arguments. If we're in a console display, we put comments in gray.
          (func, consoleDisplay) => {
            const repr = [...func.commands].map((command) => command.join(' ')).join('\n')
            if (consoleDisplay) {
              return repr.replace(/^#(.+)/gm, chalk.gray('#$1'))
            }

            return repr
          },
          (namespace, folders, fileName) => `Function ${namespace}:${[...folders, fileName].join('/')}`,
        ))
      }

      // Save tags
      for (const t of n.tags.values()) {
        promises.push(...saveResource(
          rootPath,
          'tags',
          t,
          options,
          (r) => JSON.stringify({ replace: r.replace, values: r.values }, null, indentation),
          (namespace, folders, fileName) => `Tag[${folders[0]}] ${namespace}:${[...folders.slice(1), fileName].join('/')}`,
        ))
      }

      // Save advancements
      for (const a of n.advancements.values()) {
        promises.push(...saveResource(
          rootPath,
          'advancements',
          a,
          options,
          (r) => JSON.stringify(r.advancement, null, indentation),
          (namespace, folders, fileName) => `Avancement ${namespace}:${[...folders, fileName].join('/')}`,
        ))
      }

      // Save predicates
      for (const p of n.predicates.values()) {
        promises.push(...saveResource(
          rootPath,
          'predicates',
          p,
          options,
          (r) => JSON.stringify(r.predicate, null, indentation),
          (namespace, folders, fileName) => `Predicate ${namespace}:${[...folders, fileName].join('/')}`,
        ))
      }

      // Save loot tables
      for (const l of n.loot_tables.values()) {
        promises.push(...saveResource(
          rootPath,
          'loot_tables',
          l,
          options,
          (r) => JSON.stringify(r.lootTable, null, indentation),
          (namespace, folders, fileName) => `Loot table ${namespace}:${[...folders, fileName].join('/')}`,
        ))
      }

      // Save recipe
      for (const r of n.recipes.values()) {
        promises.push(...saveResource(
          rootPath,
          'recipes',
          r,
          options,
          (resource) => JSON.stringify(resource.recipe, null, indentation),
          (namespace, folders, fileName) => `Recipe ${namespace}:${[...folders, fileName].join('/')}`,
        ))
      }

      // Save item modifier
      for (const r of n.item_modifiers.values()) {
        promises.push(...saveResource(
          rootPath,
          'item_modifiers',
          r,
          options,
          (resource) => JSON.stringify(resource.modifier, null, indentation),
          (namespace, folders, fileName) => `Item modifier ${namespace}:${[...folders, fileName].join('/')}`,
        ))
      }

      // Save item modifier
      const saveType = (
        // eslint-disable-next-line no-nested-ternary
        options.world ? 'world'
          : options.asRootDatapack ? 'root'
            : 'custom-path'
      )

      const customResources = (
        Object.entries(n)
          .filter(([type]) => type.includes('custom'))
          .map(([type, resourceMap]) => resourceMap as Map<string, CustomResource>)
          .flatMap((resourceMap) => [...resourceMap.values()])
      )

      for (const r of customResources) {
        if (r.isResource) {
          const namespace: string = r.path[0]

          // eslint-disable-next-line no-await-in-loop
          const savePath = await r.save({
            saveType,
            packName: name,
            namespace,
            saveLocation: (rootPath ? path.join(rootPath, '../') : null) as any,
          })
          const relativeSavePath = rootPath ? path.relative(rootPath, savePath) : savePath

          promises.push(...saveResource(
            savePath,
            `custom-${r.type}`,
            r,
            { ...options, relativePath: relativeSavePath },
            (resource) => resource.data,
            (_, folders, fileName) => `Custom ${r.type} "${[...folders, fileName].join('/')}.${r.extension}"`,
          ))
        }
      }
    }

    // Wait until all files are written
    await Promise.all(promises)

    if (!options.dryRun && rootPath !== null) {
      console.log(chalk`{greenBright ✓ Successfully wrote data pack to "${rootPath}".} {gray (${promises.length.toLocaleString()} files - ${(Date.now() - start).toLocaleString()}ms)}`)
    } else {
      console.log(chalk`{greenBright ✓ Successfully compiled data pack.} {gray (${(Date.now() - start).toLocaleString()}ms)}`)
    }

    return {
      destination: rootPath,
    }
  } catch (e) {
    console.error(e)
    console.log(chalk`{redBright ✗ Failed to write datapack. See above for additional information.}`)
    throw e
  }
}