Project

General

Profile

1
##### Configuration
2

    
3
log ?= $(if $(test),,1)
4
profile ?=
5
reverify ?= 1
6
exts ?= csv tsv txt xml
7
test_n ?= 2
8
tablesSort ?= plots organisms stems specimens
9

    
10
##### Vars/functions
11

    
12
selfDir_uZPPqC := $(dir $(lastword $(MAKEFILE_LIST)))
13

    
14
# Paths
15
datasrc := $(notdir $(realpath .))
16
root := $(selfDir_uZPPqC)..
17
bin := $(root)/bin
18
mappings := $(root)/mappings
19

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

    
27
# OS
28
os := $(shell uname)
29
forOs = $(patsubst %,%-$(filter Linux Darwin,$(os)),$(1))
30

    
31
# Formatting
32
SED = sed -$(if $(filter Darwin,$(os)),E,r)
33

    
34
# System
35
date = $(shell date +"%Y-%m-%d-%H-%M-%S")
36

    
37
# Terminal
38
termCols := $(shell tput cols)
39
esc := '['
40
reset := $(esc)'0m'
41
emph := $(esc)'7m '
42
endEmph := ' '$(reset)
43

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

    
52
# Commands
53
selfMap = $(bin)/cols 0 0
54
psqlOpts := --set ON_ERROR_STOP=1 --quiet
55
psqlAsBien := $(bin)/psql_vegbien $(psqlOpts)
56

    
57
# SVN
58
addDir = $(if $(wildcard $(1)/),svn add --depth=empty $(1),svn mkdir $(1))
59
setSvnIgnore = svn propset svn:ignore $(2) $(1)
60
define addDirWithIgnore
61
$(addDir)
62
$(setSvnIgnore)
63
endef
64

    
65
##### General targets
66

    
67
all: _always maps ;
68

    
69
.SUFFIXES: # turn off built-in suffix rules
70
.SECONDARY: # don't automatically delete intermediate files
71
.DELETE_ON_ERROR: # delete target if recipe fails
72

    
73
_always:
74
.PHONY: _always
75

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

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

    
83
make_script = ./$< >$@
84

    
85
%/: % _always ;
86

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

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

    
95
##### SVN
96

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

    
105
##### Installation
106

    
107
install: _always src/install ;
108

    
109
uninstall: _always src/uninstall ;
110

    
111
reinstall: _always uninstall install ;
112

    
113
##### Existing maps discovery
114

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

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

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

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

    
133
##### Sources
134

    
135
srcs = $(shell $(bin)/sort_filenames $(wildcard $(exts:%=src/*.$*.%)))
136
isXml = $(filter %.xml,$(firstword $(srcs)))
137
catSrcs = $(bin)/cat$(if $(isXml),,_csv) $(srcs)
138
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
139

    
140
# Usage: `make {--silent|-s} cat` (removes echoed make commands)
141
cat: $(addprefix cat-,$(tables)) _always ;
142

    
143
cat-%: _always
144
	$(catSrcs)
145

    
146
##### Maps building
147

    
148
# Maps to (try to) build are added to one of these
149
maps :=
150
createOnlyMaps :=
151

    
152
srcMaps := $(wildcard maps/src.*.csv)
153

    
154
mkSrcMap = env datasrc=$(datasrc) $(withCatSrcs) $(bin)/src_map >$@
155

    
156
# Autogen src maps with known table names
157
maps/src.%.csv: # no prereqs so only built if doesn't exist
158
	$(if $(srcs),$(if $(isXml),,$(mkSrcMap)))
159
# only build if CSV srcs exist for that table name
160
# Try all table names
161
createOnlyMaps += $(tablesSort:%=maps/src.%.csv)
162

    
163
# Must come before $(root)/% to override it
164
$(coreSelfMap): _always
165
	-+$(subMake)
166
# ignore errors if $(coreSelfMap) does not exist
167

    
168
# Via maps cleanup
169
ifneq ($(filter maps/.%.last_cleanup,$(MAKECMDGOALS)),)
170
maps/.$(via).%.csv.last_cleanup: maps/$(via).%.csv $(coreMap)
171
	$(bin)/in_place $< env ignore=1 $(bin)/subtract $(word 2,$+) 0 1
172
	touch $@
173
else
174
$(viaMaps): _always
175
	$(selfMake) $(@:maps/%=maps/.%.last_cleanup)
176
endif
177

    
178
joinSrcMap = $(if $(wildcard maps/src.$*.csv),$(bin)/in_place $@\
179
$(bin)/intersect maps/src.$*.csv 0)
180

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

    
185
maps/$(via).%.full.csv: maps/$(via).%.csv $(coreSelfMap)
186
	$(makeFullCsv)
187
	$(joinSrcMap)
188
maps += $(patsubst maps/%.csv,maps/%.full.csv,$(viaMaps))
189

    
190
maps/VegBIEN.%.csv: maps/$(via).%.full.csv $(coreMap)
191
	$(bin)/join <$+|$(bin)/sort_map >$@
192
maps += $(autogenMaps)
193

    
194
maps: $(createOnlyMaps) $(maps) _always ;
195

    
196
all += $(maps)
197

    
198
##### Maps validation
199

    
200
missing_mappings: _always missing_join_mappings missing_input_mappings ;
201

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

    
208
##### External dependencies
209

    
210
$(root)/%: _always
211
	+$(subMake)
212
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
213

    
214
##### Mapping
215

    
216
dbExport := $(firstword $(wildcard src/db.*.sql))
217
inputFiles := $(wildcard $(exts:%=src/*.%))
218

    
219
+maps = $(filter maps/% $(mappings)/%,$(+_))
220
<in = $(firstword $(filter-out $(+maps),$(+_)))
221
map = $(if $(<in),<$(<in),\
222
$(if $(srcs),$(withCatSrcs),\
223
$(if $(mapEnv),env $(mapEnv),\
224
$(error No input file src/*.$*.{$(exts)}))))\
225
$(root)/map $(+maps)
226
map2db = env out_database=vegbien $(map)
227

    
228
##### Import to VegBIEN
229

    
230
ifneq ($(dbExport)$(inputFiles),)
231

    
232
profileTest = $(if $(profile),$(if $(test),1))
233
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
234
$(bin)/profile_stats /dev/fd/0
235

    
236
log_ = import/$*$(if $(n),.n=$(n),).$(date).log
237
trace = $(log_:.log=.trace)
238
import = -$(if $(profileTest),$(profileOnly),(set -x; "time" env commit=1\
239
$(if $(profile),profile_to=$(trace)) $(map2db)) $(if $(log),\
240
$(if $(n),,>>$(log_))) 2>&1$(if $(log),$(if $(n),|tee -a $(log_))))
241
# don't abort on import errors, which often relate to invalid input data
242

    
243
import: $(addprefix import-,$(tables)) _always ;
244

    
245
import-%: maps/VegBIEN.%.csv _always
246
	$(import)
247
# default:
248
import-%: _always ;
249

    
250
else
251
import: _always ;
252
endif
253

    
254
##### Log files from import
255

    
256
logs := $(wildcard import/*.log import/*.trace)
257

    
258
rm_logs: _always
259
	$(RM) $(logs)
260

    
261
##### Verification of import
262

    
263
verify: $(addprefix verify-,$(tables)) _always ;
264

    
265
verify-%: verify/%.ref verify/%.out _always
266
	-$(diffVerbose) $(+_)
267
# don't abort on verification errors, which are expected during development
268
# default:
269
verify-%: verify/%.out _always
270
	$(if $(shell test -e $< && echo t),cat $<)
271
# don't run if verify/%.out's default do-nothing action was used
272
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
273

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

    
277
verify/%.out: $(mappings)/verify.%.sql _always
278
	$(verify)
279
# default:
280
verify/%.out: _always ;
281

    
282
all += $(wildcard verify/*.out)
283

    
284
ifneq ($(dbExport),)
285
%.ref: %.ref.sql
286
	$(dbAsBien) $(db) <$< >$@
287
endif
288

    
289
##### Editing import
290

    
291
import/rotate: _always
292
	echo "UPDATE party SET organizationname = organizationname||'.$(date)'\
293
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
294

    
295
import/rm: _always
296
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
297
$(psqlAsBien)
298

    
299
##### Testing
300

    
301
hasOwnRef = $(filter-out %.2-step.xml,$@)
302
testRef = $(1:.2-step.xml=.xml).ref
303

    
304
define runTest
305
@echo "Testing $(abspath $@)..."
306
>$@ env test=1 n=$(test_n) $(1)
307
@(set -x; $(diff) $(call testRef,$@) $@) 2>&1 || { e=$$?;\
308
$(if $(wildcard $(call testRef,$@)),,cat $@;)\
309
$(if $(hasOwnRef),\
310
echo $(emph)"To accept new test output:"$(endEmph);\
311
echo "$(MAKE) $@-ok --directory=$(realpath .) --makefile=../input.Makefile";\
312
,\
313
echo $(emph)"Note: The preceding failed test is compared to another test's\
314
output"$(endEmph);\
315
echo $(emph)"When it fails, this always indicates a bug"$(endEmph);\
316
)\
317
exit $$e;}
318
endef
319

    
320
test2File = $(call runTest,$(map))
321

    
322
tests :=
323

    
324
test/$(via).%.xml: maps/$(via).%.full.csv _always
325
	$(test2File)
326
tests += test/$(via).%.xml
327

    
328
test/VegBIEN.%.xml: maps/VegBIEN.%.csv _always
329
	$(test2File)
330
tests += test/VegBIEN.%.xml
331

    
332
test/VegBIEN.%.2-step.xml: test/$(via).%.xml $(coreMap) _always
333
	-$(test2File)
334
# Don't abort tester if only 2-step test fails, as it's often finicky
335
tests += test/VegBIEN.%.2-step.xml
336

    
337
test/import.%.out: maps/VegBIEN.%.csv _always
338
	$(call runTest,$(map2db))
339
tests += test/import.%.out
340

    
341
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
342

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

    
345
test: _always $(testOutputs) ;
346

    
347
all += $(testOutputs)
348

    
349
# Accepts a test output: make <test_output_path>-ok
350
%-ok: _always
351
	$(CP) $* $(call testRef,$*)
352

    
353
##### Input-type-specific
354

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

    
357
#### DB export
358

    
359
ifneq ($(dbExport),)
360

    
361
dbEngineExt := $(subst .,,$(suffix $(basename $(notdir $(dbExport)))))
362
db := $(datasrc)
363

    
364
### Installation
365

    
366
src/install: _always db ;
367

    
368
src/uninstall: _always rm_db ;
369

    
370
### DB-engine-specific
371

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

    
374
ifeq ($(dbEngineExt),my)
375

    
376
dbEngine := MySQL
377

    
378
bienPassword := $(shell cat $(root)/config/bien_password)
379
mysqlAs = mysql --user=$(1) --password='$(bienPassword)'
380
mysqlAsRoot := $(call mysqlAs,root)
381
dbAsBien := $(call mysqlAs,bien)
382

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

    
385
define createDb
386
echo "CREATE DATABASE $(db) DEFAULT CHARACTER SET latin1;"|$(mysqlAsRoot)
387
-$(mysqlAsRoot) --database=$(db) <$<
388
endef
389
# ignore errors in db import so that GRANT will still be run
390

    
391
db: $(dbExport) _always
392
	$(if $(dbExists),,$(createDb))
393
	echo "GRANT SELECT ON $(db).* TO 'bien'@'localhost';"|$(mysqlAsRoot)
394

    
395
rm_db: _always
396
	-echo "REVOKE ALL ON $(db).* FROM 'bien'@'localhost';"|$(mysqlAsRoot)
397
	echo "DROP DATABASE IF EXISTS $(db);"|$(mysqlAsRoot)
398
# ignore errors if grant not defined
399

    
400
## Unrecognized DB engine
401

    
402
else
403
$(error The DB filename $(dbExport) must be db.my.sql)
404
endif
405

    
406
### Other input types
407

    
408
else
409

    
410
src/install: _always ;
411
src/uninstall: _always ;
412

    
413
endif
414

    
415
#### DB connection info
416

    
417
ifneq ($(dbEngine),)
418
# Must come after dbEngine is set
419
mapEnv := in_engine=$(dbEngine) in_database=$(db)
420
endif
(2-2/2)