Skip to content
This repository has been archived by the owner on Jun 1, 2023. It is now read-only.

Starting a New Command

Tim Anema edited this page Apr 24, 2020 · 4 revisions

Creating a command in your ProjectType

So we have our project type defined, and I will use the Node project type for example. We can add a run command by making the following changes.

# lib/project_types/node/cli.rb
module Node
  class Project < ShopifyCli::ProjectType
    register_command('Node::Commands::Run', "run") #register the new command
  end

  module Commands
    autoload :Run, Project.project_filepath('commands/run') # specify where the command is being loaded from
  end
end

So now we have defined the shopify run command that will be available in node projects. The command will call the Node::Commands::Run class for the functionality. So we can define this functionality by creating the file lib/project_types/node/commands/run.rb

# lib/project_types/node/commands/run.rb
module Node
  module Commands
    class Run < ShopifyCli::Command
      options do |parser, flags|
        parser.on('--host=HOST') { |h| flags[:host] = h.gsub('"', '') }
      end

      def call(*)
        puts "running on #{options.flags[:host]}"
      end

      # help is shown when the user runs `shopify help` in the list
      def self.help
        <<~HELP
          Run the service
            Usage: {{command:#{ShopifyCli::TOOL_NAME} run}}
        HELP
      end

      # extended_help is shown when the user wants more specific help `shopify help run`
      def self.extended_help
        <<~HELP
          {{bold:Options:}}
            {{cyan:--host=HOST}}: The host where the service runs.
        HELP
      end
    end
  end
end

So now if we run shopify run --host=http://google.com inside a node project it will output running on http://google.com

Adding a subcommand

So if we want to add a shopify run install command, then we can simply amend the start of the run command as follows:

# lib/project_types/node/commands/run.rb
module Node
  module Commands
    class Run < ShopifyCli::Command
      subcommand :Install, 'install', Project.project_filepath('commands/run/install')
      ...

So now we have declared that the run command has a install subcommand, and that the class Node::Commands::Run::Install will be loaded and called for that command.

module Node
  module Commands
    class Run
      class Install < ShopifyCli::SubCommand
        def call(*)
        end
      end
    end
  end
end

Subcommands are called in the same way that commands are and still should implement help and extended_help so that they are easy to understand.

Clone this wiki locally