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
# Include comment column so commented mappings are never removed
271
else
272
%/map.csv: _always
273
	$(if $(wildcard $@),,$(if $(nonXml),$(mkSrcMap)))
274
	+$(selfMake) $(@:%/map.csv=%/.map.csv.last_cleanup)
275
endif
276

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

    
281
maps: $(maps) _always ;
282

    
283
all += $(maps)
284

    
285
##### Maps validation
286

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

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

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

    
300
termsSubdirs := $(tables)
301

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

    
304
##### External dependencies
305

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

    
310
##### Mapping
311

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

    
316
##### Import to VegBIEN
317

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

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

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

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

    
336
##### Log files from import
337

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

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

    
343
##### Verification of import
344

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

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

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

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

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

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

    
370
##### Editing import
371

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

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

    
380
##### Testing
381

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

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

    
409
tests :=
410

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

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

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

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

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

    
430
test: _always $(testOutputs) ;
431

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

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

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

    
441
##### Documentation
442

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

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