From f382abc2f30a9cd53a6ba59b2fe47b27363c46dd Mon Sep 17 00:00:00 2001 From: Alhadis Date: Wed, 7 Sep 2016 03:14:49 +1000 Subject: [PATCH] Add logic to consume and parse options --- script/add-grammar | 85 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100755 script/add-grammar diff --git a/script/add-grammar b/script/add-grammar new file mode 100755 index 00000000..11bb1889 --- /dev/null +++ b/script/add-grammar @@ -0,0 +1,85 @@ +#!/usr/bin/env ruby + +require "optparse" + +ROOT = File.expand_path("../../", __FILE__) + + +# Break a repository URL into its separate components +def parse_url(input) + hosts = "github\.com|bitbucket\.org|gitlab\.com" + + # HTTPS/HTTP link pointing to recognised hosts + if input =~ /^(?:https?:\/\/)?(?:[^.@]+@)?(?:www\.)?(#{hosts})\/([^\/]+)\/([^\/]+)/i + { host: $1.downcase(), user: $2, repo: $3.sub(/\.git$/, "") } + # SSH + elsif input =~ /^git@(#{hosts}):([^\/]+)\/([^\/]+)\.git$/i + { host: $1.downcase(), user: $2, repo: $3 } + # provider:user/repo + elsif input =~ /^(github|bitbucket|gitlab):\/?([^\/]+)\/([^\/]+)\/?$/i + { host: $1.downcase(), user: $2, repo: $3 } + # user/repo - Common GitHub shorthand + elsif input =~ /^\/?([^\/]+)\/([^\/]+)\/?$/ + { host: "github.com", user: $1, repo: $2 } + else + raise "Unsupported URL: #{input}" + end +end + +# Isolate the vendor-name component of a submodule path +def parse_submodule(name) + name =~ /^(?:.*(?:vendor\/)?grammars\/)?([^\/]+)/i + path = "vendor/grammars/#{$1}" + unless File.exist?("#{ROOT}/" + path) + warn "Submodule '#{path}' does not exist. Aborting." + exit 1 + end + path +end + +usage = """Usage: + #{$0} [--replace grammar] url +Examples: + #{$0} https://github.com/Alhadis/language-roff + #{$0} --replace sublime-apl https://github.com/Alhadis/language-apl +""" + + +$replace = nil +$verbose = false + +OptionParser.new do |opts| + opts.banner = usage + opts.on("-v", "--verbose", "Print verbose feedback to STDOUT") do + $verbose = true + end + opts.on("-rSUBMODULE", "--replace=SUBMODDULE", "Replace an existing grammar submodule.") do |name| + $replace = name + end +end.parse! + + +$url = ARGV[0] + +# No URL? Print a usage message and bail. +unless $url + warn usage + exit 1; +end + + +# Ensure the given URL is an HTTPS link +parts = parse_url $url +https = "https://#{parts[:host]}/#{parts[:user]}/#{parts[:repo]}" +path = "vendor/grammars/#{parts[:repo]}" +repl = parse_submodule($replace) if $replace + +if $verbose + puts "Adding grammar" + puts "\tFrom: #{https}" + puts "\tInto: #{path}" + puts "\tReplacing: #{repl}" if repl + puts "\nRegistering submodule..." +end + +#`git submodule add #{https} #{path}`