Created
March 11, 2015 13:24
-
-
Save andrewshadura/1fd5f62a9eb894a74c9a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env tclsh | |
namespace eval ::autofile { | |
} | |
rename ::proc ::autofile::proc | |
rename ::open ::autofile::open | |
set ::autofile::files(::) {} | |
::autofile::proc proc {name args body} { | |
set ns [uplevel { | |
namespace current | |
}] | |
if {$ns eq "::"} { | |
set ns {} | |
} | |
set name $ns\::$name | |
::autofile::proc $name $args $body | |
trace add execution $name leave ::autofile::autoclose | |
} | |
::autofile::proc open args { | |
set cmd [uplevel { | |
if {[dict exists [info frame -2] proc]} { | |
namespace which [dict get [info frame -2] proc] | |
} | |
}] | |
set file [::autofile::open {*}$args] | |
lappend ::autofile::files($cmd) $file | |
puts "don't forget to close $::autofile::files($cmd) for $cmd" | |
return $file | |
} | |
::autofile::proc ::autofile::autoclose {cmd args} { | |
foreach file $::autofile::files($cmd) { | |
puts "closing $file for $cmd" | |
::close $file | |
} | |
} | |
namespace eval ::test { | |
proc hi args { | |
set f [open /dev/urandom] | |
puts [binary encode base64 [read $f 4]] | |
} | |
} | |
::test::hi | |
puts bye |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment