Modules:ClassMethodsClasses:CapturableERB,CreateFile,CreateLink,Directory,EmptyDirectory,InjectIntoFile
Injects the given content into a file. Different from gsub_file, this method is reversible.
Relative path to the destination root
Data to add to the file. Can be given as a block.
give :verbose => false to not log the status and the flag for injection (:after or :before) or :force => true for insert two or more times the same content.
insert_into_file"config/environment.rb","config.gem :thor",:after=>"Rails::Initializer.run do |config|\n"insert_into_file"config/environment.rb",:after=>"Rails::Initializer.run do |config|\n"dogems=ask"Which gems would you like to add?"gems.split(" ").map{|gem|" config.gem :#{gem}"}.join("\n")end
{unchanged_no_flag:"File unchanged! Either the supplied flag value not found or the content has already been inserted!"}
Returns the value of attribute behavior.
:nodoc:.
Wraps an action object and call it accordingly to the thor class behavior.
Append text to a file.
Loads an external file and execute it in the instance binding.
Changes the mode of the given file or directory.
Comment all lines matching a given regex.
Copies the file from the relative source to the relative destination.
Create a new file relative to the destination root with the given data, which is the return value of a block or a data string.
Create a new file relative to the destination root from the given source.
Returns the root for this thor class (also aliased as destination root).
Sets the root for this thor class.
Copies recursively the files from source directory to root directory.
Creates an empty directory.
Receives a file or directory and search for it in the source paths.
Gets the content at the given address and places it at the given relative destination.
Run a regular expression replacement on a file.
Goes to the root and execute the given block.
Extends initializer to add more configuration options.
Injects text right after the class definition.
Injects text right after the module definition.
Do something in the root or on a provided subfolder.
Links the file from the relative source to the relative destination.
Prepend text to a file.
Returns the given path relative to the absolute root (ie, root where the script started).
Removes a file at the given location.
Executes a command returning the contents of the command.
Executes a ruby script (taking into account WIN32 platform quirks).
Holds source paths in instance so they can be manipulated.
Gets an ERB template at the relative source, executes it and makes a copy at the relative destination.
Run a thor command.
Uncomment all lines matching a given regex.
Returns the value of attribute behavior.
101112 | # File 'lib/thor/actions.rb', line 10defbehavior@behaviorend |
:nodoc:
12131415 | # File 'lib/thor/actions.rb', line 12defself.included(base)#:nodoc:super(base)base.extendClassMethodsend |
Wraps an action object and call it accordingly to the thor class behavior.
89909192939495 | # File 'lib/thor/actions.rb', line 89defaction(instance)#:nodoc:ifbehavior==:revokeinstance.revoke!elseinstance.invoke!endend |
Append text to a file. Since it depends on insert_into_file, it’s reversible.
path of the file to be changed
the data to append to the file, can be also given as a block.
give :verbose => false to not log the status.
append_to_file'config/environments/test.rb','config.gem "rspec"'append_to_file'config/environments/test.rb'do'config.gem "rspec"'end
192193194195196 | # File 'lib/thor/actions/file_manipulation.rb', line 192defappend_to_file(path,*args,&block)config=args.last.is_a?(Hash)?args.pop:{}config[:before]=/\z/insert_into_file(path,*(args<<config),&block)end |
Loads an external file and execute it in the instance binding.
The path to the file to execute. Can be a web address or a relative path from the source root.
apply"http://gist.github.com/103208"apply"recipes/jquery.rb"
216217218219220221222223224225226227228229230231232233 | # File 'lib/thor/actions.rb', line 216defapply(path,config={})verbose=config.fetch(:verbose,true)is_uri=path=~%r{^https?\://}path=find_in_source_paths(path)unlessis_urisay_status:apply,path,verboseshell.padding+=1ifverbosecontents=ifis_urirequire"open-uri"URI.open(path,"Accept"=>"application/x-thor-template",&:read)elseFile.open(path,&:read)endinstance_eval(contents,path)shell.padding-=1ifverboseend |
Changes the mode of the given file or directory.
the file mode
the name of the file to change mode
give :verbose => false to not log the status.
chmod"script/server",0755
145146147148149150151152153 | # File 'lib/thor/actions/file_manipulation.rb', line 145defchmod(path,mode,config={})returnunlessbehavior==:invokepath=File.(path,destination_root)say_status:chmod,relative_to_original_destination_root(path),config.fetch(:verbose,true)unless[:pretend]require"fileutils"FileUtils.chmod_R(mode,path)endend |
Comment all lines matching a given regex. It will leave the space which existed before the beginning of the line in tact and will insert a single space after the comment hash.
path of the file to be changed
the regexp or string used to decide which lines to comment
give :verbose => false to not log the status.
comment_lines'config/initializers/session_store.rb',/cookie_store/
308309310311312 | # File 'lib/thor/actions/file_manipulation.rb', line 308defcomment_lines(path,flag,*args)flag=flag.respond_to?(:source)?flag.source:flaggsub_file(path,/^(\s*)([^#\n]*#{flag})/,'\1# \2',*args)end |
Copies the file from the relative source to the relative destination. If the destination is not given it’s assumed to be equal to the source.
the relative path to the source root.
the relative path to the destination root.
give :verbose => false to not log the status, and :mode => :preserve, to preserve the file mode from the source.
copy_file"README","doc/README"copy_file"doc/README"
202122232425262728293031323334 | # File 'lib/thor/actions/file_manipulation.rb', line 20defcopy_file(source,*args,&block)config=args.last.is_a?(Hash)?args.pop:{}destination=args.first||sourcesource=File.(find_in_source_paths(source.to_s))resulting_destination=create_filedestination,nil,configdocontent=File.binread(source)content=yield(content)ifblockcontentendifconfig[:mode]==:preservemode=File.stat(source).modechmod(resulting_destination,mode,config)endend |
Create a new file relative to the destination root with the given data, which is the return value of a block or a data string.
the relative path to the destination root.
the data to append to the file.
give :verbose => false to not log the status.
create_file"lib/fun_party.rb"dohostname=ask("What is the virtual hostname I should use?")"vhost.name = #{hostname}"endcreate_file"config/apache.conf","your apache config"
2223242526 | # File 'lib/thor/actions/create_file.rb', line 22defcreate_file(destination,*args,&block)config=args.last.is_a?(Hash)?args.pop:{}data=args.firstactionCreateFile.new(self,destination,block||data.to_s,config)end |
Create a new file relative to the destination root from the given source.
the relative path to the destination root.
the relative path to the source root.
give :verbose => false to not log the status.
give :symbolic => false for hard link.
create_link"config/apache.conf","/etc/apache.conf"
1718192021 | # File 'lib/thor/actions/create_link.rb', line 17defcreate_link(destination,*args)config=args.last.is_a?(Hash)?args.pop:{}source=args.firstactionCreateLink.new(self,destination,source,config)end |
Returns the root for this thor class (also aliased as destination root).
99100101 | # File 'lib/thor/actions.rb', line 99defdestination_root@destination_stack.lastend |
Sets the root for this thor class. Relatives path are added to the directory where the script was invoked and expanded.
106107108109 | # File 'lib/thor/actions.rb', line 106defdestination_root=(root)@destination_stack||=[]@destination_stack[0]=File.(root||"")end |
Copies recursively the files from source directory to root directory. If any of the files finishes with .tt, it’s considered to be a template and is placed in the destination without the extension .tt. If any empty directory is found, it’s copied and all .empty_directory files are ignored. If any file name is wrapped within % signs, the text within the % signs will be executed as a method and replaced with the returned value. Let’s suppose a doc directory with the following files:
doc/components/.empty_directoryREADMErdoc.rb.ttapp_name%.rb
When invoked as:
directory"doc"
It will create a doc directory in the destination with the following files (assuming that the ‘app_name` method returns the value “blog”):
doc/components/READMErdoc.rbblog.rb
Encoded path note: Since Thor internals use Object#respond_to? to check if it can expand %something%, this ‘something` should be a public method in the class calling #directory. If a method is private, Thor stack raises PrivateMethodEncodedError.
the relative path to the source root.
the relative path to the destination root.
give :verbose => false to not log the status. If :recursive => false, does not look for paths recursively. If :mode => :preserve, preserve the file mode from the source. If :exclude_pattern => /regexp/, prevents copying files that match that regexp.
directory"doc"directory"doc","docs",:recursive=>false
4950515253 | # File 'lib/thor/actions/directory.rb', line 49defdirectory(source,*args,&block)config=args.last.is_a?(Hash)?args.pop:{}destination=args.first||sourceactionDirectory.new(self,source,destination||source,config,&block)end |
Creates an empty directory.
the relative path to the destination root.
give :verbose => false to not log the status.
empty_directory"doc"
131415 | # File 'lib/thor/actions/empty_directory.rb', line 13defempty_directory(destination,config={})actionEmptyDirectory.new(self,destination,config)end |
Receives a file or directory and search for it in the source paths.
Raises:
133134135136137138139140141142143144145146147148149150151152153154155156157 | # File 'lib/thor/actions.rb', line 133deffind_in_source_paths(file)possible_files=[file,file+TEMPLATE_EXTNAME]relative_root=relative_to_original_destination_root(destination_root,false)source_paths.eachdo|source|possible_files.eachdo|f|source_file=File.(f,File.join(source,relative_root))returnsource_fileifFile.exist?(source_file)endend="Could not find #{file.inspect} in any of your source paths. ".dupunlessself.class.source_root<<"Please invoke #{self.class.name}.source_root(PATH) with the PATH containing your templates. "end<<ifsource_paths.empty?"Currently you have no source paths."else"Your current source paths are: \n#{source_paths.join("\n")}"endraiseError,end |
Gets the content at the given address and places it at the given relative destination. If a block is given instead of destination, the content of the url is yielded and used as location.
get
relies on open-uri, so passing application user input would provide a command injection attack vector.
the address of the given content.
the relative path to the destination root.
give :verbose => false to not log the status, and :http_headers => <Hash> to add headers to an http request.
get"http://gist.github.com/103208","doc/README"get"http://gist.github.com/103208","doc/README",:http_headers=>{"Content-Type"=>"application/json"}get"http://gist.github.com/103208"do|content|content.split("\n").firstend
81828384858687888990919293949596979899100 | # File 'lib/thor/actions/file_manipulation.rb', line 81defget(source,*args,&block)config=args.last.is_a?(Hash)?args.pop:{}destination=args.firstrender=ifsource=~%r{^https?\://}require"open-uri"URI.send(:open,source,config.fetch(:http_headers,{})){|input|input.binmode.read}elsesource=File.(find_in_source_paths(source.to_s))File.open(source){|input|input.binmode.read}enddestination||=ifblock_given?block.arity==1?yield(render):yieldelseFile.basename(source)endcreate_filedestination,render,configend |
Run a regular expression replacement on a file.
path of the file to be changed
the regexp or string to be replaced
the replacement, can be also given as a block
give :verbose => false to not log the status, and :force => true, to force the replacement regardless of runner behavior.
gsub_file'app/controllers/application_controller.rb',/#\s*(filter_parameter_logging :password)/,'\1'gsub_file'README',/rake/,:greendo|match|match<<" no more. Use thor!"end
262263264265266267268269270271272273274275 | # File 'lib/thor/actions/file_manipulation.rb', line 262defgsub_file(path,flag,*args,&block)config=args.last.is_a?(Hash)?args.pop:{}returnunlessbehavior==:invoke||config.fetch(:force,false)path=File.(path,destination_root)say_status:gsub,relative_to_original_destination_root(path),config.fetch(:verbose,true)unless[:pretend]content=File.binread(path)content.gsub!(flag,*args,&block)File.open(path,"wb"){|file|file.write(content)}endend |
Goes to the root and execute the given block.
200201202 | # File 'lib/thor/actions.rb', line 200defin_rootinside(@destination_stack.first){yield}end |
Extends initializer to add more configuration options.
The actions default behavior. Can be :invoke or :revoke. It also accepts :force, :skip and :pretend to set the behavior and the respective option.
The root directory needed for some actions.
7273747576777879808182838485 | # File 'lib/thor/actions.rb', line 72definitialize(args=[],={},config={})self.behavior=caseconfig[:behavior].to_swhen"force","skip"(,config[:behavior]):invokewhen"revoke":revokeelse:invokeendsuperself.destination_root=config[:destination_root]end |
Injects text right after the class definition. Since it depends on insert_into_file, it’s reversible.
path of the file to be changed
the class to be manipulated
the data to append to the class, can be also given as a block.
give :verbose => false to not log the status.
inject_into_class"app/controllers/application_controller.rb","ApplicationController"," filter_parameter :password\n"inject_into_class"app/controllers/application_controller.rb","ApplicationController"do" filter_parameter :password\n"end
216217218219220 | # File 'lib/thor/actions/file_manipulation.rb', line 216definject_into_class(path,klass,*args,&block)config=args.last.is_a?(Hash)?args.pop:{}config[:after]=/class #{klass}\n|class #{klass} .*\n/insert_into_file(path,*(args<<config),&block)end |
Injects text right after the module definition. Since it depends on insert_into_file, it’s reversible.
path of the file to be changed
the module to be manipulated
the data to append to the class, can be also given as a block.
give :verbose => false to not log the status.
inject_into_module"app/helpers/application_helper.rb","ApplicationHelper"," def help; 'help'; end\n"inject_into_module"app/helpers/application_helper.rb","ApplicationHelper"do" def help; 'help'; end\n"end
239240241242243 | # File 'lib/thor/actions/file_manipulation.rb', line 239definject_into_module(path,module_name,*args,&block)config=args.last.is_a?(Hash)?args.pop:{}config[:after]=/module #{module_name}\n|module #{module_name} .*\n/insert_into_file(path,*(args<<config),&block)end |
2627282930313233 | # File 'lib/thor/actions/inject_into_file.rb', line 26definsert_into_file(destination,*args,&block)data=block_given??block:args.shiftconfig=args.shift||{}config[:after]=/\z/unlessconfig.key?(:before)||config.key?(:after)actionInjectIntoFile.new(self,destination,data,config)end |
Do something in the root or on a provided subfolder. If a relative path is given it’s referenced from the current root. The full path is yielded to the block you provide. The path is set back to the previous path when the method exits.
Returns the value yielded by the block.
the directory to move to.
give :verbose => true to log and use padding.
170171172173174175176177178179180181182183184185186187188189190191192193194195196 | # File 'lib/thor/actions.rb', line 170definside(dir="",config={},&block)verbose=config.fetch(:verbose,false)pretend=[:pretend]say_status:inside,dir,verboseshell.padding+=1ifverbose@destination_stack.pushFile.(dir,destination_root)# If the directory doesn't exist and we're not pretendingif!File.exist?(destination_root)&&!pretendrequire"fileutils"FileUtils.mkdir_p(destination_root)endresult=nilifpretend# In pretend mode, just yield down to the blockresult=block.arity==1?yield(destination_root):yieldelserequire"fileutils"FileUtils.cd(destination_root){result=block.arity==1?yield(destination_root):yield}end@destination_stack.popshell.padding-=1ifverboseresultend |
Links the file from the relative source to the relative destination. If the destination is not given it’s assumed to be equal to the source.
the relative path to the source root.
the relative path to the destination root.
give :verbose => false to not log the status.
link_file"README","doc/README"link_file"doc/README"
50515253545556 | # File 'lib/thor/actions/file_manipulation.rb', line 50deflink_file(source,*args)config=args.last.is_a?(Hash)?args.pop:{}destination=args.first||sourcesource=File.(find_in_source_paths(source.to_s))create_linkdestination,source,configend |
Prepend text to a file. Since it depends on insert_into_file, it’s reversible.
path of the file to be changed
the data to prepend to the file, can be also given as a block.
give :verbose => false to not log the status.
prepend_to_file'config/environments/test.rb','config.gem "rspec"'prepend_to_file'config/environments/test.rb'do'config.gem "rspec"'end
170171172173174 | # File 'lib/thor/actions/file_manipulation.rb', line 170defprepend_to_file(path,*args,&block)config=args.last.is_a?(Hash)?args.pop:{}config[:after]=/\A/insert_into_file(path,*(args<<config),&block)end |
Returns the given path relative to the absolute root (ie, root where the script started).
114115116117118119120121122123 | # File 'lib/thor/actions.rb', line 114defrelative_to_original_destination_root(path,remove_dot=true)root=@destination_stack[0]ifpath.start_with?(root)&&[File::SEPARATOR,File::ALT_SEPARATOR,nil,""].include?(path[root.size..root.size])path=path.duppath[0...root.size]="."remove_dot?(path[2..-1]||""):pathelsepathendend |
Removes a file at the given location.
path of the file to be changed
give :verbose => false to not log the status.
remove_file'README'remove_file'app/controllers/application_controller.rb'
325326327328329330331332333334 | # File 'lib/thor/actions/file_manipulation.rb', line 325defremove_file(path,config={})returnunlessbehavior==:invokepath=File.(path,destination_root)say_status:remove,relative_to_original_destination_root(path),config.fetch(:verbose,true)if![:pretend]&&(File.exist?(path)||File.symlink?(path))require"fileutils"::FileUtils.rm_rf(path)endend |
Executes a command returning the contents of the command.
the command to be executed.
give :verbose => false to not log the status, :capture => true to hide to output. Specify :with to append an executable to command execution.
inside('vendor')dorun('ln -s ~/edge rails')end
248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277 | # File 'lib/thor/actions.rb', line 248defrun(command,config={})returnunlessbehavior==:invokedestination=relative_to_original_destination_root(destination_root,false)desc="#{command} from #{destination.inspect}"ifconfig[:with]desc="#{File.basename(config[:with].to_s)} #{desc}"command="#{config[:with]} #{command}"endsay_status:run,desc,config.fetch(:verbose,true)returnif[:pretend]env_splat=[config[:env]]ifconfig[:env]ifconfig[:capture]require"open3"result,status=Open3.capture2e(*env_splat,command.to_s)success=status.success?elseresult=system(*env_splat,command.to_s)success=resultendabortif!success&&config.fetch(:abort_on_failure,self.class.exit_on_failure?)resultend |
Executes a ruby script (taking into account WIN32 platform quirks).
the command to be executed.
give :verbose => false to not log the status.
285286287288 | # File 'lib/thor/actions.rb', line 285defrun_ruby_script(command,config={})returnunlessbehavior==:invokeruncommand,config.merge(with:Thor::Util.ruby_command)end |
Holds source paths in instance so they can be manipulated.
127128129 | # File 'lib/thor/actions.rb', line 127defsource_paths@source_paths||=self.class.source_paths_for_searchend |
Gets an ERB template at the relative source, executes it and makes a copy at the relative destination. If the destination is not given it’s assumed to be equal to the source removing .tt from the filename.
the relative path to the source root.
the relative path to the destination root.
give :verbose => false to not log the status.
template"README","doc/README"template"doc/README"
117118119120121122123124125126127128129130131132 | # File 'lib/thor/actions/file_manipulation.rb', line 117deftemplate(source,*args,&block)config=args.last.is_a?(Hash)?args.pop:{}destination=args.first||source.sub(/#{TEMPLATE_EXTNAME}$/,"")source=File.(find_in_source_paths(source.to_s))context=config.delete(:context)||instance_eval("binding")create_filedestination,nil,configdocapturable_erb=CapturableERB.new(::File.binread(source),trim_mode:"-",eoutvar:"@output_buffer")content=capturable_erb.tapdo|erb|erb.filename=sourceend.result(context)content=yield(content)ifblockcontentendend |
Run a thor command. A hash of options can be given and it’s converted to switches.
the command to be invoked
arguments to the command
give :verbose => false to not log the status, :capture => true to hide to output. Other options are given as parameter to Thor.
thor:install,"http://gist.github.com/103208"#=> thor install http://gist.github.com/103208thor:list,:all=>true,:substring=>'rails'#=> thor list --all --substring=rails
308309310311312313314315316317318319 | # File 'lib/thor/actions.rb', line 308defthor(command,*args)config=args.last.is_a?(Hash)?args.pop:{}verbose=config.key?(:verbose)?config.delete(:verbose):truepretend=config.key?(:pretend)?config.delete(:pretend):falsecapture=config.key?(:capture)?config.delete(:capture):falseargs.unshift(command)args.pushThor::Options.to_switches(config)command=args.join(" ").stripruncommand,with::thor,verbose:verbose,pretend:pretend,capture:captureend |
Uncomment all lines matching a given regex. Preserves indentation before the comment hash and removes the hash and any immediate following space.
path of the file to be changed
the regexp or string used to decide which lines to uncomment
give :verbose => false to not log the status.
uncomment_lines'config/initializers/session_store.rb',/active_record/
289290291292293 | # File 'lib/thor/actions/file_manipulation.rb', line 289defuncomment_lines(path,flag,*args)flag=flag.respond_to?(:source)?flag.source:flaggsub_file(path,/^(\s*)#[[:blank:]]?(.*#{flag})/,'\1\2',*args)end |