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
%: %.make _always
90
	(set -x; $(make_script)) 2>>$<.log.sql
91
.PRECIOUS: % # save partial outputs of aborted src make scripts
92

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

    
96
##### SVN
97

    
98
add: _always
99
	$(call setSvnIgnore,.,'*')
100
	$(call addDirWithIgnore,verify,'*.out')
101

    
102
# Adds a new table subdir
103
%/add: _always
104
	$(call addDirWithIgnore,$*,'*')
105
	$(call addDirWithIgnore,$*/logs,$$'*.log.sql\n*.trace')
106

    
107
##### Existing maps discovery
108

    
109
sortFile := import_order.txt
110

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

    
118
srcMaps := $(wildcard */src.csv)
119

    
120
srcMap := %/src.csv
121
viaMap := %/map.csv
122
fullViaMap := %/map.full.csv
123
directMap := %/VegBIEN.csv
124
anyMap := $(srcMap) $(viaMap) $(fullViaMap) $(directMap)
125

    
126
extsFilter := $(addprefix %.,$(exts))
127
dataOnly = $(filter $(extsFilter),$(1))
128

    
129
anyTest = $*/test.%
130
srcsOnly = $(filter-out $(anyMap) $(anyTest) %/logs,$(call dataOnly,$(1)))
131

    
132
via := Veg+
133

    
134
coreMap := $(mappings)/$(via)-VegBIEN.csv
135
coreSelfMap := $(mappings)/$(via).self.csv
136

    
137
viaMaps := $(wildcard $(tables:%=%/map.csv))
138
viaMaps += $(filter-out $(viaMaps),$(srcMaps:%/src.csv=%/map.csv))
139
viaMaps += $(filter-out $(viaMaps) $(fullViaMap),$(wildcard */map.csv))
140

    
141
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
142
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
143
$(wildcard */VegBIEN.csv))
144

    
145
##### Sources
146

    
147
srcs = $(call sortFilenames,$(call srcsOnly,$(wildcard $*/*)))
148
isCsv = $(if $(srcs),$(if $(filter %.xml,$(srcs)),,1))
149
    # true if $(srcs) non-empty and contains no *.xml
150
catSrcs = $(bin)/cat$(if $(isCsv),_csv) $(srcs)
151
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
152

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

    
156
cat-%: _always
157
	$(catSrcs)
158

    
159
##### Staging tables installation
160

    
161
install: _always schema $(addprefix install-,$(tables)) ;
162

    
163
uninstall: _always rm_schema ;
164
# rm_schema will also drop all staging tables
165

    
166
reinstall: _always uninstall install ;
167

    
168
schema: _always
169
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
170
# ignore errors if schema exists
171

    
172
rm_schema: _always
173
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
174

    
175
install-%: _always
176
	$(if $(isCsv),$(import_install_))
177
import_install_ = (prefix=; . $(bin)/vegbien_dest; "time" nice -n +5\
178
env schema=$(datasrc) table=$* $(bin)/csv2db $(catSrcs)\
179
$(if $(log),$(if $(quiet),&>,2>&1|tee )$*/logs/install.log.sql))
180

    
181
##### Maps building
182

    
183
# Maps to (try to) build are added to one of these
184
maps :=
185
createOnlyMaps :=
186

    
187
srcRoot = $(mappings)/root.sh
188
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
189

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

    
204
createOnlyMaps += $(tables:%=%/src.csv)
205

    
206
# Must come before $(root)/% to override it
207
$(coreSelfMap): _always
208
	-+$(subMake)
209
# ignore errors if $(coreSelfMap) does not exist
210

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

    
223
srcMap* = $*/src.csv
224
joinSrcMap = $(if $(hasSrc),$(bin)/in_place $@ $(bin)/intersect $(srcMap*) 0)
225
hasSrc = $(shell test -s $(word 3,$+) && echo t)
226

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

    
229
%/map.full.csv: %/map.csv $(coreSelfMap)
230
	$(makeFullCsv)
231
	$(joinSrcMap)
232
maps += $(patsubst %/map.csv,%/map.full.csv,$(viaMaps))
233

    
234
%/VegBIEN.csv: %/map.full.csv $(coreMap)
235
	$(bin)/join <$+|$(bin)/sort_map >$@
236
maps += $(autogenMaps)
237

    
238
maps: $(createOnlyMaps) $(maps) _always ;
239

    
240
all += $(maps)
241

    
242
##### Maps validation
243

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

    
248
include $(root)/lib/mappings.Makefile
249

    
250
##### External dependencies
251

    
252
$(root)/%: _always
253
	+$(subMake)
254
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
255

    
256
##### Mapping
257

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

    
265
##### Import to VegBIEN
266

    
267
profileTest = $(if $(profile),$(if $(test),1))
268
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
269
$(bin)/profile_stats /dev/fd/0
270

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

    
278
import: $(addprefix import-,$(tables)) _always ;
279

    
280
import-%: %/VegBIEN.csv _always
281
	$(import)
282
# default:
283
import-%: _always ;
284

    
285
##### Log files from import
286

    
287
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
288

    
289
rm_logs: _always
290
	$(RM) $(logs)
291

    
292
##### Verification of import
293

    
294
verify: $(addprefix verify-,$(tables)) _always ;
295

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

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

    
308
verify/%.out: $(mappings)/verify.%.sql _always
309
	$(verify)
310
# default:
311
verify/%.out: _always ;
312

    
313
all += $(wildcard verify/*.out)
314

    
315
##### Editing import
316

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

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

    
325
##### Testing
326

    
327
testRefOutput = $(subst .2-step,,$(subst .staging,,$(1)))
328
testRef = $(testRefOutput).ref
329
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
330
# filter returns non-empty if they are equal
331

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

    
352
test2Db = $(call runTest,$(map2db))
353

    
354
tests :=
355

    
356
%/test.xml: %/VegBIEN.csv _always
357
	$(test2Db)
358
tests += %/test.xml
359

    
360
testStaged2Db = $(foreach use_staged,1,$(test2Db))
361
    # run with use_staged=1
362

    
363
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
364
%/test.staging.xml: %/VegBIEN.csv _always
365
	-$(if $(isCsv),$(testStaged2Db),cp -p $(@:.staging.xml=.xml) $@)
366
# Don't abort tester if only staging test fails, in case staging table missing
367
# Non-flat-file inputs fall back to mimicking a successful test
368
tests += %/test.staging.xml
369

    
370
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
371

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

    
374
test: _always $(testOutputs) ;
375

    
376
all += $(wildcard %/test*.xml)
377

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

    
382
accept-all: _always
383
	+yes|$(selfMake) test
384

    
385
##### Documentation
386

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

    
390
%/logs/steps.by_col.log.sql: _always
391
	+$(steps)
(4-4/4)