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 := $(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
# 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
# User interaction
51

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

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

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

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

    
81
##### Environment
82

    
83
export PATH := $(bin):$(PATH)
84

    
85
##### General targets
86

    
87
all: _always maps ;
88

    
89
clean: _always
90
	$(RM) $(all)
91

    
92
remake: _always clean
93
	+$(selfMake)
94
# re-run make so that cache of existing files is reset
95

    
96
make_script = ./$< >$@
97

    
98
%/: % _always ;
99

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

    
108
##### SVN
109

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

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

    
121
##### Existing maps discovery
122

    
123
sortFile := import_order.txt
124

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

    
135
anyMap := %/map.csv %/VegBIEN.csv %/unmapped_terms.csv %/new_terms.csv
136

    
137
extsFilter := $(addprefix %.,$(exts))
138
dataOnly = $(filter $(extsFilter),$(1))
139

    
140
anyTest = $*/test.%
141
srcsOnly = $(filter-out $(anyMap) $(anyTest) %/logs,$(call dataOnly,$(1)))
142

    
143
vocab := $(mappings)/VegCore.csv
144
coreMap := $(mappings)/VegCore-VegBIEN.csv
145
dict := $(mappings)/Veg+-VegCore.csv
146

    
147
viaMaps := $(tables:%=%/map.csv)
148

    
149
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
150
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
151
$(wildcard */VegBIEN.csv))
152

    
153
##### Sources
154

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

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

    
169
%/cat: _always
170
	$(catSrcs)
171

    
172
##### Staging tables installation
173

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

    
179
install: _always schema $(allInstalls:%=%/install) ;
180

    
181
uninstall: _always confirm_rm_schema rm_schema ;
182
# rm_schema will also drop all staging tables
183

    
184
reinstall: _always uninstall install ;
185

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

    
190
schema: _always
191
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
192
# ignore errors if schema exists
193

    
194
rm_schema: _always
195
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
196

    
197
installLog := logs/install.log.sql
198

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

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

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

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

    
221
cleanup = (prefix=; . $(bin)/vegbien_dest; env schema=$(datasrc) table=$*\
222
$(bin)/csv2db) $(logInstall*Add)
223

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

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

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

    
241
cleanup: _always $(tables:%=%/cleanup) ;
242

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

    
250
##### Maps building
251

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

    
255
# Maps to (try to) build are added to this
256
maps :=
257

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

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