UNPKG

2.88 kBPlain TextView Raw
1#! /usr/bin/env node
2
3import { build } from './builder';
4import { getDestinations } from './destinations';
5import { buildTree } from './fileTree';
6import { getBarrelName } from './options/barrelName';
7import { getCombinedBaseUrl } from './options/baseUrl';
8import { getLogger } from './options/logger';
9import { getSemicolonCharacter } from './options/noSemicolon';
10import { Arguments, LocationOption } from './options/options';
11import { getQuoteCharacter } from './options/quoteCharacter';
12import { resolveRootPath } from './options/rootPath';
13import { purge } from './purge';
14import { Directory } from './interfaces/directory.interface';
15
16// TODO: Document how users can call this from their own code without using the CLI.
17// TODO: We might need to do some parameter validation for that.
18export function Barrelsby(args: Arguments) {
19 // Get the launch options/arguments.
20 const logger = getLogger({ isVerbose: args.verbose ?? false });
21 const barrelName = getBarrelName(args.name ?? '', logger);
22 const directories = !Array.isArray(args.directory) ? [args.directory ?? './'] : args.directory ?? ['./'];
23
24 logger.debug(`Directories passed`, directories);
25
26 const resolvedDirectories = directories.map(directory => {
27 const rootPath = resolveRootPath(directory);
28 logger.debug('Resolved root path %s', rootPath);
29 return {
30 dir: directory,
31 rootPath,
32 baseUrl: getCombinedBaseUrl(rootPath, args.baseUrl),
33 };
34 });
35
36 logger.debug('resolved directories list', resolvedDirectories);
37
38 resolvedDirectories.forEach(async ({ rootPath, baseUrl }) => {
39 // Build the directory tree.
40 const rootTree = buildTree(rootPath, barrelName, logger);
41 logger.debug(`root tree for path: ${rootPath}`, rootTree);
42
43 // Work out which directories should have barrels.
44 const destinations: Directory[] = getDestinations(rootTree, args.location as LocationOption, barrelName, logger);
45
46 logger.debug('Destinations', destinations);
47
48 // Potentially there are some existing barrels that need removing.
49 purge(rootTree, args.delete ?? false, args.noHeader ?? false, barrelName, logger);
50
51 // Create the barrels.
52 const quoteCharacter = getQuoteCharacter(args.singleQuotes as boolean);
53 const semicolonCharacter = getSemicolonCharacter(args.noSemicolon as boolean);
54 // Add header to each barrel if the `noHeader` option is not true
55 const addHeader = args.noHeader === false;
56
57 await build({
58 addHeader,
59 destinations,
60 quoteCharacter,
61 semicolonCharacter,
62 barrelName,
63 logger,
64 baseUrl,
65 exportDefault: !!args.exportDefault,
66 fullPathname: !!args.fullPathname,
67 structure: args.structure,
68 local: !!args.local,
69 include: ([] as string[]).concat(args.include || []),
70 exclude: ([] as string[]).concat(args.exclude || [], ['node_modules']),
71 });
72 });
73}