Project

General

Profile

1
##### Configuration
2

    
3
# Command line
4
log ?= $(if $(test),,1)
5
profile ?=
6
reverify ?= 1
7
debug ?=
8
quiet ?=
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
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
srcMap := maps/src.%.csv
118
fullViaMap := maps/%.full.csv
119
directMap := maps/VegBIEN.%.csv
120
allViaMaps := $(filter-out $(srcMap) $(fullViaMap) $(directMap),\
121
$(wildcard maps/*.csv))
122
via := $(firstword $(sort $(basename $(basename $(notdir $(allViaMaps))))))
123

    
124
coreMap := $(mappings)/$(via)-VegBIEN.%.csv
125
coreSelfMap := $(mappings)/$(via).self.%.csv
126

    
127
viaMaps := $(wildcard $(tablesSort:%=maps/$(via).%.csv))
128
viaMaps += $(filter-out $(viaMaps) $(fullViaMap),$(wildcard maps/$(via).*.csv))
129

    
130
autogenMaps := $(subst $(via).,VegBIEN.,$(viaMaps))
131
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
132
$(wildcard maps/VegBIEN.*.csv))
133
tables := $(directMaps:maps/VegBIEN.%.csv=%)
134

    
135
##### Sources
136

    
137
srcs = $(shell $(bin)/sort_filenames $(wildcard $(exts:%=src/*.$*.%)))
138
isCsv = $(if $(srcs),$(if $(filter %.xml,$(srcs)),,1))
139
    # true if $(srcs) non-empty and contains no *.xml
140
catSrcs = $(bin)/cat$(if $(isCsv),_csv) $(srcs)
141
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
142

    
143
# Usage: `make {--silent|-s} cat` (removes echoed make commands)
144
cat: $(addprefix cat-,$(tables)) _always ;
145

    
146
cat-%: _always
147
	$(catSrcs)
148

    
149
##### Installation
150

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

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

    
155
reinstall: _always uninstall install ;
156

    
157
##### Staging tables
158

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

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

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

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

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

    
176
##### Maps building
177

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

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

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

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

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

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

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

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

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

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

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

    
226
all += $(maps)
227

    
228
##### Maps validation
229

    
230
missing_mappings: _always missing_join_mappings missing_input_mappings ;
231

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

    
238
##### External dependencies
239

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

    
244
##### Mapping
245

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

    
255
##### Import to VegBIEN
256

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

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

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

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

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

    
277
else
278
import: _always ;
279
endif
280

    
281
##### Log files from import
282

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

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

    
288
##### Verification of import
289

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

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

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

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

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

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

    
316
##### Editing import
317

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

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

    
326
##### Testing
327

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

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

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

    
349
tests :=
350

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

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

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

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

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

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

    
372
test: _always $(testOutputs) ;
373

    
374
all += $(testOutputs)
375

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

    
380
##### Input-type-specific
381

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

    
384
#### DB export
385

    
386
ifneq ($(dbExport),)
387

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

    
391
### Installation
392

    
393
src/install: _always db ;
394

    
395
src/uninstall: _always rm_db ;
396

    
397
### DB-engine-specific
398

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

    
401
ifeq ($(dbEngineExt),my)
402

    
403
dbEngine := MySQL
404

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

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

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

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

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

    
427
## Unrecognized DB engine
428

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

    
433
### Other input types
434

    
435
else
436

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

    
440
endif
441

    
442
#### DB connection info
443

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