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
.PRECIOUS: %/.map.csv.last_cleanup
271
else
272
%/map.csv: _always
273
	$(if $(wildcard $@),,$(if $(nonXml),$(mkSrcMap)))
274
	+$(selfMake) $(@:%/map.csv=%/.map.csv.last_cleanup)
275
.PRECIOUS: %/map.csv
276
endif
277

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

    
282
maps: $(maps) _always ;
283

    
284
all += $(maps)
285

    
286
##### Maps validation
287

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

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

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

    
301
termsSubdirs := $(tables)
302

    
303
include $(root)/lib/mappings.Makefile
304

    
305
##### External dependencies
306

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

    
311
##### Mapping
312

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

    
317
##### Import to VegBIEN
318

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

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

    
330
import: $(tables:%=%/import) _always ;
331

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

    
337
##### Log files from import
338

    
339
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
340

    
341
rm_logs: _always
342
	$(RM) $(logs)
343

    
344
##### Verification of import
345

    
346
verify: $(tables:%=%/verify) _always ;
347

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

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

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

    
366
all += $(wildcard verify/*.out)
367

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

    
371
##### Editing import
372

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

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

    
381
##### Testing
382

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

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

    
410
tests :=
411

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

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

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

    
427
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
428

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

    
431
test: _always $(testOutputs) ;
432

    
433
all += $(wildcard %/test*.xml)
434

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

    
439
accept-all: _always
440
	+yes|$(selfMake) test
441

    
442
##### Documentation
443

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

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