Project

General

Profile

1
##### Configuration
2

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

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

    
15
##### Vars/functions
16

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

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

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

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

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

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

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

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

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

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

    
70
##### General targets
71

    
72
all: _always maps ;
73

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

    
78
_always:
79
.PHONY: _always
80

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

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

    
88
make_script = ./$< >$@
89

    
90
%/: % _always ;
91

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

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

    
100
##### SVN
101

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

    
110
##### Existing maps discovery
111

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

    
117
srcMaps := $(wildcard maps/src.*.csv)
118
srcRoots := $(srcMaps:maps/src.%.csv=$(mappings)/roots/%.sh)
119

    
120
srcMap := maps/src.%.csv
121
fullViaMap := maps/%.full.csv
122
directMap := maps/VegBIEN.%.csv
123
allViaMaps := $(filter-out $(srcMap) $(fullViaMap) $(directMap),\
124
$(wildcard maps/*.csv))
125
via := $(firstword $(sort $(basename $(basename $(notdir $(allViaMaps))))))
126

    
127
# Look up via in src maps' roots
128
ifeq ($(via),)
129
ifneq ($(srcRoots),)
130
via := $(firstword $(sort\
131
$(shell $(SED) -n 's/^export out_root="([0-9A-Za-z_-]+).*$$/\1/p' $(srcRoots))))
132
endif
133
endif
134

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

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

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

    
147
##### Sources
148

    
149
srcs = $(shell $(bin)/sort_filenames $(wildcard $(exts:%=src/*.$*.%)))
150
isCsv = $(if $(srcs),$(if $(filter %.xml,$(srcs)),,1))
151
    # true if $(srcs) non-empty and contains no *.xml
152
catSrcs = $(bin)/cat$(if $(isCsv),_csv) $(srcs)
153
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
154

    
155
# Usage: `make {--silent|-s} inputs/<datasrc>/cat` (don't echo make commands)
156
cat: $(addprefix cat-,$(tables)) _always ;
157

    
158
cat-%: _always
159
	$(catSrcs)
160

    
161
##### Installation
162

    
163
install: _always src/install import/install ;
164

    
165
uninstall: _always import/uninstall src/uninstall ;
166

    
167
reinstall: _always uninstall install ;
168

    
169
##### Staging tables
170

    
171
import/install: _always import/schema $(addprefix import/install-,$(tables)) ;
172

    
173
import/uninstall: _always import/rm_schema ;
174
# rm_schema will also drop all staging tables
175

    
176
import/schema: _always
177
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
178
# ignore errors if schema exists
179

    
180
import/rm_schema: _always
181
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
182

    
183
import/install-%: _always
184
	$(if $(isCsv),$(import_install_))
185
import_install_ = (prefix=; . $(bin)/vegbien_dest; "time" nice -n +5\
186
env schema=$(datasrc) table=$* $(bin)/csv2db $(catSrcs)\
187
$(if $(log),$(if $(quiet),&>,2>&1|tee )import/install-$*.log.sql))
188

    
189
##### Maps building
190

    
191
# Maps to (try to) build are added to one of these
192
maps :=
193
createOnlyMaps :=
194

    
195
srcRoot = $(mappings)/roots/$*.sh
196
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
197

    
198
# Src maps cleanup
199
ifneq ($(filter maps/.%.last_cleanup,$(MAKECMDGOALS)),)
200
maps/.src.%.csv.last_cleanup: maps/src.%.csv
201
	$(bin)/in_place $< $(bin)/cols '*'
202
	touch $@
203
else
204
# Autogen src maps with known table names
205
maps/src.%.csv: _always
206
	$(if $(wildcard $@),,$(if $(isCsv),$(mkSrcMap)))
207
	+$(if $(isCsv),$(selfMake) $(@:maps/%=maps/.%.last_cleanup))
208
# only build if doesn't exist
209
# only build if CSV srcs exist for that table name
210
endif
211

    
212
# Try all table names
213
createOnlyMaps += $(tablesSort:%=maps/src.%.csv)
214

    
215
# Must come before $(root)/% to override it
216
$(coreSelfMap): _always
217
	-+$(subMake)
218
# ignore errors if $(coreSelfMap) does not exist
219

    
220
joinSrcMap = $(if $(hasSrc),$(bin)/in_place $@ $(bin)/intersect $(word 3,$+) 0)
221
hasSrc = $(shell test -s $(word 3,$+) && echo t)
222

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

    
227
# Must come before maps/$(via).%.csv to override it
228
maps/$(via).%.full.csv: maps/$(via).%.csv $(coreSelfMap) $(srcMap)
229
	$(makeFullCsv)
230
	$(joinSrcMap)
231
maps += $(patsubst maps/%.csv,maps/%.full.csv,$(viaMaps))
232

    
233
# Via maps cleanup
234
ifneq ($(filter maps/.%.last_cleanup,$(MAKECMDGOALS)),)
235
maps/.$(via).%.csv.last_cleanup: maps/$(via).%.csv $(coreMap)
236
	$(bin)/in_place $< env ignore=1 $(bin)/subtract $(word 2,$+) 0 1 2
237
	touch $@
238
# Include comment column so commented mappings are never removed
239
else
240
maps/$(via).%.csv: maps/src.%.csv _always
241
	$(if $(wildcard $@),,$(if $(wildcard $<),$(CP) $< $@))
242
	+$(selfMake) $(@:maps/%=maps/.%.last_cleanup)
243
endif
244

    
245
maps/VegBIEN.%.csv: maps/$(via).%.full.csv $(coreMap)
246
	$(bin)/join <$+|$(bin)/sort_map >$@
247
maps += $(autogenMaps)
248

    
249
maps: $(createOnlyMaps) $(maps) _always ;
250

    
251
all += $(maps)
252

    
253
##### Maps validation
254

    
255
missing_mappings: _always missing_join_mappings missing_input_mappings ;
256

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

    
263
##### External dependencies
264

    
265
$(root)/%: _always
266
	+$(subMake)
267
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
268

    
269
##### Mapping
270

    
271
+maps = $(filter maps/% $(mappings)/%,$(+_))
272
<in = $(firstword $(filter-out $(+maps),$(+_)))
273
map = $(if $(<in),<$(<in),\
274
$(if $(srcs),$(withCatSrcs),\
275
$(if $(mapEnv),env $(mapEnv),\
276
$(error No input file src/*.$*.{$(exts)}))))\
277
$(root)/map $(+maps)
278
map2db = $(if $(use_staged),env in_database=vegbien in_schema=$(datasrc)\
279
in_table=$*) env out_database=vegbien $(map)
280

    
281
##### Import to VegBIEN
282

    
283
ifneq ($(dbExport)$(inputFiles),)
284

    
285
profileTest = $(if $(profile),$(if $(test),1))
286
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
287
$(bin)/profile_stats /dev/fd/0
288

    
289
log_ = import/$*$(if $(n),.n=$(n),).$(date).log.sql
290
trace = $(log_:.log.sql=.trace)
291
import = -$(if $(profileTest),$(profileOnly),(set -x; "time" env commit=1\
292
$(if $(profile),profile_to=$(trace)) $(map2db)) $(if $(log),\
293
$(if $(n),,&>$(log_)))$(if $(log),$(if $(n), 2>&1|tee -a $(log_))))
294
# don't abort on import errors, which often relate to invalid input data
295

    
296
import: $(addprefix import-,$(tables)) _always ;
297

    
298
import-%: maps/VegBIEN.%.csv _always
299
	$(import)
300
# default:
301
import-%: _always ;
302

    
303
else
304
import: _always ;
305
endif
306

    
307
##### Log files from import
308

    
309
logs := $(wildcard import/*.log.sql import/*.trace)
310

    
311
rm_logs: _always
312
	$(RM) $(logs)
313

    
314
##### Verification of import
315

    
316
verify: $(addprefix verify-,$(tables)) _always ;
317

    
318
verify-%: verify/%.ref verify/%.out _always
319
	-$(diffVerbose) $(+_)
320
# don't abort on verification errors, which are expected during development
321
# default:
322
verify-%: verify/%.out _always
323
	$(if $(shell test -e $< && echo t),cat $<)
324
# don't run if verify/%.out's default do-nothing action was used
325
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
326

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

    
330
verify/%.out: $(mappings)/verify.%.sql _always
331
	$(verify)
332
# default:
333
verify/%.out: _always ;
334

    
335
all += $(wildcard verify/*.out)
336

    
337
ifneq ($(dbExport),)
338
%.ref: %.ref.sql
339
	$(dbAsBien) $(db) <$< >$@
340
endif
341

    
342
##### Editing import
343

    
344
import/rotate: _always
345
	echo "UPDATE party SET organizationname = organizationname||'.$(date)'\
346
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
347

    
348
import/rm: _always
349
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
350
$(psqlAsBien)
351

    
352
##### Testing
353

    
354
testRefOutput = $(subst .2-step,,$(subst .staging,,$(1)))
355
testRef = $(testRefOutput).ref
356
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
357
# filter returns non-empty if they are equal
358

    
359
define runTest
360
@echo "Testing $(abspath $@)..."
361
>$@ env test=1 n=$(test_n) $(1)
362
@(set -x; $(diff) $(call testRef,$@) $@) 2>&1 || { e=$$?;\
363
$(if $(wildcard $(call testRef,$@)),,cat $@;)\
364
$(if $(hasOwnRef),\
365
{\
366
read -p $(emph)'Accept new test output? (y/n)'$(endEmph) REPLY;\
367
if test "$$REPLY" = y; then\
368
(set -x; $(MAKE) $@-ok --directory=$(realpath .) --makefile=../input.Makefile);\
369
exit 0;\
370
fi;\
371
};,\
372
echo $(emph)"Note: The preceding failed test is compared to another test's\
373
output"$(endEmph);\
374
echo $(emph)"When it fails, this always indicates a bug"$(endEmph);\
375
)\
376
exit $$e;}
377
endef
378

    
379
test2File = $(call runTest,$(map))
380
test2Db = $(call runTest,$(map2db))
381

    
382
tests :=
383

    
384
test/$(via).%.xml: maps/$(via).%.full.csv _always
385
	$(test2File)
386
tests += test/$(via).%.xml
387

    
388
test/VegBIEN.%.xml: maps/VegBIEN.%.csv _always
389
	$(test2File)
390
tests += test/VegBIEN.%.xml
391

    
392
test/VegBIEN.%.2-step.xml: test/$(via).%.xml $(coreMap) _always
393
	-$(test2File)
394
# Don't abort tester if only 2-step test fails, as it's often finicky
395
tests += test/VegBIEN.%.2-step.xml
396

    
397
test/import.%.xml: maps/VegBIEN.%.csv _always
398
	$(test2Db)
399
tests += test/import.%.xml
400

    
401
testStaged2Db = $(foreach use_staged,1,$(test2Db))
402
    # run with use_staged=1
403

    
404
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
405
test/import.%.staging.xml: maps/VegBIEN.%.csv _always
406
	-$(if $(isCsv),$(testStaged2Db),cp -p $(@:.staging.xml=.xml) $@)
407
# Don't abort tester if only staging test fails, in case staging table missing
408
# Non-flat-file inputs fall back to mimicking a successful test
409
tests += test/import.%.staging.xml
410

    
411
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
412

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

    
415
test: _always $(testOutputs) ;
416

    
417
all += $(filter-out %.ref,$(wildcard test/*))
418

    
419
# Accepts a test output: make <test_output_path>-ok
420
%-ok: _always
421
	$(CP) $* $(call testRef,$*)
422

    
423
test/accept-all: _always
424
	+yes|$(selfMake) test
425

    
426
##### Documentation
427

    
428
steps = $(selfMake) -s import test=1 by_col=1 verbosity=2 n=100\
429
2>&1|$(bin)/debug2redmine >$@
430

    
431
import/steps.by_col.sql: _always
432
	+$(steps)
433

    
434
##### Input-type-specific
435

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

    
438
#### DB export
439

    
440
ifneq ($(dbExport),)
441

    
442
dbEngineExt := $(subst .,,$(suffix $(basename $(notdir $(dbExport)))))
443
db := $(datasrc)
444

    
445
### Installation
446

    
447
src/install: _always db ;
448

    
449
src/uninstall: _always rm_db ;
450

    
451
### DB-engine-specific
452

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

    
455
ifeq ($(dbEngineExt),my)
456

    
457
dbEngine := MySQL
458

    
459
bienPassword := $(shell cat $(root)/config/bien_password)
460
mysqlAs = mysql --user=$(1) --password='$(bienPassword)'
461
mysqlAsRoot := $(call mysqlAs,root)
462
dbAsBien := $(call mysqlAs,bien)
463

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

    
466
define createDb
467
echo "CREATE DATABASE $(db) DEFAULT CHARACTER SET latin1;"|$(mysqlAsRoot)
468
-$(mysqlAsRoot) --database=$(db) <$<
469
endef
470
# ignore errors in db import so that GRANT will still be run
471

    
472
db: $(dbExport) _always
473
	$(if $(dbExists),,$(createDb))
474
	echo "GRANT SELECT ON $(db).* TO 'bien'@'localhost';"|$(mysqlAsRoot)
475

    
476
rm_db: _always
477
	-echo "REVOKE ALL ON $(db).* FROM 'bien'@'localhost';"|$(mysqlAsRoot)
478
	echo "DROP DATABASE IF EXISTS $(db);"|$(mysqlAsRoot)
479
# ignore errors if grant not defined
480

    
481
## Unrecognized DB engine
482

    
483
else
484
$(error The DB filename $(dbExport) must be db.my.sql)
485
endif
486

    
487
### Other input types
488

    
489
else
490

    
491
src/install: _always ;
492
src/uninstall: _always ;
493

    
494
endif
495

    
496
#### DB connection info
497

    
498
ifneq ($(dbEngine),)
499
# Must come after dbEngine is set
500
mapEnv := in_engine=$(dbEngine) in_database=$(db)
501
endif
(4-4/4)