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
.PRECIOUS: %.last_cleanup # don't delete on error
97

    
98
make_script = ./$< >$@
99

    
100
%/: % _always ;
101

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

    
110
##### SVN
111

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

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

    
123
##### Existing maps discovery
124

    
125
sortFile := import_order.txt
126

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

    
137
anyMap := %/map.csv %/VegBIEN.csv %/unmapped_terms.csv %/new_terms.csv
138

    
139
extsFilter := $(addprefix %.,$(exts))
140
dataOnly = $(filter $(extsFilter),$(1))
141

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

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

    
149
viaMaps := $(tables:%=%/map.csv)
150

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

    
155
##### Sources
156

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

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

    
171
%/cat: _always
172
	$(catSrcs)
173

    
174
##### Staging tables installation
175

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

    
181
install: _always schema $(allInstalls:%=%/install) ;
182

    
183
uninstall: _always confirm_rm_schema rm_schema ;
184
# rm_schema will also drop all staging tables
185

    
186
reinstall: _always uninstall install ;
187

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

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

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

    
199
installLog := logs/install.log.sql
200

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

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

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

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

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

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

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

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

    
243
cleanup: _always $(tables:%=%/cleanup) ;
244

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

    
252
##### Maps building
253

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

    
257
# Maps to (try to) build are added to this
258
maps :=
259

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

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