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/VegBIEN.%.xml: maps/VegBIEN.%.csv _always
385
	$(test2File)
386
tests += test/VegBIEN.%.xml
387

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

    
392
testStaged2Db = $(foreach use_staged,1,$(test2Db))
393
    # run with use_staged=1
394

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

    
402
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
403

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

    
406
test: _always $(testOutputs) ;
407

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

    
410
# Accepts a test output: make <test_output_path>-ok
411
%-ok: _always
412
	$(CP) $* $(call testRef,$*)
413

    
414
test/accept-all: _always
415
	+yes|$(selfMake) test
416

    
417
##### Documentation
418

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

    
422
import/steps.by_col.sql: _always
423
	+$(steps)
424

    
425
##### Input-type-specific
426

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

    
429
#### DB export
430

    
431
ifneq ($(dbExport),)
432

    
433
dbEngineExt := $(subst .,,$(suffix $(basename $(notdir $(dbExport)))))
434
db := $(datasrc)
435

    
436
### Installation
437

    
438
src/install: _always db ;
439

    
440
src/uninstall: _always rm_db ;
441

    
442
### DB-engine-specific
443

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

    
446
ifeq ($(dbEngineExt),my)
447

    
448
dbEngine := MySQL
449

    
450
bienPassword := $(shell cat $(root)/config/bien_password)
451
mysqlAs = mysql --user=$(1) --password='$(bienPassword)'
452
mysqlAsRoot := $(call mysqlAs,root)
453
dbAsBien := $(call mysqlAs,bien)
454

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

    
457
define createDb
458
echo "CREATE DATABASE $(db) DEFAULT CHARACTER SET latin1;"|$(mysqlAsRoot)
459
-$(mysqlAsRoot) --database=$(db) <$<
460
endef
461
# ignore errors in db import so that GRANT will still be run
462

    
463
db: $(dbExport) _always
464
	$(if $(dbExists),,$(createDb))
465
	echo "GRANT SELECT ON $(db).* TO 'bien'@'localhost';"|$(mysqlAsRoot)
466

    
467
rm_db: _always
468
	-echo "REVOKE ALL ON $(db).* FROM 'bien'@'localhost';"|$(mysqlAsRoot)
469
	echo "DROP DATABASE IF EXISTS $(db);"|$(mysqlAsRoot)
470
# ignore errors if grant not defined
471

    
472
## Unrecognized DB engine
473

    
474
else
475
$(error The DB filename $(dbExport) must be db.my.sql)
476
endif
477

    
478
### Other input types
479

    
480
else
481

    
482
src/install: _always ;
483
src/uninstall: _always ;
484

    
485
endif
486

    
487
#### DB connection info
488

    
489
ifneq ($(dbEngine),)
490
# Must come after dbEngine is set
491
mapEnv := in_engine=$(dbEngine) in_database=$(db)
492
endif
(4-4/4)