Skip to content

Latest commit

 

History

History
571 lines (419 loc) · 22.5 KB

cli.md

File metadata and controls

571 lines (419 loc) · 22.5 KB

dependency-cruiser command line interface

The command line interface is a straightforward affair - you pass it a bunch of files, and dependency-cruiser will start cruising them:

depcruise [options] <files-or-directories>

Below you'll find a list of command line options you can use, divided into ones that are only available as options on the command line and into those also available in dependency-cruiser configurations.

Contents

Command line only options

  1. arguments - files and/ or directories
  2. --output-type: specify the output format
  3. --config/ --validate: use a configuration with rules and/or options
  4. --init
  5. --info: show what alt-js are supported
  6. --help/ no parameters: get help

Options also available in dependency-cruiser configurations

  1. --do-not-follow: don't cruise modules adhering to this pattern any further
  2. --exclude: exclude dependencies from being cruised
  3. --include-only: only include modules satisfying a pattern
  4. --max-depth
  5. --prefix prefixing links
  6. --module-systems
  7. --ts-pre-compilation-deps (typescript only)
  8. --ts-config: use a typescript configuration file ('project')
  9. --webpack-config: use (the resolution options of) a webpack configuration`
  10. --preserve-symlinks

Command line only options

arguments - files and/ or directories

You can pass a bunch of files, directories and 'glob' patterns. dependency-cruiser will

  • resolve the glob patterns (if any) to files and directories
  • scan directories (if any) for files with supported extensions
  • add the passed files to that ... and start the cruise with the files thus found.

Cruising multiple files and directories in one go

Just pass them as arguments. This, e.g. will cruise every file in the folders src, test and lib (recursively) + the file called index.ts in the root.

depcruise --output-type dot src test lib index.ts

passing globs as parameters

dependency-cruiser uses node-glob to make sure globs work the same accross platforms. It cannot prevent the environment from expanding globs before it can process it, however.

As each environment interprets globs slightly differently, a pattern like packages/**/src/**/*.js will yield different results.

To make sure glob expansion works exactly the same accross platforms slap some quotes around them, so it's not the environment (/ shell) expanding the glob, but dependency-cruiser itself:

depcruise "packages/**/src/**/*.js"

--output-type: specify the output format

err

For use in build scripts, in combination with --config. It's also the default reporter. Sample use:

dependency-cruise --config my-depcruise-rules.json src

This will:

  • ... print nothing and exit with code 0 if dependency-cruiser didn't find any violations of the rules in .dependency-cruiser.json.
  • ... print the violating dependencies if there is any. Moreover it will exit with exit code number of violations with severity error found in the same fashion linters and test tools do.

See the depcruise target in the package.json for a real world example.

err-long

Similar to err, but in addition for each violation it emits the comment that went with the violated rule, so it's easier to put the rule into context (and if the comment contains that information: why the rule is there, and how to fix it). If you use dependency-cruiser in a lint-staged like setup, this might be a useful format,

dependency-cruise --output-type err-long --config my-depcruise-rules.json src

dot

Supplying dot as output type will make dependency-cruiser write a GraphViz dot format directed graph. Typical use is in concert with GraphViz dot (-T is the short form of --output-type:)

dependency-cruise -x "^node_modules" -T dot src | dot -T svg > dependencygraph.svg
ddot - summarize on folder level

Since version 4.13.0 there's an experimental ddot reporter that summarizes modules on folder level. In version 6.3.0 its presentation changed a bit to be closer to the regular dot one, a.o. growing the capability to customize colors.

err-html

Generates an stand alone html report with:

  • a summary with files & dependencies cruised and the number of errors and warnings found
  • all rules, ordered by the number of violations (unviolated ones are hidden by default)
  • a list of all dependency and module violations, ordered by severity, rule name, from module, to module.
dependency-cruise --validate --output-type err-html -f dependency-report.html src test configs

screen shot of an err-html report - the real one is accessible

html

Write it to html with a dependency matrix instead:

dependency-cruise -T html -f dependencies.html src

csv

If you supply csv it will write the dependency matrix to a comma separated file - so you can import it into a spreadsheet program and analyze from there.

teamcity

Write the output in TeamCity service message format.

E.g. to cruise src (using the .dependency-cruiser config) and emit TeamCity messages to stdout:

dependency-cruise -v -T teamcity  -- src
Sample output
##teamcity[inspectionType id='not-to-dev-dep' name='not-to-dev-dep' description='Don|'t allow dependencies from src/app/lib to a development only package' category='dependency-cruiser' flowId='8970869134' timestamp='2019-06-02T10:37:56.812']
##teamcity[inspectionType id='no-orphans' name='no-orphans' description='Modules without any incoming or outgoing dependencies are might indicate unused code.' category='dependency-cruiser' flowId='8970869134' timestamp='2019-06-02T10:37:56.812']
##teamcity[inspectionType id='not-to-unresolvable' name='not-to-unresolvable' description='' category='dependency-cruiser' flowId='8970869134' timestamp='2019-06-02T10:37:56.812']
##teamcity[inspection typeId='not-to-dev-dep' message='src/asneeze.js -> node_modules/eslint/lib/api.js' file='src/asneeze.js' SEVERITY='ERROR' flowId='8970869134' timestamp='2019-06-02T10:37:56.812']
##teamcity[inspection typeId='not-to-unresolvable' message='src/index.js -> ./medontexist.json' file='src/index.js' SEVERITY='ERROR' flowId='8970869134' timestamp='2019-06-02T10:37:56.812']
##teamcity[inspection typeId='not-to-dev-dep' message='src/index.js -> node_modules/dependency-cruiser/src/main/index.js' file='src/index.js' SEVERITY='ERROR' flowId='8970869134' timestamp='2019-06-02T10:37:56.812']
##teamcity[inspection typeId='not-to-dev-dep' message='src/index.js -> node_modules/eslint/lib/api.js' file='src/index.js' SEVERITY='ERROR' flowId='8970869134' timestamp='2019-06-02T10:37:56.812']
##teamcity[inspection typeId='no-orphans' message='src/orphan.js -> src/orphan.js' file='src/orphan.js' SEVERITY='ERROR' flowId='8970869134' timestamp='2019-06-02T10:37:56.812']

Just like the err reporter the teamcity reporter has an empty output when there's no violations - and a non-zero exit code when there's errors.

json

This emits the internal representation of a cruise as json. It's the input format for depcruise-fmt, and is useful for debugging.

See output-format for more information

anon - obfuscated json

The same as json - but with all paths obfuscated. This enables you to share the result of a cruise for troubleshooting purposes without showing what the source code is about.

To save an anonymized dependency graph to anonymized-result.json do this:

depcruise --validate --output-type anon --output-to anonymized-result.json bin src

e.g. to save an anonymized graph into and svg:

depcruise --validate --output-type anon bin src | depcruise-fmt --output-type dot - | dot -T svg > anonymized_graph.svg
Sample output

Here's a part of dependency-cruiser's own dependency graph both original and obfuscated (after converting it to a graph via depcruise-fmt and dot - so it's easier to compare than the two json's):

Original
original
Obfuscated
obfuscated
How does the obfuscation work?
  • It uses the list of words you pass in options.reporterOptions.anon.wordlist to replace non-common path elements with (src/search/dragonfly-algorithm.js -> src/animal/announce.js, src/search/dragonfly-algorithm.spec.js -> src/animal/announce.spec.js).
  • (You can use any array of strings here - a good one is Sindre Sorhus' mnemonic-words, which you can simply require into the option if you're using javascript as the config file format):
    ...
    options: {
      reporterOptions:
        anon: {
          wordlist: require('mnemonic-words')
        }
    }
    ...
  • It will retain name similarties (like the announce.js/ announce.spec.js above).
  • When there's more path elements in your dependency graph than in the corpus the algorithm falls back to random strings that have the same length and pattern as the original one (secretService-record.ts -> fnwarqVboiuvq-pugnmh.ts).
  • The algorithm considers some patterns to be 'common'. It leaves those alone to retain some readability. 'Common' patterns include src, test, node_modules, ., index etc. You can find the full regexp in anonymizePath.js.
  • The algorithm obfuscates within node_modules is obfuscated as well, so it won't become apparent from the dependency graph which ones your app uses either.

--config/ --validate

Validates against a list of rules in a configuration file. This defaults to a file called .dependency-cruiser.json (/ .dependency-cruiser.js), but you can specify your own rules file, which can be in json format or a valid node module returning a rules object literal.

dependency-cruise -x node_modules --config my.rules.json src spec

Tip: usually you don't need to specify the rules file. However if run depcruise --config src, src will be interpreted as the rules file. Which is probably is not what you want. To prevent this, place -- after the last option, like so:

dependency-cruise --config -- src

The configuration specifies a bunch of regular expressions pairs your dependencies should adhere tom as well as configuration options that tweak what is cruised and how.

A simple validation configuration that forbids modules in src to use stuff in the test folder and allows everything else:

{
  "forbidden": [
    {
      "from": { "path": "^src" },
      "to": { "path": "^test" }
    }
  ]
}

You can optionally specify a name and an error severity ('error', 'warn' (the default) and 'info') with them that will appear in some reporters:

{
  "forbidden": [
    {
      "name": "no-src-to-test",
      "severity": "error",
      "from": { "path": "^src" },
      "to": { "path": "^test" }
    }
  ]
}

For more information about writing rules see the tutorial and the rules-reference. The rules-reference also describes all the options.

For an easy set up of both use --init

--init

This asks some questions and - depending on the answers - creates a dependency-cruiser configuration with some useful rules to the current folder and exits.

The configuration file is larded with documentation to make it easy to tweak.

Use --config to have dependency-cruiser take the configuration file into account.

Some of the rules that will be in the configuration (either directly or from a preset):
Rule Description
no-circular flags all circular dependencies
no-orphans flags orphan modules (except typescript .d.ts files)
no-deprecated-core flags dependencies on deprecated node 'core' modules
no-deprecated-npm flags dependencies on deprecated npm modules
no-non-package-json flags (npm) dependencies that don't occur in package.json
not-to-unresolvable flags dependencies that can't be resolved
no-duplicate-dep-types flags dependencies that occur more than once in package.json
not-to-test Don't allow dependencies from outside test folders to test folders
not-to-spec Don't allow dependencies to (typescript/ javascript/ coffeescript) spec files
not-to-dev-dep Don't allow dependencies from src/app/lib to a development only package
optional-deps-used Inform about the use of 'optional' dependencies (so you can ensure their imports a are sufficiently managed)
peer-deps-used Warn about the use of a peer dependency (they might be OK for you, but it's not typical you have them).
no-duplicate-dep-types Warn if a dependency occurs in your package.json more than once (technically: has more than one dependency type)

--info showing what alt-js are supported

Which alt-js languages dependency-cruiser supports depends on the availability it has to them. To see how dependency-cruiser perceives its environment use depcruise --info (any arguments are ignored).

Typical output
Supported:

  If you need a supported, but not enabled transpiler ('✖' below), just install
  it in the same folder dependency-cruiser is installed. E.g. 'npm i livescript'
  will enable livescript support if it's installed in your project folder.

Transpilers:

  ✔ javascript (>es1)
  ✔ coffee-script (>=1.0.0 <2.0.0)
  ✔ coffeescript (>=1.0.0 <3.0.0)
  ✖ livescript (>=1.0.0 <2.0.0)
  ✔ typescript (>=2.0.0 <4.0.0)

Extensions:

  ✔ .js
  ✔ .mjs
  ✔ .jsx
  ✔ .vue
  ✔ .ts
  ✔ .tsx
  ✔ .d.ts
  ✖ .ls
  ✔ .coffee
  ✔ .litcoffee
  ✔ .coffee.md
  ✔ .csx
  ✔ .cjsx

--help / no parameters

Running with no parameters gets you help.

Options also available in dependency-cruiser configurations

Some of the options in dependency-cruiser configurations are also available as command line options. They override what's in the configuration, so they're great if you need to quickly experiment with an option, or when you want to use one configuration for multiple purposes.

The first four options below will be of use when you want to tame the size of the visual representation of a big dependency graph. For the rest of the options you're typically best off setting in a configuration file (generate one with depcruise --init).

--do-not-follow: don't cruise modules adhering to this pattern any further

If you do want to see certain modules in your reports, but are not interested in these modules' dependencies, you'd pass the regular expression for those modules to the --do-not-follow (short: -X) option. A typical pattern you'd use with this is "node_modules" (but be sure to check out the possibilities you have with the doNotFollow option)

dependency-cruise -X "^node_modules" -T html -f deps-with-unfollowed-node_modules.html src

Details and more ways to limit dependency-cruiser from following things: check out the doNotFollow option in the rules reference.

--exclude: exclude dependencies from being cruised

If you don't want to see certain modules in your report (or not have them validated), you can exclude them by passing a regular expression to the --exclude (short: -x) option. Two examples:

dependency-cruise -x "node_modules" -T html -f deps-without-node_modules.html src
dependency-cruise -x "^(coverage|test|node_modules)" -T html -f deps-without-stuffs.html src

See the exclude option in the rules reference for details.

--include-only: only include modules satisfying a pattern

E.g. to only take modules into account that are in the src tree (and exclude all node_modules, core modules and modules otherwise outside it):

dependency-cruise --include-only "^src" -T dot src | dot -T svg > internal-dependency-graph.svg

See includeOnly in the rules reference for more details.

--max-depth

Only cruise the specified depth, counting from the specified root-module(s). This command is mostly useful in combination with visualisation output like dot to keep the generated output to a manageable size.

dependency-cruise --max-depth 2 -T dot src/main/index.ts | dot -T svg > depth-limited-dependency-graph.svg

See maxDepth

This will only be effective when you pass one file as an argument.

--prefix prefixing links

In the dot output prefix links to the source files with a string - useful to link to e.g. an on line repository.

dependency-cruise --prefix "https://github.com/you/yourrepo/tree/master/" -T dot src | dot -T svg > dependency-graph-with-links-to-gh.svg

See prefix in the rules reference for details.

--module-systems

Here you can pass a list of module systems dependency-cruiser should use to detect dependencies. It defaults to amd, cjs, es6.

See moduleSystems in the rules reference

--ts-pre-compilation-deps (typescript only)

By default dependency-cruiser does not take dependencies between typescript modules that don't exist after compilation to javascript. Pass this command line switch to do take them into account.

For details see tsPreCompilationDeps in the rules reference.

--ts-config: use a typescript configuration file ('project')

If you use typescript and want dependency-cruiser to take the baseDir's and/ or paths in your tsconfig.json into account- can pass it with this option.

Although it's possible to pass it as a command line option, you typically want to do this in a configuration file - see tsConfig section in the rules reference for details.

--webpack-config: use (the resolution options of) a webpack configuration

With a webpack config you can drastically alter how module names resolve to files on disk, a.o. with aliases. If you want dependency-cruiser to take that into account (you probaly do), you can pass the webpack config here.

However, just like with tsconfigs, you probably want to put this in a configuration file - see the webpackConfig section in the rules reference.

--preserve-symlinks

Whether to leave symlinks as is or resolve them to their realpath. This option defaults to false (which is also nodejs' default behavior since release 6).

You'll typically want to set this in the configuration file with the preserveSymlinks option.

depcruise-fmt

depcruise-fmt is a separate command line program, that takes the (json) output of a dependency-cruise and runs one of the reporters over it. This could be useful if you want to display the results of the same cruise in different ways, without having to run the cruise repeatedly. Especially on bigger code bases this can save time. Cruising all code can sometimes take more than a minute, while formatting usually takes well below a second.

For instance, to report any violations to console, create a distributable report and generate a dependency graph. With just the depcruise command this would look like

depcruise -v -T err-long src
depcruise -v -T err-html src -f violation-report.html
depcruise -v -T dot src | dot -T svg > dependency-graph.svg

With depcruise-fmt there's just one cruise and three quick depcruise-fmt commands

depcruise -v -T json src -f cruise_result.json
depcruise-fmt -T err-long cruise_result.json
depcruise-fmt -T err-html -f violation-report.html cruise_result.json
depcruise-fmt -T dot cruise_result.json | dot -T svg > dependency-graph.svg
Usage: depcruise-fmt [options] <dependency-cruiser-json>

Options:
  -V, --version             output the version number
  -f, --output-to <file>    file to write output to; - for stdout
                            (default: "-")
  -T, --output-type <type>  output type - err|err-long|err-html|dot|ddot|json
                            (default: "err")
  -h, --help                output usage information

Daphne's dependencies - a gentle introduction

Daphne's dependencies sport a visual overview of all the output formats. It also shows how Daphne and her colleagues use them in their workflow.