-
Notifications
You must be signed in to change notification settings - Fork 308
/
builder.py
1258 lines (1110 loc) · 42.7 KB
/
builder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import hashlib
import os
import shutil
import sqlite3
import stat
import sys
import tempfile
from collections import deque
from collections import namedtuple
from contextlib import contextmanager
from itertools import chain
import click
from lektor.build_programs import builtin_build_programs
from lektor.buildfailures import FailureController
from lektor.constants import PRIMARY_ALT
from lektor.context import Context
from lektor.reporter import reporter
from lektor.sourcesearch import find_files
from lektor.utils import fs_enc
from lektor.utils import process_extra_flags
from lektor.utils import prune_file_and_folder
def create_tables(con):
can_disable_rowid = (3, 8, 2) <= sqlite3.sqlite_version_info
if can_disable_rowid:
without_rowid = "without rowid"
else:
without_rowid = ""
try:
con.execute(
f"""
create table if not exists artifacts (
artifact text,
source text,
source_mtime integer,
source_size integer,
source_checksum text,
is_dir integer,
is_primary_source integer,
primary key (artifact, source)
) {without_rowid};
"""
)
con.execute(
"""
create index if not exists artifacts_source on artifacts (
source
);
"""
)
con.execute(
f"""
create table if not exists artifact_config_hashes (
artifact text,
config_hash text,
primary key (artifact)
) {without_rowid};
"""
)
con.execute(
f"""
create table if not exists dirty_sources (
source text,
primary key (source)
) {without_rowid};
"""
)
con.execute(
f"""
create table if not exists source_info (
path text,
alt text,
lang text,
type text,
source text,
title text,
primary key (path, alt, lang)
) {without_rowid};
"""
)
finally:
con.close()
class BuildState:
def __init__(self, builder, path_cache):
self.builder = builder
self.named_temporaries = set()
self.updated_artifacts = []
self.failed_artifacts = []
self.path_cache = path_cache
@property
def pad(self):
"""The pad for this buildstate."""
return self.builder.pad
@property
def env(self):
"""The environment backing this buildstate."""
return self.builder.env
@property
def config(self):
"""The config for this buildstate."""
return self.builder.pad.db.config
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
self.close()
def close(self):
for fn in self.named_temporaries:
try:
os.remove(fn)
except OSError:
pass
def notify_failure(self, artifact, exc_info):
"""Notify about a failure. This marks a failed artifact and stores
a failure.
"""
self.failed_artifacts.append(artifact)
self.builder.failure_controller.store_failure(artifact.artifact_name, exc_info)
reporter.report_failure(artifact, exc_info)
def make_named_temporary(self, identifier=None):
"""Creates a named temporary file and returns the filename for it.
This can be usedful in some scenarious when building with external
tools.
"""
tmpdir = os.path.join(self.builder.meta_path, "tmp")
try:
os.makedirs(tmpdir)
except OSError:
pass
fn = os.path.join(
dir,
"nt-%s-%s.tmp" % (identifier or "generic", os.urandom(20).encode("hex")),
)
self.named_temporaries.add(fn)
return fn
def get_file_info(self, filename):
if filename:
return self.path_cache.get_file_info(filename)
return None
def to_source_filename(self, filename):
return self.path_cache.to_source_filename(filename)
def get_virtual_source_info(self, virtual_source_path):
virtual_source = self.pad.get(virtual_source_path)
if not virtual_source:
return VirtualSourceInfo(virtual_source_path, None, None)
mtime = virtual_source.get_mtime(self.path_cache)
checksum = virtual_source.get_checksum(self.path_cache)
return VirtualSourceInfo(virtual_source_path, mtime, checksum)
def connect_to_database(self):
"""Returns a database connection for the build state db."""
return self.builder.connect_to_database()
def get_destination_filename(self, artifact_name):
"""Returns the destination filename for an artifact name."""
return os.path.join(
self.builder.destination_path,
artifact_name.strip("/").replace("/", os.path.sep),
)
def artifact_name_from_destination_filename(self, filename):
"""Returns the artifact name for a destination filename."""
dst = self.builder.destination_path
filename = os.path.join(dst, filename)
if filename.startswith(dst):
filename = filename[len(dst) :].lstrip(os.path.sep)
if os.path.altsep:
filename = filename.lstrip(os.path.altsep)
return filename.replace(os.path.sep, "/")
def new_artifact(
self, artifact_name, sources=None, source_obj=None, extra=None, config_hash=None
):
"""Creates a new artifact and returns it."""
dst_filename = self.get_destination_filename(artifact_name)
key = self.artifact_name_from_destination_filename(dst_filename)
return Artifact(
self,
key,
dst_filename,
sources,
source_obj=source_obj,
extra=extra,
config_hash=config_hash,
)
def artifact_exists(self, artifact_name):
"""Given an artifact name this checks if it was already produced."""
dst_filename = self.get_destination_filename(artifact_name)
return os.path.exists(dst_filename)
def get_artifact_dependency_infos(self, artifact_name, sources):
con = self.connect_to_database()
try:
cur = con.cursor()
rv = list(self._iter_artifact_dependency_infos(cur, artifact_name, sources))
finally:
con.close()
return rv
def _iter_artifact_dependency_infos(self, cur, artifact_name, sources):
"""This iterates over all dependencies as file info objects."""
cur.execute(
"""
select source, source_mtime, source_size,
source_checksum, is_dir
from artifacts
where artifact = ?
""",
[artifact_name],
)
rv = cur.fetchall()
found = set()
for path, mtime, size, checksum, is_dir in rv:
if "@" in path:
yield path, VirtualSourceInfo(path, mtime, checksum)
else:
file_info = FileInfo(
self.env, path, mtime, size, checksum, bool(is_dir)
)
filename = self.to_source_filename(file_info.filename)
found.add(filename)
yield filename, file_info
# In any case we also iterate over our direct sources, even if the
# build state does not know about them yet. This can be caused by
# an initial build or a change in original configuration.
for source in sources:
filename = self.to_source_filename(source)
if filename not in found:
yield source, None
def write_source_info(self, info):
"""Writes the source info into the database. The source info is
an instance of :class:`lektor.build_programs.SourceInfo`.
"""
reporter.report_write_source_info(info)
source = self.to_source_filename(info.filename)
con = self.connect_to_database()
try:
cur = con.cursor()
for lang, title in info.title_i18n.items():
cur.execute(
"""
insert or replace into source_info
(path, alt, lang, type, source, title)
values (?, ?, ?, ?, ?, ?)
""",
[info.path, info.alt, lang, info.type, source, title],
)
con.commit()
finally:
con.close()
def prune_source_infos(self):
"""Remove all source infos of files that no longer exist."""
MAX_VARS = 999 # Default SQLITE_MAX_VARIABLE_NUMBER.
con = self.connect_to_database()
to_clean = []
try:
cur = con.cursor()
cur.execute(
"""
select distinct source from source_info
"""
)
for (source,) in cur.fetchall():
fs_path = os.path.join(self.env.root_path, source)
if not os.path.exists(fs_path):
to_clean.append(source)
if to_clean:
for i in range(0, len(to_clean), MAX_VARS):
chunk = to_clean[i : i + MAX_VARS]
cur.execute(
"""
delete from source_info
where source in (%s)
"""
% ", ".join(["?"] * len(chunk)),
chunk,
)
con.commit()
finally:
con.close()
for source in to_clean:
reporter.report_prune_source_info(source)
def remove_artifact(self, artifact_name):
"""Removes an artifact from the build state."""
con = self.connect_to_database()
try:
cur = con.cursor()
cur.execute(
"""
delete from artifacts where artifact = ?
""",
[artifact_name],
)
con.commit()
finally:
con.close()
def _any_sources_are_dirty(self, cur, sources):
"""Given a list of sources this checks if any of them are marked
as dirty.
"""
sources = [self.to_source_filename(x) for x in sources]
if not sources:
return False
cur.execute(
"""
select source from dirty_sources where source in (%s) limit 1
"""
% ", ".join(["?"] * len(sources)),
sources,
)
return cur.fetchone() is not None
@staticmethod
def _get_artifact_config_hash(cur, artifact_name):
"""Returns the artifact's config hash."""
cur.execute(
"""
select config_hash from artifact_config_hashes
where artifact = ?
""",
[artifact_name],
)
rv = cur.fetchone()
return rv[0] if rv else None
def check_artifact_is_current(self, artifact_name, sources, config_hash):
con = self.connect_to_database()
cur = con.cursor()
try:
# The artifact config changed
if config_hash != self._get_artifact_config_hash(cur, artifact_name):
return False
# If one of our source files is explicitly marked as dirty in the
# build state, we are not current.
if self._any_sources_are_dirty(cur, sources):
return False
# If we do have an already existing artifact, we need to check if
# any of the source files we depend on changed.
for _, info in self._iter_artifact_dependency_infos(
cur, artifact_name, sources
):
# if we get a missing source info it means that we never
# saw this before. This means we need to build it.
if info is None:
return False
if isinstance(info, VirtualSourceInfo):
new_vinfo = self.get_virtual_source_info(info.path)
if not info.unchanged(new_vinfo):
return False
# If the file info is different, then it clearly changed.
elif not info.unchanged(self.get_file_info(info.filename)):
return False
return True
finally:
con.close()
def iter_unreferenced_artifacts(self, all=False):
"""Finds all unreferenced artifacts in the build folder and yields
them.
"""
dst = os.path.join(self.builder.destination_path)
con = self.connect_to_database()
cur = con.cursor()
try:
for dirpath, dirnames, filenames in os.walk(dst):
dirnames[:] = [
x for x in dirnames if not self.env.is_ignored_artifact(x)
]
for filename in filenames:
if self.env.is_ignored_artifact(filename):
continue
full_path = os.path.join(dst, dirpath, filename)
artifact_name = self.artifact_name_from_destination_filename(
full_path
)
if all:
yield artifact_name
continue
cur.execute(
"""
select source from artifacts
where artifact = ?
and is_primary_source""",
[artifact_name],
)
sources = set(x[0] for x in cur.fetchall())
# It's a bad artifact if there are no primary sources
# or the primary sources do not exist.
if not sources or not any(
self.get_file_info(x).exists for x in sources
):
yield artifact_name
finally:
con.close()
def iter_artifacts(self):
"""Iterates over all artifact and their file infos.."""
con = self.connect_to_database()
try:
cur = con.cursor()
cur.execute(
"""
select distinct artifact from artifacts order by artifact
"""
)
rows = cur.fetchall()
con.close()
for (artifact_name,) in rows:
path = self.get_destination_filename(artifact_name)
info = FileInfo(self.builder.env, path)
if info.exists:
yield artifact_name, info
finally:
con.close()
def vacuum(self):
"""Vacuums the build db."""
con = self.connect_to_database()
try:
con.execute("vacuum")
finally:
con.close()
def _describe_fs_path_for_checksum(path):
"""Given a file system path this returns a basic description of what
this is. This is used for checksum hashing on directories.
"""
# This is not entirely correct as it does not detect changes for
# contents from alternatives. However for the moment it's good
# enough.
if os.path.isfile(path):
return b"\x01"
if os.path.isfile(os.path.join(path, "contents.lr")):
return b"\x02"
if os.path.isdir(path):
return b"\x03"
return b"\x00"
class FileInfo:
"""A file info object holds metainformation of a file so that changes
can be detected easily.
"""
def __init__(
self, env, filename, mtime=None, size=None, checksum=None, is_dir=None
):
self.env = env
self.filename = filename
if mtime is not None and size is not None and is_dir is not None:
self._stat = (mtime, size, is_dir)
else:
self._stat = None
self._checksum = checksum
def _get_stat(self):
rv = self._stat
if rv is not None:
return rv
try:
st = os.stat(self.filename)
mtime = int(st.st_mtime)
if stat.S_ISDIR(st.st_mode):
size = len(os.listdir(self.filename))
is_dir = True
else:
size = int(st.st_size)
is_dir = False
rv = mtime, size, is_dir
except OSError:
rv = 0, -1, False
self._stat = rv
return rv
@property
def mtime(self):
"""The timestamp of the last modification."""
return self._get_stat()[0]
@property
def size(self):
"""The size of the file in bytes. If the file is actually a
dictionary then the size is actually the number of files in it.
"""
return self._get_stat()[1]
@property
def is_dir(self):
"""Is this a directory?"""
return self._get_stat()[2]
@property
def exists(self):
return self.size >= 0
@property
def checksum(self):
"""The checksum of the file or directory."""
rv = self._checksum
if rv is not None:
return rv
try:
h = hashlib.sha1()
if os.path.isdir(self.filename):
h.update(b"DIR\x00")
for filename in sorted(os.listdir(self.filename)):
if self.env.is_uninteresting_source_name(filename):
continue
if isinstance(filename, str):
filename = filename.encode("utf-8")
h.update(filename)
h.update(
_describe_fs_path_for_checksum(
os.path.join(self.filename, filename.decode("utf-8"))
)
)
h.update(b"\x00")
else:
with open(self.filename, "rb") as f:
while 1:
chunk = f.read(16 * 1024)
if not chunk:
break
h.update(chunk)
checksum = h.hexdigest()
except (OSError, IOError):
checksum = "0" * 40
self._checksum = checksum
return checksum
@property
def filename_and_checksum(self):
"""Like 'filename:checksum'."""
return "%s:%s" % (self.filename, self.checksum)
def unchanged(self, other):
"""Given another file info checks if the are similar enough to
not consider it changed.
"""
if not isinstance(other, FileInfo):
raise TypeError("'other' must be a FileInfo, not %r" % other)
# If mtime and size match, we skip the checksum comparison which
# might require a file read which we do not want in those cases.
# (Except if it's a directory, then we won't do that)
if not self.is_dir and self.mtime == other.mtime and self.size == other.size:
return True
return self.checksum == other.checksum
class VirtualSourceInfo:
def __init__(self, path, mtime=None, checksum=None):
self.path = path
self.mtime = mtime
self.checksum = checksum
def unchanged(self, other):
if not isinstance(other, VirtualSourceInfo):
raise TypeError("'other' must be a VirtualSourceInfo, not %r" % other)
if self.path != other.path:
raise ValueError(
"trying to compare mismatched virtual paths: "
"%r.unchanged(%r)" % (self, other)
)
return (self.mtime, self.checksum) == (other.mtime, other.checksum)
def __repr__(self):
return "VirtualSourceInfo(%r, %r, %r)" % (self.path, self.mtime, self.checksum)
artifacts_row = namedtuple(
"artifacts_row",
[
"artifact",
"source",
"source_mtime",
"source_size",
"source_checksum",
"is_dir",
"is_primary_source",
],
)
class Artifact:
"""This class represents a build artifact."""
def __init__(
self,
build_state,
artifact_name,
dst_filename,
sources,
source_obj=None,
extra=None,
config_hash=None,
):
self.build_state = build_state
self.artifact_name = artifact_name
self.dst_filename = dst_filename
self.sources = sources
self.in_update_block = False
self.updated = False
self.source_obj = source_obj
self.extra = extra
self.config_hash = config_hash
self._new_artifact_file = None
self._pending_update_ops = []
def __repr__(self):
return "<%s %r>" % (
self.__class__.__name__,
self.dst_filename,
)
@property
def is_current(self):
"""Checks if the artifact is current."""
# If the artifact does not exist, we're not current.
if not os.path.isfile(self.dst_filename):
return False
return self.build_state.check_artifact_is_current(
self.artifact_name, self.sources, self.config_hash
)
def get_dependency_infos(self):
return self.build_state.get_artifact_dependency_infos(
self.artifact_name, self.sources
)
def ensure_dir(self):
"""Creates the directory if it does not exist yet."""
dst_dir = os.path.dirname(self.dst_filename)
try:
os.makedirs(dst_dir)
except OSError:
pass
def open(self, mode="rb", encoding=None, ensure_dir=None):
"""Opens the artifact for reading or writing. This is transaction
safe by writing into a temporary file and by moving it over the
actual source in commit.
"""
if ensure_dir is None:
ensure_dir = "r" not in mode
if ensure_dir:
self.ensure_dir()
if "r" in mode:
fn = self._new_artifact_file or self.dst_filename
return open(fn, mode=mode, encoding=encoding)
if self._new_artifact_file is None:
fd, tmp_filename = tempfile.mkstemp(
dir=os.path.dirname(self.dst_filename), prefix=".__trans"
)
os.chmod(tmp_filename, 0o644)
self._new_artifact_file = tmp_filename
return os.fdopen(fd, mode)
return open(self._new_artifact_file, mode=mode, encoding=encoding)
def replace_with_file(self, filename, ensure_dir=True, copy=False):
"""This is similar to open but it will move over a given named
file. The file will be deleted by a rollback or renamed by a
commit.
"""
if ensure_dir:
self.ensure_dir()
if copy:
with self.open("wb") as df:
with open(filename, "rb") as sf:
shutil.copyfileobj(sf, df)
else:
self._new_artifact_file = filename
def render_template_into(self, template_name, this, **extra):
"""Renders a template into the artifact. The default behavior is to
catch the error and render it into the template with a failure marker.
"""
rv = self.build_state.env.render_template(
template_name, self.build_state.pad, this=this, **extra
)
with self.open("wb") as f:
f.write(rv.encode("utf-8") + b"\n")
def _memorize_dependencies(
self, dependencies=None, virtual_dependencies=None, for_failure=False
):
"""This updates the dependencies recorded for the artifact based
on the direct sources plus the provided dependencies. This also
stores the config hash.
This normally defers the operation until commit but the `for_failure`
more will immediately commit into a new connection.
"""
def operation(con):
primary_sources = set(
self.build_state.to_source_filename(x) for x in self.sources
)
seen = set()
rows = []
for source in chain(self.sources, dependencies or ()):
source = self.build_state.to_source_filename(source)
if source in seen:
continue
info = self.build_state.get_file_info(source)
rows.append(
artifacts_row(
artifact=self.artifact_name,
source=source,
source_mtime=info.mtime,
source_size=info.size,
source_checksum=info.checksum,
is_dir=info.is_dir,
is_primary_source=source in primary_sources,
)
)
seen.add(source)
for v_source in virtual_dependencies or ():
checksum = v_source.get_checksum(self.build_state.path_cache)
mtime = v_source.get_mtime(self.build_state.path_cache)
rows.append(
artifacts_row(
artifact=self.artifact_name,
source=v_source.path,
source_mtime=mtime,
source_size=None,
source_checksum=checksum,
is_dir=False,
is_primary_source=False,
)
)
reporter.report_dependencies(rows)
cur = con.cursor()
if not for_failure:
cur.execute(
"delete from artifacts where artifact = ?", [self.artifact_name]
)
if rows:
cur.executemany(
"""
insert or replace into artifacts (
artifact, source, source_mtime, source_size,
source_checksum, is_dir, is_primary_source)
values (?, ?, ?, ?, ?, ?, ?)
""",
rows,
)
if self.config_hash is None:
cur.execute(
"""
delete from artifact_config_hashes
where artifact = ?
""",
[self.artifact_name],
)
else:
cur.execute(
"""
insert or replace into artifact_config_hashes
(artifact, config_hash) values (?, ?)
""",
[self.artifact_name, self.config_hash],
)
cur.close()
if for_failure:
con = self.build_state.connect_to_database()
try:
operation(con)
except: # noqa
con.rollback()
con.close()
raise
con.commit()
con.close()
else:
self._auto_deferred_update_operation(operation)
def clear_dirty_flag(self):
"""Clears the dirty flag for all sources."""
def operation(con):
sources = [self.build_state.to_source_filename(x) for x in self.sources]
cur = con.cursor()
cur.execute(
"""
delete from dirty_sources where source in (%s)
"""
% ", ".join(["?"] * len(sources)),
list(sources),
)
cur.close()
reporter.report_dirty_flag(False)
self._auto_deferred_update_operation(operation)
def set_dirty_flag(self):
"""Given a list of artifacts this will mark all of their sources
as dirty so that they will be rebuilt next time.
"""
def operation(con):
sources = set()
for source in self.sources:
sources.add(self.build_state.to_source_filename(source))
if not sources:
return
cur = con.cursor()
cur.executemany(
"""
insert or replace into dirty_sources (source) values (?)
""",
[(x,) for x in sources],
)
cur.close()
reporter.report_dirty_flag(True)
self._auto_deferred_update_operation(operation)
def _auto_deferred_update_operation(self, f):
"""Helper that defers an update operation when inside an update
block to a later point. Otherwise it's auto committed.
"""
if self.in_update_block:
self._pending_update_ops.append(f)
return
con = self.build_state.connect_to_database()
try:
f(con)
except: # noqa
con.rollback()
raise
con.commit()
@contextmanager
def update(self):
"""Opens the artifact for modifications. At the start the dirty
flag is cleared out and if the commit goes through without errors it
stays cleared. The setting of the dirty flag has to be done by the
caller however based on the `exc_info` on the context.
"""
ctx = self.begin_update()
try:
yield ctx
except: # pylint: disable=bare-except # noqa
exc_info = sys.exc_info()
self.finish_update(ctx, exc_info)
else:
self.finish_update(ctx)
def begin_update(self):
"""Begins an update block."""
if self.in_update_block:
raise RuntimeError("Artifact is already open for updates.")
self.updated = False
ctx = Context(self)
ctx.push()
self.in_update_block = True
self.clear_dirty_flag()
return ctx
def _commit(self):
con = None
try:
for op in self._pending_update_ops:
if con is None:
con = self.build_state.connect_to_database()
op(con)
if self._new_artifact_file is not None:
os.replace(self._new_artifact_file, self.dst_filename)
self._new_artifact_file = None
if con is not None:
con.commit()
con.close()
con = None
self.build_state.updated_artifacts.append(self)
self.build_state.builder.failure_controller.clear_failure(
self.artifact_name
)
finally:
if con is not None:
con.rollback()
con.close()
def _rollback(self):
if self._new_artifact_file is not None:
try:
os.remove(self._new_artifact_file)
except OSError:
pass
self._new_artifact_file = None
self._pending_update_ops = []
def finish_update(self, ctx, exc_info=None):
"""Finalizes an update block."""
if not self.in_update_block:
raise RuntimeError("Artifact is not open for updates.")
ctx.pop()
self.in_update_block = False
self.updated = True
# If there was no error, we memoize the dependencies like normal
# and then commit our transaction.
if exc_info is None:
self._memorize_dependencies(
ctx.referenced_dependencies,
ctx.referenced_virtual_dependencies.values(),
)
self._commit()
return
# If an error happened we roll back all changes and record the
# stacktrace in two locations: we record it on the context so
# that a called can respond to our failure, and we also persist
# it so that the dev server can render it out later.
self._rollback()
# This is a special form of dependency memorization where we do
# not prune old dependencies and we just append new ones and we
# use a new database connection that immediately commits.
self._memorize_dependencies(
ctx.referenced_dependencies,
ctx.referenced_virtual_dependencies.values(),
for_failure=True,
)
ctx.exc_info = exc_info
self.build_state.notify_failure(self, exc_info)
class PathCache:
def __init__(self, env):
self.file_info_cache = {}
self.source_filename_cache = {}
self.env = env
def to_source_filename(self, filename):
"""Given a path somewhere below the environment this will return the
short source filename that is used internally. Unlike the given
path, this identifier is also platform independent.
"""