Trying to loop over several files execute a command on each file and concat the output to same str variable

Viewed 98

flake8_errs is the variable initialized to empty string ('').

Trying to concat the output of the command

flake8 --config=$(CI_DIR)/lint-configs/python/.flake8 $$py_file;

on each .py file to flake8_errs variable.

Then check if flake8_errs has some content and raise an err.

This is what I tried so far:

flake8_errs =''
.PHONY: .flake8
.flake8:
    . $(VIRTUALENV_DIR)/bin/activate; \
    if [ "$${FORCE_CHECK_ALL_FILES}" = "true" ]; then \
        find ./* -name "*.py" | while read py_file; do \
            flake8_errs += flake8 --config=$(CI_DIR)/lint-configs/python/.flake8 $$py_file; \
        done; \
    else \
        echo "No files have changed, skipping run..."; \
    fi;
    if [ ! -z "${flake8_errs}" ]; then \
        exit 1; \
    fi;
1 Answers

You can't use make functions in a recipe, and you can't assign to make variables in a recipe. Recipes are fully expanded once so all make constructs are resolved, then the shell is invoked and given the results of that expansion, then make waits for the shell to finish to determine whether it worked.

You can't "intersperse" shell and makefile content, where the shell would have to run some things, then make constructs would be expanded, then the shell would run more things, etc.

You should write the entire rule using ONLY shell constructs:

.PHONY: .flake8
.flake8:
        . $(VIRTUALENV_DIR)/bin/activate; \
        files='$(CHANGED_PY)'; \
        if [ '$(FORCE_CHECK_ALL_FILES)' = true ]; then \
            files="$$(find ./* -name "*.py")"; \
        fi; \
        if [ -z "$$files" ]; then \
            echo "No files have changed, skipping run..."; \
            exit 0; \
        fi; \
        errors=; \
        for file in $$files; do \
            if [ -n "$$file" ]; then \
                errors="$$errors $$(flake8 --config=$(CI_DIR)/lint-configs/python/.flake8 $$file)"; \
            fi; \
        done; \
        if [ -n "$$errors" ]; then \
           echo "got errors: $$errors"; \
           exit 1; \
        fi;
Related