Skip to content

Commit

Permalink
Cleaned up code and added 'last_file' option
Browse files Browse the repository at this point in the history
  • Loading branch information
jo1gi committed Apr 6, 2021
1 parent 687b836 commit 461ed0e
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions src/openurl.cr
Original file line number Diff line number Diff line change
@@ -1,51 +1,61 @@
require "yaml"

# Stores all of the available rules for urls to be tested against
tests = {
"protocol" => /^[^:]+/,
"domain" => /(?<=:\/\/)[^\/]+/
"domain" => /(?<=:\/\/)[^\/]+/,
"last_file" => /[^\/]+$/
}

def make_test(url, regex)
url.match(regex)
# Tests a url on a specific regex parameter from `tests`
def make_regex_test(url : String, test : Regex, value : String) : Bool
matches = url.match(test)
if matches && matches.size >= 1
part = matches[0].not_nil!
return !Regex.new(value).match(part).nil?
end
return false
end

# Loads config file
def load_config(path)
File.open(path) do |file|
YAML.parse(file)
end
end

# Returns the path of the default config file
def find_config() : String
"#{ENV["XDG_CONFIG_HOME"]}/openurl/config.yaml"
end

def test_command(url, option, tests)
# Tests if a set of rules match the url
def test_command(url, option, tests) : Bool
if !option["command"]?
return false
end
tests.each do |name, test|
if option[name]?
part = url.match(test).not_nil!.to_a[0].not_nil!
if !Regex.new(option[name].as_s).match(part).nil?
if make_regex_test(url, test, option[name].as_s)
next
else
return false
end
return false
end
end
return true
end

# Finds a command in the rules which the url matches
def find_command(url : String, config, tests)
config.as_a.each do |c|
if test_command(url, c, tests)
if c["subcommands"]?
subcommand = find_command(url, c["subcommands"], tests)
if !subcommand.nil?
if subcommand
return subcommand
end
end
return c["command"].as_s
return c["command"].as_s.not_nil!
end
end
end
Expand Down

0 comments on commit 461ed0e

Please sign in to comment.