Project

General

Profile

1
selfDir_uZPPqC := $(dir $(lastword $(MAKEFILE_LIST)))
2
root := $(selfDir_uZPPqC)..
3
include $(root)/lib/common.Makefile
4

    
5

    
6
##### Configuration
7

    
8
# Command line
9
log ?= $(if $(test),,1)
10
profile ?=
11
quiet ?=
12
reverify ?= 1
13
use_staged ?= $(by_col)
14

    
15
# Makefile
16
tablesSort ?= plots organisms stems specimens
17
exts ?= csv tsv txt xml
18
test_n ?= 2
19

    
20
##### Vars/functions
21

    
22
# Paths
23
datasrc := $(notdir $(realpath .))
24
bin := $(root)/bin
25
mappings := $(root)/mappings
26

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

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

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

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

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

    
51
# Commands
52
MKDIR = mkdir -p
53
mkdir = $(MKDIR) $(@D)
54
CP = cp -p
55
diff = diff --unified=2
56
diffIgnoreSpace = $(diff) --ignore-space-change
57
diffVerbose = $(if $(verbose),diff --side-by-side --left-column\
58
--width=$(termCols),$(diff))
59

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

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

    
73
##### General targets
74

    
75
all: _always maps ;
76

    
77
clean: _always
78
	$(RM) $(all)
79

    
80
remake: _always clean
81
	+$(selfMake)
82
# re-run make so that cache of existing files is reset
83

    
84
make_script = ./$< >$@
85

    
86
%/: % _always ;
87

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

    
93
%: %.make _always
94
	$(make_script)
95

    
96
##### SVN
97

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

    
106
##### Existing maps discovery
107

    
108
inputFiles := $(wildcard $(exts:%=src/*.%))
109
ifeq ($(inputFiles),)
110
dbExport := $(firstword $(wildcard src/db.*.sql))
111
endif
112

    
113
srcMaps := $(wildcard maps/src.*.csv)
114
srcRoots := $(srcMaps:maps/src.%.csv=$(mappings)/roots/%.sh)
115

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

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

    
131
coreMap := $(mappings)/$(via)-VegBIEN.%.csv
132
coreSelfMap := $(mappings)/$(via).self.%.csv
133

    
134
viaMaps := $(wildcard $(tablesSort:%=maps/$(via).%.csv))
135
viaMaps += $(filter-out $(viaMaps),$(srcMaps:maps/src.%=maps/$(via).%))
136
viaMaps += $(filter-out $(viaMaps) $(fullViaMap),$(wildcard maps/$(via).*.csv))
137

    
138
autogenMaps := $(subst $(via).,VegBIEN.,$(viaMaps))
139
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
140
$(wildcard maps/VegBIEN.*.csv))
141
tables := $(directMaps:maps/VegBIEN.%.csv=%)
142

    
143
##### Sources
144

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

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

    
154
cat-%: _always
155
	$(catSrcs)
156

    
157
##### Installation
158

    
159
install: _always src/install import/install ;
160

    
161
uninstall: _always import/uninstall src/uninstall ;
162

    
163
reinstall: _always uninstall install ;
164

    
165
##### Staging tables
166

    
167
import/install: _always import/schema $(addprefix import/install-,$(tables)) ;
168

    
169
import/uninstall: _always import/rm_schema ;
170
# rm_schema will also drop all staging tables
171

    
172
import/schema: _always
173
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
174
# ignore errors if schema exists
175

    
176
import/rm_schema: _always
177
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
178

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

    
185
##### Maps building
186

    
187
# Maps to (try to) build are added to one of these
188
maps :=
189
createOnlyMaps :=
190

    
191
srcRoot = $(mappings)/roots/$*.sh
192
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
193

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

    
208
# Try all table names
209
createOnlyMaps += $(tablesSort:%=maps/src.%.csv)
210

    
211
# Must come before $(root)/% to override it
212
$(coreSelfMap): _always
213
	-+$(subMake)
214
# ignore errors if $(coreSelfMap) does not exist
215

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

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

    
223
# Must come before maps/$(via).%.csv to override it
224
maps/$(via).%.full.csv: maps/$(via).%.csv $(coreSelfMap) $(srcMap)
225
	$(makeFullCsv)
226
	$(joinSrcMap)
227
maps += $(patsubst maps/%.csv,maps/%.full.csv,$(viaMaps))
228

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

    
241
maps/VegBIEN.%.csv: maps/$(via).%.full.csv $(coreMap)
242
	$(bin)/join <$+|$(bin)/sort_map >$@
243
maps += $(autogenMaps)
244

    
245
maps: $(createOnlyMaps) $(maps) _always ;
246

    
247
all += $(maps)
248

    
249
##### Maps validation
250

    
251
missing_mappings: _always missing_join_mappings missing_input_mappings ;
252

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

    
259
##### External dependencies
260

    
261
$(root)/%: _always
262
	+$(subMake)
263
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
264

    
265
##### Mapping
266

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

    
277
##### Import to VegBIEN
278

    
279
ifneq ($(dbExport)$(inputFiles),)
280

    
281
profileTest = $(if $(profile),$(if $(test),1))
282
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
283
$(bin)/profile_stats /dev/fd/0
284

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

    
292
import: $(addprefix import-,$(tables)) _always ;
293

    
294
import-%: maps/VegBIEN.%.csv _always
295
	$(import)
296
# default:
297
import-%: _always ;
298

    
299
else
300
import: _always ;
301
endif
302

    
303
##### Log files from import
304

    
305
logs := $(wildcard import/*.log.sql import/*.trace)
306

    
307
rm_logs: _always
308
	$(RM) $(logs)
309

    
310
##### Verification of import
311

    
312
verify: $(addprefix verify-,$(tables)) _always ;
313

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

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

    
326
verify/%.out: $(mappings)/verify.%.sql _always
327
	$(verify)
328
# default:
329
verify/%.out: _always ;
330

    
331
all += $(wildcard verify/*.out)
332

    
333
ifneq ($(dbExport),)
334
%.ref: %.ref.sql
335
	$(dbAsBien) $(db) <$< >$@
336
endif
337

    
338
##### Editing import
339

    
340
import/rotate: _always
341
	echo "UPDATE party SET organizationname = organizationname||'.$(date)'\
342
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
343

    
344
import/rm: _always
345
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
346
$(psqlAsBien)
347

    
348
##### Testing
349

    
350
testRefOutput = $(subst .2-step,,$(subst .staging,,$(1)))
351
testRef = $(testRefOutput).ref
352
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
353
# filter returns non-empty if they are equal
354

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

    
375
test2Db = $(call runTest,$(map2db))
376

    
377
tests :=
378

    
379
test/import.%.xml: maps/VegBIEN.%.csv _always
380
	$(test2Db)
381
tests += test/import.%.xml
382

    
383
testStaged2Db = $(foreach use_staged,1,$(test2Db))
384
    # run with use_staged=1
385

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

    
393
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
394

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

    
397
test: _always $(testOutputs) ;
398

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

    
401
# Accepts a test output: make <test_output_path>-ok
402
%-ok: _always
403
	$(CP) $* $(call testRef,$*)
404

    
405
test/accept-all: _always
406
	+yes|$(selfMake) test
407

    
408
##### Documentation
409

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

    
413
import/steps.by_col.sql: _always
414
	+$(steps)
415

    
416
##### Input-type-specific
417

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

    
420
#### DB export
421

    
422
ifneq ($(dbExport),)
423

    
424
dbEngineExt := $(subst .,,$(suffix $(basename $(notdir $(dbExport)))))
425
db := $(datasrc)
426

    
427
### Installation
428

    
429
src/install: _always db ;
430

    
431
src/uninstall: _always rm_db ;
432

    
433
### DB-engine-specific
434

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

    
437
ifeq ($(dbEngineExt),my)
438

    
439
dbEngine := MySQL
440

    
441
bienPassword := $(shell cat $(root)/config/bien_password)
442
mysqlAs = mysql --user=$(1) --password='$(bienPassword)'
443
mysqlAsRoot := $(call mysqlAs,root)
444
dbAsBien := $(call mysqlAs,bien)
445

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

    
448
define createDb
449
echo "CREATE DATABASE $(db) DEFAULT CHARACTER SET latin1;"|$(mysqlAsRoot)
450
-$(mysqlAsRoot) --database=$(db) <$<
451
endef
452
# ignore errors in db import so that GRANT will still be run
453

    
454
db: $(dbExport) _always
455
	$(if $(dbExists),,$(createDb))
456
	echo "GRANT SELECT ON $(db).* TO 'bien'@'localhost';"|$(mysqlAsRoot)
457

    
458
rm_db: _always
459
	-echo "REVOKE ALL ON $(db).* FROM 'bien'@'localhost';"|$(mysqlAsRoot)
460
	echo "DROP DATABASE IF EXISTS $(db);"|$(mysqlAsRoot)
461
# ignore errors if grant not defined
462

    
463
## Unrecognized DB engine
464

    
465
else
466
$(error The DB filename $(dbExport) must be db.my.sql)
467
endif
468

    
469
### Other input types
470

    
471
else
472

    
473
src/install: _always ;
474
src/uninstall: _always ;
475

    
476
endif
477

    
478
#### DB connection info
479

    
480
ifneq ($(dbEngine),)
481
# Must come after dbEngine is set
482
mapEnv := in_engine=$(dbEngine) in_database=$(db)
483
endif
(4-4/4)