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
diffIgnoreSpace = $(diff) --ignore-space-change
55
diffVerbose = $(if $(verbose),diff --side-by-side --left-column\
56
--width=$(termCols),$(diff))
57

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

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

    
71
##### General targets
72

    
73
all: _always maps ;
74

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

    
79
_always:
80
.PHONY: _always
81

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

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

    
89
make_script = ./$< >$@
90

    
91
%/: % _always ;
92

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

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

    
101
##### SVN
102

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

    
111
##### Existing maps discovery
112

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

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

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

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

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

    
139
viaMaps := $(wildcard $(tablesSort:%=maps/$(via).%.csv))
140
viaMaps += $(filter-out $(viaMaps),$(srcMaps:maps/src.%=maps/$(via).%))
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
##### Sources
149

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

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

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

    
162
##### Installation
163

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

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

    
168
reinstall: _always uninstall install ;
169

    
170
##### Staging tables
171

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

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

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

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

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

    
190
##### Maps building
191

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

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

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

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

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

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

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

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

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

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

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

    
252
all += $(maps)
253

    
254
##### Maps validation
255

    
256
missing_mappings: _always missing_join_mappings missing_input_mappings ;
257

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

    
264
##### External dependencies
265

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

    
270
##### Mapping
271

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

    
282
##### Import to VegBIEN
283

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

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

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

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

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

    
304
else
305
import: _always ;
306
endif
307

    
308
##### Log files from import
309

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

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

    
315
##### Verification of import
316

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

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

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

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

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

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

    
343
##### Editing import
344

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

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

    
353
##### Testing
354

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

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

    
380
test2Db = $(call runTest,$(map2db))
381

    
382
tests :=
383

    
384
test/import.%.xml: maps/VegBIEN.%.csv _always
385
	$(test2Db)
386
tests += test/import.%.xml
387

    
388
testStaged2Db = $(foreach use_staged,1,$(test2Db))
389
    # run with use_staged=1
390

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

    
398
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
399

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

    
402
test: _always $(testOutputs) ;
403

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

    
406
# Accepts a test output: make <test_output_path>-ok
407
%-ok: _always
408
	$(CP) $* $(call testRef,$*)
409

    
410
test/accept-all: _always
411
	+yes|$(selfMake) test
412

    
413
##### Documentation
414

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

    
418
import/steps.by_col.sql: _always
419
	+$(steps)
420

    
421
##### Input-type-specific
422

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

    
425
#### DB export
426

    
427
ifneq ($(dbExport),)
428

    
429
dbEngineExt := $(subst .,,$(suffix $(basename $(notdir $(dbExport)))))
430
db := $(datasrc)
431

    
432
### Installation
433

    
434
src/install: _always db ;
435

    
436
src/uninstall: _always rm_db ;
437

    
438
### DB-engine-specific
439

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

    
442
ifeq ($(dbEngineExt),my)
443

    
444
dbEngine := MySQL
445

    
446
bienPassword := $(shell cat $(root)/config/bien_password)
447
mysqlAs = mysql --user=$(1) --password='$(bienPassword)'
448
mysqlAsRoot := $(call mysqlAs,root)
449
dbAsBien := $(call mysqlAs,bien)
450

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

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

    
459
db: $(dbExport) _always
460
	$(if $(dbExists),,$(createDb))
461
	echo "GRANT SELECT ON $(db).* TO 'bien'@'localhost';"|$(mysqlAsRoot)
462

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

    
468
## Unrecognized DB engine
469

    
470
else
471
$(error The DB filename $(dbExport) must be db.my.sql)
472
endif
473

    
474
### Other input types
475

    
476
else
477

    
478
src/install: _always ;
479
src/uninstall: _always ;
480

    
481
endif
482

    
483
#### DB connection info
484

    
485
ifneq ($(dbEngine),)
486
# Must come after dbEngine is set
487
mapEnv := in_engine=$(dbEngine) in_database=$(db)
488
endif
(4-4/4)