Skip to content

Commit

Permalink
Initially add gitconfig lexer [without tests]
Browse files Browse the repository at this point in the history
  • Loading branch information
aonemd committed Dec 2, 2016
1 parent 3c28b75 commit 84cd379
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 0 deletions.
53 changes: 53 additions & 0 deletions lib/changit/lexer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
module Changit
class Lexer
RULES = [
[/\[(.*?)\]/, SectionToken].freeze,
[/^[^(=|\[|\s)]*\s*\=\s*[^(=|\[|\])]*/, KeyValueToken].freeze
].freeze

attr_reader :tokens, :token_hash

def initialize(expression)
@tokens = tokenize(expression)
@token_hash = to_hash
end

def to_s
@tokens.map(&:to_s).join
end

private

def tokenize(expression)
expression.gsub!(/\t/, '')

tokens = []
expression.each_line do |line|
RULES.each do |rule, token_type|
lexmeme = line.slice(rule)

if (lexmeme)
tokens << token_type.new(lexmeme)
break
end
end
end

tokens
end

def to_hash
token_hash = {}

@tokens.map do |token|
if token.class == SectionToken
token_hash[token] = []
else
token_hash[token_hash.to_a.last[0]].push(token)
end
end

token_hash
end
end
end
22 changes: 22 additions & 0 deletions lib/changit/lexer/key_value_token.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module Changit
class Lexer
class KeyValueToken
include Comparable

attr_reader :lhs # left-hand side
attr_accessor :rhs # right-hand side

def initialize(key_value)
@lhs, @rhs = key_value.split('=').map(&:strip)
end

def to_s
"\t#{@lhs} = #{@rhs}\n"
end

def <=>(another)
self.lhs <=> another.lhs
end
end
end
end
15 changes: 15 additions & 0 deletions lib/changit/lexer/section_token.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module Changit
class Lexer
class SectionToken
attr_reader :value

def initialize(section)
@section = section
end

def to_s
"#{@section}\n"
end
end
end
end

0 comments on commit 84cd379

Please sign in to comment.