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
allSubdirs := $(call wildcard/,src/*/)
107
tables := $(call sortFilenames,$(filter-out _%,$(allSubdirs:src/%/=%)))
108

    
109
srcMaps := $(wildcard src/*/src.csv)
110

    
111
srcMap := src/%/src.csv
112
viaMap := src/%/map.csv
113
fullViaMap := src/%/map.full.csv
114
directMap := src/%/VegBIEN.csv
115
anyMap := $(srcMap) $(viaMap) $(fullViaMap) $(directMap)
116

    
117
anyTest = src/$*/test.%
118
srcsOnly = $(filter-out $(anyMap) $(anyTest) src/%/logs,$(1))
119

    
120
via := Veg+
121

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

    
125
viaMaps := $(wildcard $(tables:%=src/%/map.csv))
126
viaMaps += $(filter-out $(viaMaps),$(srcMaps:src/%/src.csv=src/%/map.csv))
127
viaMaps += $(filter-out $(viaMaps) $(fullViaMap),$(wildcard src/*/map.csv))
128

    
129
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
130
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
131
$(wildcard src/*/VegBIEN.csv))
132

    
133
##### Sources
134

    
135
srcs = $(call sortFilenames,$(call srcsOnly,$(wildcard src/$*/*)))
136
isCsv = $(if $(srcs),$(if $(filter %.xml,$(srcs)),,1))
137
    # true if $(srcs) non-empty and contains no *.xml
138
catSrcs = $(bin)/cat$(if $(isCsv),_csv) $(srcs)
139
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
140

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

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

    
147
##### Staging tables installation
148

    
149
install: _always schema $(addprefix install-,$(tables)) ;
150

    
151
uninstall: _always rm_schema ;
152
# rm_schema will also drop all staging tables
153

    
154
reinstall: _always uninstall install ;
155

    
156
schema: _always
157
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
158
# ignore errors if schema exists
159

    
160
rm_schema: _always
161
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
162

    
163
install-%: _always
164
	$(if $(isCsv),$(import_install_))
165
import_install_ = (prefix=; . $(bin)/vegbien_dest; "time" nice -n +5\
166
env schema=$(datasrc) table=$* $(bin)/csv2db $(catSrcs)\
167
$(if $(log),$(if $(quiet),&>,2>&1|tee )src/$*/logs/install.log.sql))
168

    
169
##### Maps building
170

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

    
175
srcRoot = $(mappings)/roots/$*.sh
176
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
177

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

    
192
createOnlyMaps += $(tables:%=src/%/src.csv)
193

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

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

    
211
srcMap* = src/$*/src.csv
212
joinSrcMap = $(if $(hasSrc),$(bin)/in_place $@ $(bin)/intersect $(srcMap*) 0)
213
hasSrc = $(shell test -s $(word 3,$+) && echo t)
214

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

    
217
src/%/map.full.csv: src/%/map.csv $(coreSelfMap)
218
	$(makeFullCsv)
219
	$(joinSrcMap)
220
maps += $(patsubst src/%/map.csv,src/%/map.full.csv,$(viaMaps))
221

    
222
src/%/VegBIEN.csv: src/%/map.full.csv $(coreMap)
223
	$(bin)/join <$+|$(bin)/sort_map >$@
224
maps += $(autogenMaps)
225

    
226
maps: $(createOnlyMaps) $(maps) _always ;
227

    
228
all += $(maps)
229

    
230
##### Maps validation
231

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

    
236
include $(root)/lib/mappings.Makefile
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 src/%/map.csv src/%/VegBIEN.csv $(mappings)/%,$(+_))
247
map = $(if $(srcs),$(withCatSrcs) $(root)/map $(+maps),\
248
$(shell echo Warning: No input file src/$*/*.{$(exts)} >&2)false)
249
# need false to run some command, when prefixed by `env ...` below
250
map2db = $(if $(use_staged),env in_database=vegbien in_schema=$(datasrc)\
251
in_table=$*) env out_database=vegbien $(map)
252

    
253
##### Import to VegBIEN
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_ = src/$*/logs/$(if $(n),n=$(n).,)$(date).log.sql
260
trace = $(log_:.log.sql=.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_)))$(if $(log),$(if $(n), 2>&1|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-%: src/%/VegBIEN.csv _always
269
	$(import)
270
# default:
271
import-%: _always ;
272

    
273
##### Log files from import
274

    
275
logs := $(wildcard src/*/logs/*.log.sql src/*/logs/*.trace)
276

    
277
rm_logs: _always
278
	$(RM) $(logs)
279

    
280
##### Verification of import
281

    
282
verify: $(addprefix verify-,$(tables)) _always ;
283

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

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

    
296
verify/%.out: $(mappings)/verify.%.sql _always
297
	$(verify)
298
# default:
299
verify/%.out: _always ;
300

    
301
all += $(wildcard verify/*.out)
302

    
303
##### Editing import
304

    
305
rotate: _always
306
	echo "UPDATE party SET organizationname = organizationname||'.$(date)'\
307
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
308

    
309
rm: _always
310
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
311
$(psqlAsBien)
312

    
313
##### Testing
314

    
315
testRefOutput = $(subst .2-step,,$(subst .staging,,$(1)))
316
testRef = $(testRefOutput).ref
317
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
318
# filter returns non-empty if they are equal
319

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

    
340
test2Db = $(call runTest,$(map2db))
341

    
342
tests :=
343

    
344
src/%/test.xml: src/%/VegBIEN.csv _always
345
	$(test2Db)
346
tests += src/%/test.xml
347

    
348
testStaged2Db = $(foreach use_staged,1,$(test2Db))
349
    # run with use_staged=1
350

    
351
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
352
src/%/test.staging.xml: src/%/VegBIEN.csv _always
353
	-$(if $(isCsv),$(testStaged2Db),cp -p $(@:.staging.xml=.xml) $@)
354
# Don't abort tester if only staging test fails, in case staging table missing
355
# Non-flat-file inputs fall back to mimicking a successful test
356
tests += src/%/test.staging.xml
357

    
358
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
359

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

    
362
test: _always $(testOutputs) ;
363

    
364
all += $(wildcard src/%/test*.xml)
365

    
366
# Accepts a test output: make <test_output_path>-ok
367
%-ok: _always
368
	$(CP) $* $(call testRef,$*)
369

    
370
accept-all: _always
371
	+yes|$(selfMake) test
372

    
373
##### Documentation
374

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

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