Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Persistent side effects with Dir, File and FileUtils #91

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion src/icr/command_stack.cr
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,27 @@ module Icr
type = :struct
when .match /^alias\s/
type = :alias
when .match with_persistent_side_effect
type = :side_effect
when .match /^[A-Z]([A-Za-z0-9_]+)?\s*=[^=~]/
type = :constant_assignment
when .match /^macro\s/
type = :macro
else
type = :regular
end
@commands << Command.new(type, command)
do_push(Command.new(type, command))
end

# Pop the last command. It's used in cases if the last command results into error.
def pop
@commands.pop
end

def printable_execution_result?
[:regular, :side_effect].includes?(@commands.last.type)
end

# Generate crystal source code, based on the command in the stack.
def to_code
code =
Expand All @@ -64,6 +70,7 @@ module Icr

def __icr_exec__
#{code(:regular, 1)}
#{code(:side_effect, 1)}
end

puts "#{DELIMITER}\#{__icr_exec__.inspect}"
Expand All @@ -75,5 +82,23 @@ module Icr
cmds = @commands.select { |cmd| cmd.type == command_type }.map &.value
cmds.map { |cmd| (" " * indent_level) + cmd }.join("\n")
end

private def do_push(command)
pop_when_last_was_side_effect unless @commands.empty?
@commands << command
end

# Pop the last command if the last command got side effects.
private def pop_when_last_was_side_effect
@commands.pop if @commands.last.type == :side_effect
end

private def with_persistent_side_effect
# Dir.mkdir(), Dir.mkdir_p(), Dir.rmdir(),
# File.delete(), File.link(), File.rename(), File.symlink(),
# FileUtils.mkdir(), FileUtils.mkdir_p(), FileUtils.mv(),
# FileUtils.rm, FileUtils.rm_r(), FileUtils.rm_rf(), FileUtils.rmdir()
/^Dir\.(mkdir|rmdir)|^FileUtils\.(mkdir|mv|rm)|^File\.(delete|link|rename|symlink)/
end
end
end
2 changes: 1 addition & 1 deletion src/icr/console.cr
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ module Icr
end

private def print_execution_result?
@command_stack.commands.last.type == :regular
@command_stack.printable_execution_result?
end

private def __exit__
Expand Down