JHHK

欢迎来到我的个人网站
行者常至 为者常成

制作一个命令行工具

目录

示例代码

模仿pod制作一个xypod
示例代码:在xypod.rb文件内的代码
两个重要的点:
一、在文件头部指定shebang
二、给文件添加执行权限

#!/usr/bin/ruby

def handleHelp
    hint = "
Usage:

    $ pod COMMAND

    CocoaPods, the Cocoa library package manager.

Commands:

    + cache         Manipulate the CocoaPods cache
    + deintegrate   Deintegrate CocoaPods from your project
    + env           Display pod environment
    + init          Generate a Podfile for the current directory
    + install       Install project dependencies according to versions from a
                    Podfile.lock
    + ipc           Inter-process communication
    + lib           Develop pods
    + list          List pods
    + outdated      Show outdated project dependencies
    + plugins       Show available CocoaPods plugins
    + repo          Manage spec-repositories
    + search        Search for pods
    + setup         Set up the CocoaPods environment
    + spec          Manage pod specs
    + trunk         Interact with the CocoaPods API (e.g. publishing new specs)
    + try           Try a Pod!
    + update        Update outdated project dependencies and create new Podfile.lock

Options:

    --allow-root    Allows CocoaPods to run as root
    --silent        Show nothing
    --version       Show the version of the tool
    --verbose       Show more debugging information
    --no-ansi       Show output without ANSI codes
    --help          Show help banner of specified command
    "
    puts hint
end

if ARGV.length == 0 
    puts "缺少参数 请使用 --help 查看帮助"
    exit -1
end


ARGV.each do |arg|
    if arg == "--help"
        handleHelp
    elsif arg == "--version"
        puts "1.0.0"
        
    elsif arg == "repo"
        # 调用pod自身的功能
        cmd = "pod repo"
        system cmd
    else 
        puts "暂未实现"
    end
end

制作步骤

一、如何制作

# 将文件copy到bin目录下
cp ./xypod.rb /usr/local/bin/xypod

二、验证下

# 查看下安装位置
$ which xypod
/usr/local/bin/xypod

# 查看下文件格式
$ file /usr/local/bin/xypod
/usr/local/bin/xypod: Ruby script text executable, Unicode text, UTF-8 text

使用

使用跟pod的使用方式一样

$ xypod --version
1.0.0

$ pod --version
1.14.2
$ xypod --help
Usage:

    $ pod COMMAND

    CocoaPods, the Cocoa library package manager.

Commands:

    + cache         Manipulate the CocoaPods cache
    + deintegrate   Deintegrate CocoaPods from your project
    ...
$ xypod repo

trunk
- Type: CDN
- URL:  https://cdn.cocoapods.org/
- Path: /Users/lixiaoyi/.cocoapods/repos/trunk

XYAppMobileSpec
- Type: git (master)
- URL:  https://e.coding.net/lxy911/xyappmobilespec/XYAppMobileSpec.git
- Path: /Users/lixiaoyi/.cocoapods/repos/XYAppMobileSpec

2 repos

Ps:这是一个非常简单的示例,主要是了解如何将ruby代码转为一个命令行工具


行者常至,为者常成!





R
Valine - A simple comment system based on Leancloud.