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
exts ?= csv tsv txt xml
17
test_n ?= 2
18

    
19
##### Vars/functions
20

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

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

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

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

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

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

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

    
59
# BIEN commands
60
sortFilenames = $(shell $(bin)/sort_filenames $(1))
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 addDirWithIgnore,src,'*')
100
	$(call addDirWithIgnore,src/specimens,'*')
101
	$(call addDirWithIgnore,src/specimens/logs,$$'*.log.sql\n*.trace')
102
	$(call addDirWithIgnore,verify,'*.out')
103

    
104
##### Existing maps discovery
105

    
106
sortFile := src/import_order.txt
107

    
108
ifneq ($(wildcard $(sortFile)),)
109
tables := $(shell cat $(sortFile))# $(shell) replaces "\n" with " "
110
else
111
allSubdirs := $(call wildcard/,src/*/)
112
tables := $(call sortFilenames,$(filter-out _%,$(allSubdirs:src/%/=%)))
113
endif
114

    
115
srcMaps := $(wildcard src/*/src.csv)
116

    
117
srcMap := src/%/src.csv
118
viaMap := src/%/map.csv
119
fullViaMap := src/%/map.full.csv
120
directMap := src/%/VegBIEN.csv
121
anyMap := $(srcMap) $(viaMap) $(fullViaMap) $(directMap)
122

    
123
anyTest = src/$*/test.%
124
srcsOnly = $(filter-out $(anyMap) $(anyTest) src/%/logs,$(1))
125

    
126
via := Veg+
127

    
128
coreMap := $(mappings)/$(via)-VegBIEN.csv
129
coreSelfMap := $(mappings)/$(via).self.csv
130

    
131
viaMaps := $(wildcard $(tables:%=src/%/map.csv))
132
viaMaps += $(filter-out $(viaMaps),$(srcMaps:src/%/src.csv=src/%/map.csv))
133
viaMaps += $(filter-out $(viaMaps) $(fullViaMap),$(wildcard src/*/map.csv))
134

    
135
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
136
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
137
$(wildcard src/*/VegBIEN.csv))
138

    
139
##### Sources
140

    
141
srcs = $(call sortFilenames,$(call srcsOnly,$(wildcard src/$*/*)))
142
isCsv = $(if $(srcs),$(if $(filter %.xml,$(srcs)),,1))
143
    # true if $(srcs) non-empty and contains no *.xml
144
catSrcs = $(bin)/cat$(if $(isCsv),_csv) $(srcs)
145
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
146

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

    
150
cat-%: _always
151
	$(catSrcs)
152

    
153
##### Staging tables installation
154

    
155
install: _always schema $(addprefix install-,$(tables)) ;
156

    
157
uninstall: _always rm_schema ;
158
# rm_schema will also drop all staging tables
159

    
160
reinstall: _always uninstall install ;
161

    
162
schema: _always
163
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
164
# ignore errors if schema exists
165

    
166
rm_schema: _always
167
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
168

    
169
install-%: _always
170
	$(if $(isCsv),$(import_install_))
171
import_install_ = (prefix=; . $(bin)/vegbien_dest; "time" nice -n +5\
172
env schema=$(datasrc) table=$* $(bin)/csv2db $(catSrcs)\
173
$(if $(log),$(if $(quiet),&>,2>&1|tee )src/$*/logs/install.log.sql))
174

    
175
##### Maps building
176

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

    
181
srcRoot = $(mappings)/roots/$*.sh
182
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
183

    
184
# Src maps cleanup
185
ifneq ($(filter src/%/.src.csv.last_cleanup,$(MAKECMDGOALS)),)
186
src/%/.src.csv.last_cleanup: src/%/src.csv
187
	$(bin)/in_place $< $(bin)/cols +
188
	touch $@
189
else
190
# Autogen src maps with known table names
191
src/%/src.csv: _always
192
	$(if $(wildcard $@),,$(if $(isCsv),$(mkSrcMap)))
193
	+$(if $(isCsv),$(selfMake) $(@:src/%/src.csv=src/%/.src.csv.last_cleanup))
194
# only build if doesn't exist
195
# only build if CSV srcs exist for that table name
196
endif
197

    
198
createOnlyMaps += $(tables:%=src/%/src.csv)
199

    
200
# Must come before $(root)/% to override it
201
$(coreSelfMap): _always
202
	-+$(subMake)
203
# ignore errors if $(coreSelfMap) does not exist
204

    
205
# Via maps cleanup
206
ifneq ($(filter src/%/.map.csv.last_cleanup,$(MAKECMDGOALS)),)
207
src/%/.map.csv.last_cleanup: src/%/map.csv $(coreMap)
208
	$(bin)/in_place $< env ignore=1 $(bin)/subtract $(word 2,$+) 0 1 2
209
	touch $@
210
# Include comment column so commented mappings are never removed
211
else
212
src/%/map.csv: src/%/src.csv _always
213
	$(if $(wildcard $@),,$(if $(wildcard $<),$(CP) $< $@))
214
	+$(selfMake) $(@:src/%/map.csv=src/%/.map.csv.last_cleanup)
215
endif
216

    
217
srcMap* = src/$*/src.csv
218
joinSrcMap = $(if $(hasSrc),$(bin)/in_place $@ $(bin)/intersect $(srcMap*) 0)
219
hasSrc = $(shell test -s $(word 3,$+) && echo t)
220

    
221
makeFullCsv = env ignore=1 $(bin)/union <$(wordlist 1,2,$+)|$(bin)/sort_map >$@
222

    
223
src/%/map.full.csv: src/%/map.csv $(coreSelfMap)
224
	$(makeFullCsv)
225
	$(joinSrcMap)
226
maps += $(patsubst src/%/map.csv,src/%/map.full.csv,$(viaMaps))
227

    
228
src/%/VegBIEN.csv: src/%/map.full.csv $(coreMap)
229
	$(bin)/join <$+|$(bin)/sort_map >$@
230
maps += $(autogenMaps)
231

    
232
maps: $(createOnlyMaps) $(maps) _always ;
233

    
234
all += $(maps)
235

    
236
##### Maps validation
237

    
238
missingMappingsCmd = +$(selfMake) remake 2>&1\
239
|$(SED) -n 's/^.*No $(*2Space) mapping for (.*)$$/\1/p'|$(SED) 's/\/_.*//'\
240
$(if $(filter non-empty_join,$*),|$(bin)/ucase_first 0)|sort|uniq
241

    
242
include $(root)/lib/mappings.Makefile
243

    
244
##### External dependencies
245

    
246
$(root)/%: _always
247
	+$(subMake)
248
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
249

    
250
##### Mapping
251

    
252
+maps = $(filter src/%/map.csv src/%/VegBIEN.csv $(mappings)/%,$(+_))
253
map = $(if $(srcs),$(withCatSrcs) $(root)/map $(+maps),\
254
$(shell echo Warning: No input file src/$*/*.{$(exts)} >&2)false)
255
# need false to run some command, when prefixed by `env ...` below
256
map2db = $(if $(use_staged),env in_database=vegbien in_schema=$(datasrc)\
257
in_table=$*) env out_database=vegbien $(map)
258

    
259
##### Import to VegBIEN
260

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

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

    
272
import: $(addprefix import-,$(tables)) _always ;
273

    
274
import-%: src/%/VegBIEN.csv _always
275
	$(import)
276
# default:
277
import-%: _always ;
278

    
279
##### Log files from import
280

    
281
logs := $(wildcard src/*/logs/*.log.sql src/*/logs/*.trace)
282

    
283
rm_logs: _always
284
	$(RM) $(logs)
285

    
286
##### Verification of import
287

    
288
verify: $(addprefix verify-,$(tables)) _always ;
289

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

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

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

    
307
all += $(wildcard verify/*.out)
308

    
309
##### Editing import
310

    
311
rotate: _always
312
	echo "UPDATE party SET organizationname = organizationname||'.$(date)'\
313
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
314

    
315
rm: _always
316
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
317
$(psqlAsBien)
318

    
319
##### Testing
320

    
321
testRefOutput = $(subst .2-step,,$(subst .staging,,$(1)))
322
testRef = $(testRefOutput).ref
323
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
324
# filter returns non-empty if they are equal
325

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

    
346
test2Db = $(call runTest,$(map2db))
347

    
348
tests :=
349

    
350
src/%/test.xml: src/%/VegBIEN.csv _always
351
	$(test2Db)
352
tests += src/%/test.xml
353

    
354
testStaged2Db = $(foreach use_staged,1,$(test2Db))
355
    # run with use_staged=1
356

    
357
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
358
src/%/test.staging.xml: src/%/VegBIEN.csv _always
359
	-$(if $(isCsv),$(testStaged2Db),cp -p $(@:.staging.xml=.xml) $@)
360
# Don't abort tester if only staging test fails, in case staging table missing
361
# Non-flat-file inputs fall back to mimicking a successful test
362
tests += src/%/test.staging.xml
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 += $(wildcard src/%/test*.xml)
371

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

    
376
accept-all: _always
377
	+yes|$(selfMake) test
378

    
379
##### Documentation
380

    
381
steps = $(selfMake) -s import-$* test=1 by_col=1 verbosity=2 n=100\
382
2>&1|$(bin)/debug2redmine >$@
383

    
384
src/%/logs/steps.by_col.log.sql: _always
385
	+$(steps)
(4-4/4)