Project

General

Profile

1
##### Configuration
2

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

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

    
14
##### Vars/functions
15

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

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

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

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

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

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

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

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

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

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

    
69
##### General targets
70

    
71
all: _always maps ;
72

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

    
77
_always:
78
.PHONY: _always
79

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

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

    
87
make_script = ./$< >$@
88

    
89
%/: % _always ;
90

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

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

    
99
##### SVN
100

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

    
109
##### Existing maps discovery
110

    
111
srcMap := maps/src.%.csv
112
fullViaMap := maps/%.full.csv
113
directMap := maps/VegBIEN.%.csv
114
allViaMaps := $(filter-out $(srcMap) $(fullViaMap) $(directMap),\
115
$(wildcard maps/*.csv))
116
via := $(firstword $(sort $(basename $(basename $(notdir $(allViaMaps))))))
117

    
118
coreMap := $(mappings)/$(via)-VegBIEN.%.csv
119
coreSelfMap := $(mappings)/$(via).self.%.csv
120

    
121
viaMaps := $(wildcard $(tablesSort:%=maps/$(via).%.csv))
122
viaMaps += $(filter-out $(viaMaps) $(fullViaMap),$(wildcard maps/$(via).*.csv))
123

    
124
autogenMaps := $(subst $(via).,VegBIEN.,$(viaMaps))
125
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
126
$(wildcard maps/VegBIEN.*.csv))
127
tables := $(directMaps:maps/VegBIEN.%.csv=%)
128

    
129
##### Installation
130

    
131
install: _always src/install import/install ;
132

    
133
uninstall: _always import/uninstall src/uninstall ;
134

    
135
reinstall: _always uninstall install ;
136

    
137
##### Staging tables
138

    
139
import/install: _always import/schema $(addprefix import/install-,$(tables)) ;
140

    
141
import/uninstall: _always import/rm_schema ;
142
# rm_schema will also drop all staging tables
143

    
144
import/schema: _always
145
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
146
# ignore errors if schema exists
147

    
148
import/rm_schema: _always
149
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
150

    
151
import/install-%: _always
152
	env datasrc=$(datasrc) table=$* $(withCatSrcs) $(bin)/csv2ddl$(if\
153
$(debug),|tee /dev/fd/2)|$(psqlAsBien)
154
	#-echo "COPY $(datasrc).;"|$(psqlAsBien)
155

    
156
##### Sources
157

    
158
srcs = $(shell $(bin)/sort_filenames $(wildcard $(exts:%=src/*.$*.%)))
159
isXml = $(filter %.xml,$(firstword $(srcs)))
160
catSrcs = $(bin)/cat$(if $(isXml),,_csv) $(srcs)
161
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
162

    
163
# Usage: `make {--silent|-s} cat` (removes echoed make commands)
164
cat: $(addprefix cat-,$(tables)) _always ;
165

    
166
cat-%: _always
167
	$(catSrcs)
168

    
169
##### Maps building
170

    
171
# Maps to (try to) build are added to one of these
172
maps :=
173
createOnlyMaps :=
174

    
175
srcMaps := $(wildcard maps/src.*.csv)
176

    
177
mkSrcMap = env datasrc=$(datasrc) $(withCatSrcs) $(bin)/src_map >$@
178

    
179
# Autogen src maps with known table names
180
maps/src.%.csv: # no prereqs so only built if doesn't exist
181
	$(if $(srcs),$(if $(isXml),,$(mkSrcMap)))
182
# only build if CSV srcs exist for that table name
183
# Try all table names
184
createOnlyMaps += $(tablesSort:%=maps/src.%.csv)
185

    
186
# Must come before $(root)/% to override it
187
$(coreSelfMap): _always
188
	-+$(subMake)
189
# ignore errors if $(coreSelfMap) does not exist
190

    
191
# Via maps cleanup
192
ifneq ($(filter maps/.%.last_cleanup,$(MAKECMDGOALS)),)
193
maps/.$(via).%.csv.last_cleanup: maps/$(via).%.csv $(coreMap)
194
	$(bin)/in_place $< env ignore=1 $(bin)/subtract $(word 2,$+) 0 1
195
	touch $@
196
else
197
$(viaMaps): _always
198
	$(selfMake) $(@:maps/%=maps/.%.last_cleanup)
199
endif
200

    
201
joinSrcMap = $(if $(wildcard maps/src.$*.csv),$(bin)/in_place $@\
202
$(bin)/intersect maps/src.$*.csv 0)
203

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

    
208
maps/$(via).%.full.csv: maps/$(via).%.csv $(coreSelfMap)
209
	$(makeFullCsv)
210
	$(joinSrcMap)
211
maps += $(patsubst maps/%.csv,maps/%.full.csv,$(viaMaps))
212

    
213
maps/VegBIEN.%.csv: maps/$(via).%.full.csv $(coreMap)
214
	$(bin)/join <$+|$(bin)/sort_map >$@
215
maps += $(autogenMaps)
216

    
217
maps: $(createOnlyMaps) $(maps) _always ;
218

    
219
all += $(maps)
220

    
221
##### Maps validation
222

    
223
missing_mappings: _always missing_join_mappings missing_input_mappings ;
224

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

    
231
##### External dependencies
232

    
233
$(root)/%: _always
234
	+$(subMake)
235
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
236

    
237
##### Mapping
238

    
239
dbExport := $(firstword $(wildcard src/db.*.sql))
240
inputFiles := $(wildcard $(exts:%=src/*.%))
241

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

    
251
##### Import to VegBIEN
252

    
253
ifneq ($(dbExport)$(inputFiles),)
254

    
255
profileTest = $(if $(profile),$(if $(test),1))
256
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
257
$(bin)/profile_stats /dev/fd/0
258

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

    
266
import: $(addprefix import-,$(tables)) _always ;
267

    
268
import-%: maps/VegBIEN.%.csv _always
269
	$(import)
270
# default:
271
import-%: _always ;
272

    
273
else
274
import: _always ;
275
endif
276

    
277
##### Log files from import
278

    
279
logs := $(wildcard import/*.log import/*.trace)
280

    
281
rm_logs: _always
282
	$(RM) $(logs)
283

    
284
##### Verification of import
285

    
286
verify: $(addprefix verify-,$(tables)) _always ;
287

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

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

    
300
verify/%.out: $(mappings)/verify.%.sql _always
301
	$(verify)
302
# default:
303
verify/%.out: _always ;
304

    
305
all += $(wildcard verify/*.out)
306

    
307
ifneq ($(dbExport),)
308
%.ref: %.ref.sql
309
	$(dbAsBien) $(db) <$< >$@
310
endif
311

    
312
##### Editing import
313

    
314
import/rotate: _always
315
	echo "UPDATE party SET organizationname = organizationname||'.$(date)'\
316
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
317

    
318
import/rm: _always
319
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
320
$(psqlAsBien)
321

    
322
##### Testing
323

    
324
hasOwnRef = $(filter-out %.2-step.xml,$@)
325
testRef = $(1:.2-step.xml=.xml).ref
326

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

    
343
test2File = $(call runTest,$(map))
344

    
345
tests :=
346

    
347
test/$(via).%.xml: maps/$(via).%.full.csv _always
348
	$(test2File)
349
tests += test/$(via).%.xml
350

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

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

    
360
test/import.%.out: maps/VegBIEN.%.csv _always
361
	$(call runTest,$(map2db))
362
tests += test/import.%.out
363

    
364
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
365

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

    
368
test: _always $(testOutputs) ;
369

    
370
all += $(testOutputs)
371

    
372
# Accepts a test output: make <test_output_path>-ok
373
%-ok: _always
374
	$(CP) $* $(call testRef,$*)
375

    
376
##### Input-type-specific
377

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

    
380
#### DB export
381

    
382
ifneq ($(dbExport),)
383

    
384
dbEngineExt := $(subst .,,$(suffix $(basename $(notdir $(dbExport)))))
385
db := $(datasrc)
386

    
387
### Installation
388

    
389
src/install: _always db ;
390

    
391
src/uninstall: _always rm_db ;
392

    
393
### DB-engine-specific
394

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

    
397
ifeq ($(dbEngineExt),my)
398

    
399
dbEngine := MySQL
400

    
401
bienPassword := $(shell cat $(root)/config/bien_password)
402
mysqlAs = mysql --user=$(1) --password='$(bienPassword)'
403
mysqlAsRoot := $(call mysqlAs,root)
404
dbAsBien := $(call mysqlAs,bien)
405

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

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

    
414
db: $(dbExport) _always
415
	$(if $(dbExists),,$(createDb))
416
	echo "GRANT SELECT ON $(db).* TO 'bien'@'localhost';"|$(mysqlAsRoot)
417

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

    
423
## Unrecognized DB engine
424

    
425
else
426
$(error The DB filename $(dbExport) must be db.my.sql)
427
endif
428

    
429
### Other input types
430

    
431
else
432

    
433
src/install: _always ;
434
src/uninstall: _always ;
435

    
436
endif
437

    
438
#### DB connection info
439

    
440
ifneq ($(dbEngine),)
441
# Must come after dbEngine is set
442
mapEnv := in_engine=$(dbEngine) in_database=$(db)
443
endif
(2-2/2)