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 dmp xml
17
test_n ?= 2
18

    
19
##### Vars/functions
20

    
21
# Paths
22
datasrc := $(patsubst .%,%,$(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
# Terminal
41
termCols := $(shell tput cols)
42
esc := '['
43
reset := $(esc)'0m'
44
emph := $(esc)'7m '
45
endEmph := ' '$(reset)
46

    
47
# User interaction
48

    
49
confirm = $(if $(shell read -p $(emph)"$(1)"$(endEmph)$$'$(if\
50
$(2),\n$(2))\nContinue? (y/n) ' REPLY; test "$$REPLY" = y && echo t),,\
51
$(error Aborting))
52

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

    
62
# BIEN commands
63
sortFilenames = $(shell $(bin)/sort_filenames $(1))
64
selfMap = $(bin)/cols 0 0
65
psqlOpts := --set ON_ERROR_STOP=1 --quiet
66
psqlAsBien := $(bin)/psql_vegbien $(psqlOpts)
67
# Usage: ($(inDatasrc); cat $(file))|$(psqlCmd)
68
inDatasrc = echo 'SET search_path TO "$(datasrc)";'
69

    
70
# SVN
71
addDir = $(if $(wildcard $(1)/),svn add --depth=empty $(1),svn mkdir $(1))
72
setSvnIgnore = svn propset svn:ignore $(2) $(1)
73
define addDirWithIgnore
74
$(addDir)
75
$(setSvnIgnore)
76
endef
77

    
78
##### Environment
79

    
80
export PATH := $(bin):$(PATH)
81

    
82
##### General targets
83

    
84
all: _always maps ;
85

    
86
clean: _always
87
	$(RM) $(all)
88

    
89
remake: _always clean
90
	+$(selfMake)
91
# re-run make so that cache of existing files is reset
92

    
93
make_script = ./$< >$@
94

    
95
%/: % _always ;
96

    
97
%: %.make
98
	$(if $(wildcard $@),,"time" $(make_script))
99
# Only remake if doesn't exist. This prevents unintentional remaking when the
100
# make script is newly checked out from svn (which sets the mod time to now) but
101
# the output is synced externally.
102
# Can't remove prereq to do this, because it determines when the rule applies.
103
.PRECIOUS: % # save partial outputs of aborted src make scripts
104

    
105
##### SVN
106

    
107
add: _always
108
	$(call setSvnIgnore,.,'*')
109
	$(call addDirWithIgnore,logs,$$'*.log.sql\n*.trace')
110
	$(call addDirWithIgnore,verify,'*.out')
111
	$(call addFile,import_order.txt)
112

    
113
# Adds a new table subdir
114
%/add: _always
115
	$(call addDirWithIgnore,$*,'*')
116
	$(call addDirWithIgnore,$*/logs,$$'*.log.sql\n*.trace')
117

    
118
##### Existing maps discovery
119

    
120
sortFile := import_order.txt
121

    
122
tables := $(if $(wildcard $(sortFile)),$(shell cat $(sortFile)))
123
    # $(shell) replaces "\n" with " "
124
allSubdirs := $(call wildcard/,*/)
125
allTables := $(call sortFilenames,$(filter-out _% verify logs,$(allSubdirs:%/=%)))
126
joinedTables := $(filter-out $(tables),$(allTables))
127
allTables := $(joinedTables) $(tables)# move joined tables to beginning
128
ifeq ($(tables),)# none specified in sort file
129
tables := $(allTables)
130
endif
131

    
132
anyMap := %/map.csv %/VegBIEN.csv %/unmapped_terms.csv %/new_terms.csv
133

    
134
extsFilter := $(addprefix %.,$(exts))
135
dataOnly = $(filter $(extsFilter),$(1))
136

    
137
anyTest = $*/test.%
138
srcsOnly = $(filter-out $(anyMap) $(anyTest) %/logs,$(call dataOnly,$(1)))
139

    
140
vocab := $(mappings)/VegCore.csv
141
coreMap := $(mappings)/VegCore-VegBIEN.csv
142
dict := $(mappings)/Veg+-VegCore.csv
143

    
144
viaMaps := $(tables:%=%/map.csv)
145

    
146
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
147
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
148
$(wildcard */VegBIEN.csv))
149

    
150
##### Sources
151

    
152
srcs = $(call sortFilenames,$(call srcsOnly,$(wildcard $*/*)))
153
nonHeaderSrcs = $(filter-out %/header.csv,$(srcs))
154
isRef = $(if $(nonHeaderSrcs),,1)
155
    # empty subdir, so references an already-installed staging table
156
isXml = $(filter %.xml,$(nonHeaderSrcs))
157
nonXml = $(if $(isXml),,1)
158
isCsv = $(if $(nonHeaderSrcs),$(if $(isXml),,1))
159
    # true if $(srcs) non-empty and contains no *.xml
160
catSrcs = $(bin)/cat$(if $(nonXml),_csv) $(srcs)
161
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
162

    
163
# Usage: `make {--silent|-s} inputs/<datasrc>/cat` (don't echo make commands)
164
cat: $(tables:%=%/cat) _always ;
165

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

    
169
##### Staging tables installation
170

    
171
dbExports := $(sort $(wildcard *.schema.sql))# schemas first
172
dbExports += $(sort $(filter-out $(dbExports),$(wildcard *.sql)))# all others
173
dbExports := $(strip $(dbExports))# += adds extra whitespace
174
allInstalls := $(if $(dbExports),sql) $(allTables)
175

    
176
install: _always schema $(allInstalls:%=%/install) ;
177

    
178
uninstall: _always confirm_rm_schema rm_schema ;
179
# rm_schema will also drop all staging tables
180

    
181
reinstall: _always uninstall install ;
182

    
183
confirm_rm_schema: _always
184
	$(if $(filter TNRS,$(datasrc)),$(call confirm,WARNING: This will delete the\
185
TNRS cache!,To save it: make backups/TNRS.backup-remake))
186

    
187
schema: _always
188
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
189
# ignore errors if schema exists
190

    
191
rm_schema: _always
192
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
193

    
194
installLog := logs/install.log.sql
195

    
196
logInstall = $(if $(log),$(if $(quiet),$(2)$(1)$(installLog) 2>&1,2>&1|tee $(3)\
197
$(1)$(installLog)))
198
logInstall* = $(call logInstall,$*/,>)
199
logInstall*Add = $(call logInstall,$*/,>>,-a)# append to log
200

    
201
# Must come before %/install to override it
202
sql/install: $(dbExports)
203
	($(inDatasrc); cat $+|grep -vF 'SET search_path')|"time" $(psqlAsBien) \
204
$(logInstall)
205

    
206
# The export must be created with:
207
# `--compatible=postgresql --add-locks=false --set-charset --no-create-info`
208
# Must come before `%.sql: _MySQL/%.sql` to override it
209
%.data.sql: _MySQL/%.data.sql
210
	$(bin)/my2pg.data <$< >$@
211

    
212
# The export must be created with:
213
# `--compatible=postgresql --add-locks=false --set-charset`
214
# Add `--no-data` to create a schema-only export.
215
%.sql: _MySQL/%.sql
216
	$(bin)/my2pg <$< >$@
217

    
218
cleanup = (prefix=; . $(bin)/vegbien_dest; env schema=$(datasrc) table=$*\
219
$(bin)/csv2db) $(logInstall*Add)
220

    
221
define exportHeader
222
$(cleanup)
223
echo 'SELECT * FROM "$(datasrc)"."$*" LIMIT 0;'|$(psqlAsBien) \
224
--no-align --field-separator=, --pset=footer=off >$*/header.csv
225
endef
226

    
227
# For staging tables which are derived by joining together other staging tables.
228
%/install %/header.csv: %/create.sql _always
229
	($(inDatasrc); echo 'CREATE TABLE "$*" AS'; cat $<; echo ';')|"time" \
230
$(psqlAsBien) --echo-all --set=table='"$*"' $(logInstall*)
231
	$(exportHeader)
232
.PRECIOUS: %/header.csv
233

    
234
%/install: _always
235
	$(if $(isRef),$(exportHeader),$(if $(nonXml),$(import_install_)))
236
import_install_ = (prefix=; . $(bin)/vegbien_dest; "time" nice -n +5\
237
env schema=$(datasrc) table=$* $(bin)/csv2db $(catSrcs) $(logInstall*))
238

    
239
cleanup: _always $(tables:%=%/cleanup) ;
240

    
241
# WARNING: This removes any index comments, due to a PostgreSQL bug.
242
# This occurs because ALTER TABLE recreates the index but not its comment.
243
%/cleanup: _always
244
	$(cleanup)
245
	$(if $(wildcard $*/cleanup.sql),($(inDatasrc); cat $*/cleanup.sql;)\
246
|"time" $(psqlAsBien) --echo-all --set=table='"$*"' $(logInstall*Add))
247

    
248
##### Maps building
249

    
250
# WARNING: You CANNOT make a subdir using `make inputs/<datasrc>/<subdir>/`.
251
# You must instead make the entire datasource dir: `make inputs/<datasrc>/`
252

    
253
# Maps to (try to) build are added to this
254
maps :=
255

    
256
srcRoot = $(mappings)/root.sh
257
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
258

    
259
# Via maps cleanup
260
ifneq ($(filter %/.map.csv.last_cleanup,$(MAKECMDGOALS)),)
261
%/.map.csv.last_cleanup: %/map.csv $(vocab) $(dict)
262
	$(bin)/in_place $< $(bin)/canon 1 $(vocab)
263
	$(bin)/in_place $< $(bin)/canon 1 $(dict)
264
	$(bin)/in_place $< $(bin)/translate 1 $(dict)
265
	touch $@
266
	+$(selfMake) $(<:%/map.csv=%/unmapped_terms.csv)
267
	+$(selfMake) $(<:%/map.csv=%/new_terms.csv)
268
.PRECIOUS: %/.map.csv.last_cleanup
269
else
270
%/map.csv: _always
271
	$(if $(wildcard $@),,$(if $(nonXml),$(mkSrcMap)))
272
	+$(selfMake) $(@:%/map.csv=%/.map.csv.last_cleanup)
273
.PRECIOUS: %/map.csv
274
endif
275

    
276
%/VegBIEN.csv: %/map.csv $(coreMap)
277
	<$< $(bin)/cat_cols 1 2|$(bin)/join $(coreMap)|$(bin)/sort_map >$@
278
maps += $(autogenMaps)
279

    
280
maps: $(maps) _always ;
281

    
282
all += $(maps)
283

    
284
##### Maps validation
285

    
286
# `tail -n +2`: Remove header before running filter_out_ci because filter_out_ci
287
# only removes the header if it matches the vocabulary's header.
288

    
289
%/unmapped_terms.csv: %/map.csv $(coreMap)
290
	tail -n +2 $<|$(bin)/cols 1|$(bin)/filter_out_ci 0 $(coreMap) >$@
291
	$(bin)/autoremove $@
292

    
293
%/new_terms.csv: %/map.csv $(vocab) $(dict) %/unmapped_terms.csv
294
	$(newTerms)
295
	$(bin)/autoremove $@
296
newTerms = tail -n +2 $<|$(bin)/filter_out_ci 0 $(vocab)|$(bin)/filter_out_ci 0\
297
$(dict) $(if $(wildcard $(word 4,$+)),|$(bin)/filter_out_ci 0 $(word 4,$+)) >$@
298

    
299
termsSubdirs := $(tables)
300

    
301
include $(root)/lib/mappings.Makefile
302

    
303
##### External dependencies
304

    
305
$(root)/%: _always
306
	+$(subMake)
307
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
308

    
309
##### Mapping
310

    
311
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
312
map2db = env in_database=vegbien in_schema=$(datasrc) in_table=$*\
313
out_database=vegbien $(root)/map $(+maps)
314

    
315
##### Import to VegBIEN
316

    
317
profileTest = $(if $(profile),$(if $(test),1))
318
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
319
$(bin)/profile_stats /dev/fd/0
320

    
321
log_ = $*/logs/$(if $(n),n=$(n).,)$(date).log.sql
322
trace = $(log_:.log.sql=.trace)
323
import = -$(if $(profileTest),$(profileOnly),(set -x; "time" env commit=1\
324
$(if $(profile),profile_to=$(trace)) $(map2db)) $(if $(log),\
325
$(if $(n),,&>$(log_)))$(if $(log),$(if $(n), 2>&1|tee -a $(log_))))
326
# don't abort on import errors, which often relate to invalid input data
327

    
328
import: $(tables:%=%/import) _always ;
329

    
330
%/import: %/VegBIEN.csv _always
331
	$(import)
332
# default:
333
%/import: _always ;
334

    
335
##### Log files from import
336

    
337
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
338

    
339
rm_logs: _always
340
	$(RM) $(logs)
341

    
342
##### Verification of import
343

    
344
verify: $(tables:%=%/verify) _always ;
345

    
346
%/verify: verify/%.ref verify/%.out _always
347
	-$(diffVerbose) $(+_)
348
# don't abort on verification errors, which are expected during development
349
# default:
350
%/verify: verify/%.out _always
351
	$(if $(shell test -e $< && echo t),cat $<)
352
# don't run if verify/%.out's default do-nothing action was used
353
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
354

    
355
psqlExport := "time" $(psqlAsBien) --no-align --field-separator=$$'\t'\
356
--pset=footer=off --pset=null=NULL
357
verify = $(if $(reverify),$(psqlExport) --set=datasource="'$(datasrc)'" <$< >$@)
358

    
359
verify/%.out: $(mappings)/verify.%.sql _always
360
	$(verify)
361
# default:
362
verify/%.out: _always ;
363

    
364
all += $(wildcard verify/*.out)
365

    
366
%.ref: %.ref.sql
367
	($(inDatasrc); cat $<)|$(psqlExport) >$@
368

    
369
##### Editing import
370

    
371
rotate: _always
372
	echo "UPDATE party SET organizationname = organizationname||'.$(date)'\
373
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
374

    
375
rm: _always
376
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
377
$(psqlAsBien)
378

    
379
##### Testing
380

    
381
testRefOutput = $(subst .by_col,,$(1))
382
testRef = $(testRefOutput).ref
383
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
384
# filter returns non-empty if they are equal
385

    
386
# `rm $@`: Remove outputs of successful tests to reduce clutter
387
# `$(foreach use_staged...)`: Run with use_staged=1
388
define runTest
389
@echo "Testing $(abspath $@)..."
390
>$@ env test=1 n=$(test_n) $(1) $(foreach use_staged,1,$(map2db))
391
@(set -x; $(diffIgnoreSpace) $(call testRef,$@) $@) 2>&1 && rm $@ || { e=$$?;\
392
$(if $(wildcard $(call testRef,$@)),,cat $@;)\
393
$(if $(hasOwnRef),\
394
{\
395
read -p $(emph)'Accept new test output? (y/n)'$(endEmph) REPLY;\
396
if test "$$REPLY" = y; then\
397
(set -x; $(MAKE) $@-ok --directory=$(realpath .) --makefile=../input.Makefile);\
398
exit 0;\
399
fi;\
400
};,\
401
echo $(emph)"Note: The preceding failed test is compared to another test's\
402
output"$(endEmph);\
403
echo $(emph)"When it fails, this always indicates a bug"$(endEmph);\
404
)\
405
exit $$e;}
406
endef
407

    
408
tests :=
409

    
410
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
411
# Non-flat-file inputs fall back to mimicking a successful test
412
%/test.xml: %/VegBIEN.csv _always
413
	$(if $(nonXml),$(call runTest,by_col=))
414
tests += %/test.xml
415

    
416
%/test.by_col.xml: %/VegBIEN.csv _always
417
	$(if $(nonXml),$(call runTest,by_col=1))
418

    
419
# Only run column-based tests if column-based mode enabled, because these tests
420
# are much slower than the row-based tests for small numbers of rows
421
ifneq ($(by_col),)
422
tests += %/test.by_col.xml
423
endif
424

    
425
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
426

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

    
429
test: _always $(testOutputs) ;
430

    
431
all += $(wildcard %/test*.xml)
432

    
433
# Accepts a test output: make <test_output_path>-ok
434
%-ok: _always
435
	mv $* $(call testRef,$*)
436

    
437
accept-all: _always
438
	+yes|$(selfMake) test
439

    
440
##### Documentation
441

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

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