Cleaning Up Generated Files

Credit: Stefan Lang

Problem

You want to clean up files that aren actually part of your project: generated files, backup files, and so on.

Solution

Within your Rakefile, require the rake/clean library to get access to the clean and clobber tasks. Put glob patterns for all your generated files in the CLOBBER FileList. Put glob patterns for all other scratch files in the CLEAN FileList.

By default, CLEAN also includes the patterns **/*~, **/*.bak, and **/core. Heres a typical set of CLOBBER and CLEAN files:

require rake/clean # Include the "pkg" and "doc" directories and their contents. # Include all files ending in ".o" in the current directory # and its subdirectories (recursively). CLOBBER.include(pkg, doc, **/*.o) # Include InstalledFiles and .config: files created by setup.rb. # Include temporary files created during test run. CLEAN.include(InstalledFiles, .config, est/**/*.tmp)

Run rake clean to remove all files specified by the CLEAN filelist, and rake clobber to remove the files specified by both file lists.

Discussion

The rake/clean library initializes the constants CLEAN and CLOBBER to new Rake:: FileList instances. It also defines the tasks clean and clobber, making clean a prerequisite of clobber. The idea is that rake clean removes any files that might need to be recreated once your program changes, while rake clobber returns your source tree to a completely pristine state.

Other Rake libraries define cleanup tasks that remove certain products of their main tasks. An example: the packaging libraries create a task called clobber_package, and make it a prerequisite of clobber. Running rake clobber on such a project removes the package files: you don have to explicitly include them in your CLOBBER list.

You can do the same thing for your own tasks: rather than manipulate CLEAN and CLOBBER, you can create a custom cleanup task and make it a prerequisite of clean or clobber. The following code is a different way of making sure that rake clobber removes any precompiled object files:

desc Remove all object files. task clobber_objects do rm_f FileList[**/*.o] end # Make clobber_objects a prerequisite of the preexisting clobber task task clobber => clobber_objects

Now you can run rake clobber_objects to remove all object files, and rake clobber to remove all other unwanted files as well.

See Also

Категории