Project

General

Profile

1
##### Configuration
2

    
3
# Command line
4
log ?= $(if $(test),,1)
5
profile ?=
6
reverify ?= 1
7
debug ?=
8

    
9
# Makefile
10
tablesSort ?= plots organisms stems specimens
11
exts ?= csv tsv txt xml
12
test_n ?= 2
13

    
14
##### Vars/functions
15

    
16
selfDir_uZPPqC := $(dir $(lastword $(MAKEFILE_LIST)))
17

    
18
# Paths
19
datasrc := $(notdir $(realpath .))
20
root := $(selfDir_uZPPqC)..
21
bin := $(root)/bin
22
mappings := $(root)/mappings
23

    
24
# Make
25
SHELL := /bin/bash
26
selfMake = $(MAKE) --makefile=../input.Makefile
27
subMake = $(MAKE) $(@:$(root)/%=%) --directory=$(root)
28
+_ = $(+:_%=)
29
addBeforeExt = $(basename $(2))$(1)$(suffix $(2))
30

    
31
# OS
32
os := $(shell uname)
33
forOs = $(patsubst %,%-$(filter Linux Darwin,$(os)),$(1))
34

    
35
# Formatting
36
SED = sed -$(if $(filter Darwin,$(os)),E,r)
37

    
38
# System
39
date = $(shell date +"%Y-%m-%d-%H-%M-%S")
40

    
41
# Terminal
42
termCols := $(shell tput cols)
43
esc := '['
44
reset := $(esc)'0m'
45
emph := $(esc)'7m '
46
endEmph := ' '$(reset)
47

    
48
# Commands
49
MKDIR = mkdir -p
50
mkdir = $(MKDIR) $(@D)
51
CP = cp -p
52
diff = diff --unified=2
53
diffVerbose = $(if $(verbose),diff --side-by-side --left-column\
54
--width=$(termCols),$(diff))
55

    
56
# BIEN commands
57
selfMap = $(bin)/cols 0 0
58
psqlOpts := --set ON_ERROR_STOP=1 --quiet
59
psqlAsBien := $(bin)/psql_vegbien $(psqlOpts)
60

    
61
# SVN
62
addDir = $(if $(wildcard $(1)/),svn add --depth=empty $(1),svn mkdir $(1))
63
setSvnIgnore = svn propset svn:ignore $(2) $(1)
64
define addDirWithIgnore
65
$(addDir)
66
$(setSvnIgnore)
67
endef
68

    
69
##### General targets
70

    
71
all: _always maps ;
72

    
73
.SUFFIXES: # turn off built-in suffix rules
74
.SECONDARY: # don't automatically delete intermediate files
75
.DELETE_ON_ERROR: # delete target if recipe fails
76

    
77
_always:
78
.PHONY: _always
79

    
80
clean: _always
81
	$(RM) $(all)
82

    
83
remake: _always clean
84
	+$(selfMake)
85
# re-run make so that cache of existing files is reset
86

    
87
make_script = ./$< >$@
88

    
89
%/: % _always ;
90

    
91
# Must come before `%: %.make` to override it
92
src/%: src/%.make _always
93
	(set -x; $(make_script)) 2>>$<.log
94
.PRECIOUS: src/% # save partial outputs of aborted src make scripts
95

    
96
%: %.make _always
97
	$(make_script)
98

    
99
##### SVN
100

    
101
add: _always
102
	$(call setSvnIgnore,.,$$'')
103
	$(call addDirWithIgnore,src,$$'*')
104
	$(call addDirWithIgnore,maps,$$'.~*')
105
	$(call addDirWithIgnore,import,$$'*')
106
	$(call addDirWithIgnore,test,$$'*.out\n*.xml')
107
	$(call addDirWithIgnore,verify,$$'*.out')
108

    
109
##### Sources
110

    
111
inputFiles := $(wildcard $(exts:%=src/*.%))
112
ifeq ($(inputFiles),)
113
dbExport := $(firstword $(wildcard src/db.*.sql))
114
endif
115

    
116
srcs = $(shell $(bin)/sort_filenames $(wildcard $(exts:%=src/*.$*.%)))
117
isCsv = $(if $(srcs),$(if $(filter %.xml,$(srcs)),,1))
118
    # true if $(srcs) non-empty and contains no *.xml
119
catSrcs = $(bin)/cat$(if $(isCsv),_csv) $(srcs)
120
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
121

    
122
# Usage: `make {--silent|-s} cat` (removes echoed make commands)
123
cat: $(addprefix cat-,$(tables)) _always ;
124

    
125
cat-%: _always
126
	$(catSrcs)
127

    
128
##### Existing maps discovery
129

    
130
srcMap := maps/src.%.csv
131
fullViaMap := maps/%.full.csv
132
directMap := maps/VegBIEN.%.csv
133
allViaMaps := $(filter-out $(srcMap) $(fullViaMap) $(directMap),\
134
$(wildcard maps/*.csv))
135
via := $(firstword $(sort $(basename $(basename $(notdir $(allViaMaps))))))
136

    
137
coreMap := $(mappings)/$(via)-VegBIEN.%.csv
138
coreSelfMap := $(mappings)/$(via).self.%.csv
139

    
140
viaMaps := $(wildcard $(tablesSort:%=maps/$(via).%.csv))
141
viaMaps += $(filter-out $(viaMaps) $(fullViaMap),$(wildcard maps/$(via).*.csv))
142

    
143
autogenMaps := $(subst $(via).,VegBIEN.,$(viaMaps))
144
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
145
$(wildcard maps/VegBIEN.*.csv))
146
tables := $(directMaps:maps/VegBIEN.%.csv=%)
147

    
148
##### Installation
149

    
150
install: _always src/install import/install ;
151

    
152
uninstall: _always import/uninstall src/uninstall ;
153

    
154
reinstall: _always uninstall install ;
155

    
156
##### Staging tables
157

    
158
import/install: _always import/schema $(addprefix import/install-,$(tables)) ;
159

    
160
import/uninstall: _always import/rm_schema ;
161
# rm_schema will also drop all staging tables
162

    
163
import/schema: _always
164
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
165
# ignore errors if schema exists
166

    
167
import/rm_schema: _always
168
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
169

    
170
import/install-%: _always
171
	$(if $(isCsv),$(import_install_))
172
import_install_ = (prefix=; . $(bin)/vegbien_dest; "time" env schema=$(datasrc)\
173
table=$* $(bin)/csv2db $(catSrcs)$(if $(log), &>import/install.log))
174

    
175
##### Maps building
176

    
177
# Maps to (try to) build are added to one of these
178
maps :=
179
createOnlyMaps :=
180

    
181
srcMaps := $(wildcard maps/src.*.csv)
182

    
183
mkSrcMap = $(catSrcs)|env datasrc=$(datasrc) $(bin)/src_map >$@
184

    
185
# Autogen src maps with known table names
186
maps/src.%.csv: # no prereqs so only built if doesn't exist
187
	$(if $(isCsv),$(mkSrcMap))
188
# only build if CSV srcs exist for that table name
189
# Try all table names
190
createOnlyMaps += $(tablesSort:%=maps/src.%.csv)
191

    
192
# Must come before $(root)/% to override it
193
$(coreSelfMap): _always
194
	-+$(subMake)
195
# ignore errors if $(coreSelfMap) does not exist
196

    
197
# Via maps cleanup
198
ifneq ($(filter maps/.%.last_cleanup,$(MAKECMDGOALS)),)
199
maps/.$(via).%.csv.last_cleanup: maps/$(via).%.csv $(coreMap)
200
	$(bin)/in_place $< env ignore=1 $(bin)/subtract $(word 2,$+) 0 1
201
	touch $@
202
else
203
$(viaMaps): _always
204
	$(selfMake) $(@:maps/%=maps/.%.last_cleanup)
205
endif
206

    
207
joinSrcMap = $(if $(wildcard maps/src.$*.csv),$(bin)/in_place $@\
208
$(bin)/intersect maps/src.$*.csv 0)
209

    
210
makeFullCsv = $(if $(shell test -e $(word 2,$+) && echo t),\
211
env ignore=1 $(bin)/union <$+|,<$< )$(bin)/sort_map >$@
212
# can't use $(wildcard) because it won't recheck file after $(coreSelfMap) runs
213

    
214
maps/$(via).%.full.csv: maps/$(via).%.csv $(coreSelfMap)
215
	$(makeFullCsv)
216
	$(joinSrcMap)
217
maps += $(patsubst maps/%.csv,maps/%.full.csv,$(viaMaps))
218

    
219
maps/VegBIEN.%.csv: maps/$(via).%.full.csv $(coreMap)
220
	$(bin)/join <$+|$(bin)/sort_map >$@
221
maps += $(autogenMaps)
222

    
223
maps: $(createOnlyMaps) $(maps) _always ;
224

    
225
all += $(maps)
226

    
227
##### Maps validation
228

    
229
missing_mappings: _always missing_join_mappings missing_input_mappings ;
230

    
231
missing_%_mappings: _always # stem is one of join|input
232
	@echo $(emph)"Missing $* mappings:"$(endEmph)
233
	@+$(selfMake) remake 2>&1\
234
|$(SED) -n 's/^.*No.* $* mapping for ([0-9A-Za-z_-]+).*$$/\1/p'\
235
$(if $(filter join,$*),|$(bin)/ucase_first 0)|sort|uniq
236

    
237
##### External dependencies
238

    
239
$(root)/%: _always
240
	+$(subMake)
241
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
242

    
243
##### Mapping
244

    
245
+maps = $(filter maps/% $(mappings)/%,$(+_))
246
<in = $(firstword $(filter-out $(+maps),$(+_)))
247
map = $(if $(<in),<$(<in),\
248
$(if $(srcs),$(withCatSrcs),\
249
$(if $(mapEnv),env $(mapEnv),\
250
$(error No input file src/*.$*.{$(exts)}))))\
251
$(root)/map $(+maps)
252
map2db = env out_database=vegbien $(map)
253

    
254
##### Import to VegBIEN
255

    
256
ifneq ($(dbExport)$(inputFiles),)
257

    
258
profileTest = $(if $(profile),$(if $(test),1))
259
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
260
$(bin)/profile_stats /dev/fd/0
261

    
262
log_ = import/$*$(if $(n),.n=$(n),).$(date).log
263
trace = $(log_:.log=.trace)
264
import = -$(if $(profileTest),$(profileOnly),(set -x; "time" env commit=1\
265
$(if $(profile),profile_to=$(trace)) $(map2db)) $(if $(log),\
266
$(if $(n),,>>$(log_))) 2>&1$(if $(log),$(if $(n),|tee -a $(log_))))
267
# don't abort on import errors, which often relate to invalid input data
268

    
269
import: $(addprefix import-,$(tables)) _always ;
270

    
271
import-%: maps/VegBIEN.%.csv _always
272
	$(import)
273
# default:
274
import-%: _always ;
275

    
276
else
277
import: _always ;
278
endif
279

    
280
##### Log files from import
281

    
282
logs := $(wildcard import/*.log import/*.trace)
283

    
284
rm_logs: _always
285
	$(RM) $(logs)
286

    
287
##### Verification of import
288

    
289
verify: $(addprefix verify-,$(tables)) _always ;
290

    
291
verify-%: verify/%.ref verify/%.out _always
292
	-$(diffVerbose) $(+_)
293
# don't abort on verification errors, which are expected during development
294
# default:
295
verify-%: verify/%.out _always
296
	$(if $(shell test -e $< && echo t),cat $<)
297
# don't run if verify/%.out's default do-nothing action was used
298
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
299

    
300
verify = $(if $(reverify),"time" $(psqlAsBien) --set=datasource="'$(datasrc)'"\
301
--no-align --field-separator=$$'\t' --pset=footer=off --pset=null=NULL <$< >$@)
302

    
303
verify/%.out: $(mappings)/verify.%.sql _always
304
	$(verify)
305
# default:
306
verify/%.out: _always ;
307

    
308
all += $(wildcard verify/*.out)
309

    
310
ifneq ($(dbExport),)
311
%.ref: %.ref.sql
312
	$(dbAsBien) $(db) <$< >$@
313
endif
314

    
315
##### Editing import
316

    
317
import/rotate: _always
318
	echo "UPDATE party SET organizationname = organizationname||'.$(date)'\
319
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
320

    
321
import/rm: _always
322
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
323
$(psqlAsBien)
324

    
325
##### Testing
326

    
327
hasOwnRef = $(filter-out %.2-step.xml,$@)
328
testRef = $(1:.2-step.xml=.xml).ref
329

    
330
define runTest
331
@echo "Testing $(abspath $@)..."
332
>$@ env test=1 n=$(test_n) $(1)
333
@(set -x; $(diff) $(call testRef,$@) $@) 2>&1 || { e=$$?;\
334
$(if $(wildcard $(call testRef,$@)),,cat $@;)\
335
$(if $(hasOwnRef),\
336
echo $(emph)"To accept new test output:"$(endEmph);\
337
echo "$(MAKE) $@-ok --directory=$(realpath .) --makefile=../input.Makefile";\
338
,\
339
echo $(emph)"Note: The preceding failed test is compared to another test's\
340
output"$(endEmph);\
341
echo $(emph)"When it fails, this always indicates a bug"$(endEmph);\
342
)\
343
exit $$e;}
344
endef
345

    
346
test2File = $(call runTest,$(map))
347

    
348
tests :=
349

    
350
test/$(via).%.xml: maps/$(via).%.full.csv _always
351
	$(test2File)
352
tests += test/$(via).%.xml
353

    
354
test/VegBIEN.%.xml: maps/VegBIEN.%.csv _always
355
	$(test2File)
356
tests += test/VegBIEN.%.xml
357

    
358
test/VegBIEN.%.2-step.xml: test/$(via).%.xml $(coreMap) _always
359
	-$(test2File)
360
# Don't abort tester if only 2-step test fails, as it's often finicky
361
tests += test/VegBIEN.%.2-step.xml
362

    
363
test/import.%.out: maps/VegBIEN.%.csv _always
364
	$(call runTest,$(map2db))
365
tests += test/import.%.out
366

    
367
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
368

    
369
.PRECIOUS: $(testOutputs) # save outputs of failed tests so they can be accepted
370

    
371
test: _always $(testOutputs) ;
372

    
373
all += $(testOutputs)
374

    
375
# Accepts a test output: make <test_output_path>-ok
376
%-ok: _always
377
	$(CP) $* $(call testRef,$*)
378

    
379
##### Input-type-specific
380

    
381
# Each input type needs var $(mapEnv) and targets src/install, src/uninstall
382

    
383
#### DB export
384

    
385
ifneq ($(dbExport),)
386

    
387
dbEngineExt := $(subst .,,$(suffix $(basename $(notdir $(dbExport)))))
388
db := $(datasrc)
389

    
390
### Installation
391

    
392
src/install: _always db ;
393

    
394
src/uninstall: _always rm_db ;
395

    
396
### DB-engine-specific
397

    
398
# Each DB engine needs vars $(dbEngine), $(dbAsBien) and targets db, rm_db
399

    
400
ifeq ($(dbEngineExt),my)
401

    
402
dbEngine := MySQL
403

    
404
bienPassword := $(shell cat $(root)/config/bien_password)
405
mysqlAs = mysql --user=$(1) --password='$(bienPassword)'
406
mysqlAsRoot := $(call mysqlAs,root)
407
dbAsBien := $(call mysqlAs,bien)
408

    
409
dbExists = $(shell echo "SHOW DATABASES LIKE '$(db)';"|$(mysqlAsRoot))
410

    
411
define createDb
412
echo "CREATE DATABASE $(db) DEFAULT CHARACTER SET latin1;"|$(mysqlAsRoot)
413
-$(mysqlAsRoot) --database=$(db) <$<
414
endef
415
# ignore errors in db import so that GRANT will still be run
416

    
417
db: $(dbExport) _always
418
	$(if $(dbExists),,$(createDb))
419
	echo "GRANT SELECT ON $(db).* TO 'bien'@'localhost';"|$(mysqlAsRoot)
420

    
421
rm_db: _always
422
	-echo "REVOKE ALL ON $(db).* FROM 'bien'@'localhost';"|$(mysqlAsRoot)
423
	echo "DROP DATABASE IF EXISTS $(db);"|$(mysqlAsRoot)
424
# ignore errors if grant not defined
425

    
426
## Unrecognized DB engine
427

    
428
else
429
$(error The DB filename $(dbExport) must be db.my.sql)
430
endif
431

    
432
### Other input types
433

    
434
else
435

    
436
src/install: _always ;
437
src/uninstall: _always ;
438

    
439
endif
440

    
441
#### DB connection info
442

    
443
ifneq ($(dbEngine),)
444
# Must come after dbEngine is set
445
mapEnv := in_engine=$(dbEngine) in_database=$(db)
446
endif
(2-2/2)