# Makefile 經驗分享
@mileschou
---
## 這是一個建置工具
---
## 簡單的格式
    
```makefile
foo.txt:
	echo "foo" > foo.txt
bar.txt:
	echo "bar" > bar.txt
```
----
```bash
make foo.txt
make bar.txt
```
---
## 應用實例
    
```makefile
build:  
	docker build -t=seagon .  
shell:  
	docker run --rm -it seagon sh
run:  
	docker run --rm -it -p 8000:80 seagon
```
---
## 試試看?
    
```bash
touch build
make build
```
---
## PHONY 用法 1
    
```makefile
.PHONY: build
build:
	docker build -t=seagon .
```
---
## PHONY 用法 2
    
```makefile
SLEEP = 1 2 3 4 5
go:
	@for sec in $(SLEEP); do \
    	echo $$sec; \
	done
```
----
## PHONY 用法 2
    
```makefile
SLEEP = 1 2 3 4 5
.PHONY: go $(SLEEP)
go: $(SLEEP)
$(SLEEP):
	@sleep $@ && echo $@
```
PS:文件有提到定義 PHONY 有助於效能提升
---
## 依賴的表達方式與應用
    
```makefile
test: vendor
	php vendor/bin/phpunit
vendor: composer.phar
	php composer.phar install
composer.phar:
	curl -sS https://getcomposer.org/installer | php
```
----
``` bash
make test
```
----
```makefile
test: .env
	php vendor/bin/phpunit
.env: vendor
	cp .env.example .env
	php artisan key:generate
vendor: composer.phar
	php composer.phar install
composer.phar:
	curl -sS https://getcomposer.org/installer | php
```
---
## 變數應用 1
    
```makefile
ENV := dev
STACK :=
sso:
	aws sso --profile ${ENV} login AWS_PROFILE=${ENV}
deploy:
	cdk deploy --profile ${ENV} --context ENV=${ENV} ${STACK}
```
----
```bash
make sso
make sso ENV=prod
make deploy ENV=prod
make deploy ENV=prod STACK=AuthStack
```
---
## 變數應用 2
    
```makefile
IMAGE := $(shell basename $(shell pwd))
VERSION := latest
build:
	docker build -t=$(IMAGE):$(VERSION) .
```
---
## 變數應用 3
    
```makefile
IMAGE := $(shell basename $(shell pwd))
COMPOSER_PATH := $(shell which composer)
ifdef COMPOSER_PATH
	GITHUB_TOKEN := $(shell composer config -g github-oauth.github.com)
endif
image:
ifdef GITHUB_TOKEN
	docker build --tag=$(IMAGE) --build-arg GITHUB_TOKEN=${GITHUB_TOKEN} .
else
	@echo ">>> Please pass the env var";
	@exit 1
endif
```
---
## 完整應用範例
---
## 參考資料
- [官方網站](https://www.gnu.org/software/make/manual/html_node/)
             
            {"metaMigratedAt":"2023-06-16T20:13:06.012Z","metaMigratedFrom":"YAML","title":"#15 - Makefile 經驗分享","breaks":true,"contributors":"[{\"id\":\"208766f2-1253-4ddc-b70a-16e6fba73e62\",\"add\":2391,\"del\":223}]"}