iDecode
iDecode

Reputation: 28866

How to run a script using "dart pub global run" command?

The directory of my package foo:

enter image description here

The pubspec.yaml file has:

name: foo

executables:
  foo: bar

The package foo is activated using dart pub global activate ... and if I add the directory to PATH environment, the following command works:

foo bar

but if I remove it, and try to run the dart pub global run command, it doesn't work.

me@mac foo % dart pub global run foo bar
Could not find bin/foo.dart.

So, how can I run a script without adding it to the PATH using dart pub global run as suggested here.

You can directly run a script from an activated package from the command line. If you are unable to run the script directly, you can also use dart pub global run.

Note: dart pub global run foo:bar works but that doesn't have to do with the executables defined in the pubspec.yaml file.

Upvotes: 0

Views: 1119

Answers (1)

Patrick O'Hara
Patrick O'Hara

Reputation: 2229

Specifying:

executables:
  foo: bar

Means that when the package is activated, the command foo will map to the file bar.dart. There is no need to specify bar when invoking it.

For example, I have this package:

name: dictionary
...
executables:
    scrabble:

It defines an executable scrabble that invokes scrabble.dart. I activate it like this:

dart pub global activate --source path dictionary

This reports:

...
Installed executable scrabble.
Activated dictionary 1.0.0 at path "[...]\Dart\dictionary".

I can invoke the scrabble command which invokes scrabble.dart. I can also invoke it like this:

dart pub global run dictionary:scrabble

If my pubspec has:

executables:
    dictionary: scrabble

Then the command dictionary invokes the file scrabble.dart.

(Do not forget to include the pub cache on your PATH. For me on Windows this is C:\Users\pohara\AppData\Roaming\Pub\Cache\bin.

Addition: continuing with the dictionary: scrabble example, when I activate dictionary` I get:

...
Installed executable dictionary.
Activated dictionary 1.0.0 at path "[...]\Dart\dictionary".

And my pub cache on Windows has this file to run the dictionary command:

> cat C:\Users\pohara\AppData\Roaming\Pub\Cache\bin\dictionary.bat
@echo off
rem This file was created by pub v2.12.2.
rem Package: dictionary
rem Version: 1.0.0
rem Executable: dictionary
rem Script: scrabble
pub global run dictionary:scrabble %*

So the command dictionary explicitly runs the scrabble file in the dictionary package.

Both these commands fail:

> dart pub global run dictionary scrabble
Could not find bin\dictionary.dart.

> dart pub global run dictionary
Could not find bin\dictionary.dart.

And of course this one succeeds:

> dart pub global run dictionary:scrabble

This is all consistent with the documentation https://dart.dev/tools/pub/pubspec#executables.

Upvotes: 1

Related Questions