makefile

Makefile: Generating zip files of all sub folders


I'm trying to transition away from my ad-hoc build script, which iterates over all children of the project's home, and creates a corresponding zip file for each:

for i in */; do
    if [[ -d $i ]]; then
        echo "Processing folder $i";
        zip "${i%/}.zip" "$i"*.txt
        echo "Created ${i%/}.zip"
    fi
done;

The first line is clunky, but it's just iterating through all subdirs excluding hidden ones. As you can see the logic is straightforward, but doing this in a Makefile without explicitly specifying each subdirectory seems difficult.

Ideally we should start with:

project
  subdir1
    file1.txt
    file2.txt
  subdir2
    file3.txt

...and end up with:

project
  subdir1
    file1.txt
    file2.txt
  subdir1.zip
  subdir2
    file3.txt
  subdir2.zip

Is there a way to safely get this sort of recursion out of make?

edit: Cleaned up base script, thanks Etan


Solution

  • Something like this might do what you want.

    SUBDIRS := $(wildcard */)
    ZIPS := $(addsuffix .zip,$(subst /,,$(SUBDIRS)))
    
    $(ZIPS) : %.zip : | %
        zip $@ $*/*.txt
    
    dist: $(ZIPS)
    

    You might need to adjust the prerequisites on that static pattern rule, etc. to get the correct rebuilding behavior (should make detect when it needs to rebuild, should it always rebuild, should it never rebuild when the .zip file exists, etc).