forked from readthedocs/readthedocs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
1358 lines (1161 loc) · 41.9 KB
/
models.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
"""Models for the builds app."""
import datetime
import os.path
import re
from functools import partial
import regex
import structlog
from django.conf import settings
from django.db import models
from django.db.models import F
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
from django_extensions.db.fields import (
CreationDateTimeField,
ModificationDateTimeField,
)
from django_extensions.db.models import TimeStampedModel
from jsonfield import JSONField
from polymorphic.models import PolymorphicModel
import readthedocs.builds.automation_actions as actions
from readthedocs.builds.constants import (
BRANCH,
BUILD_STATE,
BUILD_STATE_FINISHED,
BUILD_STATE_TRIGGERED,
BUILD_STATUS_CHOICES,
BUILD_TYPES,
EXTERNAL,
GENERIC_EXTERNAL_VERSION_NAME,
GITHUB_EXTERNAL_VERSION_NAME,
GITLAB_EXTERNAL_VERSION_NAME,
INTERNAL,
LATEST,
NON_REPOSITORY_VERSIONS,
PREDEFINED_MATCH_ARGS,
PREDEFINED_MATCH_ARGS_VALUES,
STABLE,
TAG,
VERSION_TYPES,
)
from readthedocs.builds.managers import (
AutomationRuleMatchManager,
ExternalBuildManager,
ExternalVersionManager,
InternalBuildManager,
InternalVersionManager,
VersionAutomationRuleManager,
VersionManager,
)
from readthedocs.builds.querysets import (
BuildQuerySet,
RelatedBuildQuerySet,
VersionQuerySet,
)
from readthedocs.builds.utils import (
get_bitbucket_username_repo,
get_github_username_repo,
get_gitlab_username_repo,
get_vcs_url,
)
from readthedocs.builds.version_slug import VersionSlugField
from readthedocs.config import LATEST_CONFIGURATION_VERSION
from readthedocs.projects.constants import (
BITBUCKET_COMMIT_URL,
BITBUCKET_URL,
DOCTYPE_CHOICES,
GITHUB_BRAND,
GITHUB_COMMIT_URL,
GITHUB_PULL_REQUEST_COMMIT_URL,
GITHUB_URL,
GITLAB_BRAND,
GITLAB_COMMIT_URL,
GITLAB_MERGE_REQUEST_COMMIT_URL,
GITLAB_URL,
MEDIA_TYPES,
PRIVACY_CHOICES,
PRIVATE,
SPHINX,
SPHINX_HTMLDIR,
SPHINX_SINGLEHTML,
)
from readthedocs.projects.models import APIProject, Project
from readthedocs.projects.version_handling import determine_stable_version
from readthedocs.storage import build_environment_storage
log = structlog.get_logger(__name__)
class Version(TimeStampedModel):
"""Version of a ``Project``."""
# Overridden from TimeStampedModel just to allow null values.
# TODO: remove after deploy.
created = CreationDateTimeField(
_('created'),
null=True,
blank=True,
)
modified = ModificationDateTimeField(
_('modified'),
null=True,
blank=True,
)
project = models.ForeignKey(
Project,
verbose_name=_('Project'),
related_name='versions',
on_delete=models.CASCADE,
)
type = models.CharField(
_('Type'),
max_length=20,
choices=VERSION_TYPES,
default='unknown',
)
# used by the vcs backend
#: The identifier is the ID for the revision this is version is for. This
#: might be the revision number (e.g. in SVN), or the commit hash (e.g. in
#: Git). If the this version is pointing to a branch, then ``identifier``
#: will contain the branch name.
identifier = models.CharField(_('Identifier'), max_length=255)
#: This is the actual name that we got for the commit stored in
#: ``identifier``. This might be the tag or branch name like ``"v1.0.4"``.
#: However this might also hold special version names like ``"latest"``
#: and ``"stable"``.
verbose_name = models.CharField(_('Verbose Name'), max_length=255)
#: The slug is the slugified version of ``verbose_name`` that can be used
#: in the URL to identify this version in a project. It's also used in the
#: filesystem to determine how the paths for this version are called. It
#: must not be used for any other identifying purposes.
slug = VersionSlugField(
_('Slug'),
max_length=255,
populate_from='verbose_name',
)
supported = models.BooleanField(_('Supported'), default=True)
active = models.BooleanField(_('Active'), default=False)
built = models.BooleanField(_('Built'), default=False)
uploaded = models.BooleanField(_('Uploaded'), default=False)
privacy_level = models.CharField(
_('Privacy Level'),
max_length=20,
choices=PRIVACY_CHOICES,
default=settings.DEFAULT_VERSION_PRIVACY_LEVEL,
help_text=_('Level of privacy for this Version.'),
)
hidden = models.BooleanField(
_('Hidden'),
default=False,
help_text=_('Hide this version from the version (flyout) menu and search results?')
)
machine = models.BooleanField(_('Machine Created'), default=False)
# Whether the latest successful build for this version contains certain media types
has_pdf = models.BooleanField(_('Has PDF'), default=False)
has_epub = models.BooleanField(_('Has ePub'), default=False)
has_htmlzip = models.BooleanField(_('Has HTML Zip'), default=False)
documentation_type = models.CharField(
_('Documentation type'),
max_length=20,
choices=DOCTYPE_CHOICES,
default=SPHINX,
help_text=_(
'Type of documentation the version was built with.'
),
)
objects = VersionManager.from_queryset(VersionQuerySet)()
# Only include BRANCH, TAG, UNKNOWN type Versions.
internal = InternalVersionManager.from_queryset(partial(VersionQuerySet, internal_only=True))()
# Only include EXTERNAL type Versions.
external = ExternalVersionManager.from_queryset(partial(VersionQuerySet, external_only=True))()
class Meta:
unique_together = [('project', 'slug')]
ordering = ['-verbose_name']
def __str__(self):
return gettext(
'Version {version} of {project} ({pk})'.format(
version=self.verbose_name,
project=self.project,
pk=self.pk,
),
)
@property
def is_private(self):
"""
Check if the version is private (taking external versions into consideration).
The privacy level of an external version is given by
the value of ``project.external_builds_privacy_level``.
"""
if self.is_external:
return self.project.external_builds_privacy_level == PRIVATE
return self.privacy_level == PRIVATE
@property
def is_external(self):
return self.type == EXTERNAL
@property
def ref(self):
if self.slug == STABLE:
stable = determine_stable_version(
self.project.versions(manager=INTERNAL).all()
)
if stable:
return stable.slug
@property
def vcs_url(self):
version_name = self.verbose_name
if not self.is_external:
if self.slug == STABLE:
version_name = self.ref
elif self.slug == LATEST:
version_name = self.project.get_default_branch()
else:
version_name = self.slug
if 'bitbucket' in self.project.repo:
version_name = self.identifier
return get_vcs_url(
project=self.project,
version_type=self.type,
version_name=version_name,
)
@property
def last_build(self):
return self.builds.order_by('-date').first()
@property
def config(self):
"""
Proxy to the configuration of the build.
:returns: The configuration used in the last successful build.
:rtype: dict
"""
last_build = (
self.builds(manager=INTERNAL).filter(
state=BUILD_STATE_FINISHED,
success=True,
).order_by('-date')
.only('_config')
.first()
)
return last_build.config
@property
def commit_name(self):
"""
Return the branch name, the tag name or the revision identifier.
The result could be used as ref in a git repo, e.g. for linking to
GitHub, Bitbucket or GitLab.
"""
# LATEST is special as it is usually a branch but does not contain the
# name in verbose_name.
if self.slug == LATEST:
return self.project.get_default_branch()
if self.slug == STABLE:
if self.type == BRANCH:
# Special case, as we do not store the original branch name
# that the stable version works on. We can only interpolate the
# name from the commit identifier, but it's hacky.
# TODO: Refactor ``Version`` to store more actual info about
# the underlying commits.
if self.identifier.startswith('origin/'):
return self.identifier[len('origin/'):]
return self.identifier
# By now we must have handled all special versions.
if self.slug in NON_REPOSITORY_VERSIONS:
raise Exception('All special versions must be handled by now.')
if self.type in (BRANCH, TAG):
# If this version is a branch or a tag, the verbose_name will
# contain the actual name. We cannot use identifier as this might
# include the "origin/..." part in the case of a branch. A tag
# would contain the hash in identifier, which is not as pretty as
# the actual tag name.
return self.verbose_name
if self.type == EXTERNAL:
# If this version is a EXTERNAL version, the identifier will
# contain the actual commit hash. which we can use to
# generate url for a given file name
return self.identifier
# If we came that far it's not a special version
# nor a branch, tag or EXTERNAL version.
# Therefore just return the identifier to make a safe guess.
log.debug(
'TODO: Raise an exception here. Testing what cases it happens',
)
return self.identifier
def get_absolute_url(self):
"""Get absolute url to the docs of the version."""
if not self.built and not self.uploaded:
return reverse(
'project_version_detail',
kwargs={
'project_slug': self.project.slug,
'version_slug': self.slug,
},
)
external = self.type == EXTERNAL
return self.project.get_docs_url(
version_slug=self.slug,
external=external,
)
def delete(self, *args, **kwargs): # pylint: disable=arguments-differ
from readthedocs.projects.tasks.utils import clean_project_resources
log.info('Removing files for version.', version_slug=self.slug)
clean_project_resources(self.project, self)
super().delete(*args, **kwargs)
@property
def identifier_friendly(self):
"""Return display friendly identifier."""
if re.match(r'^[0-9a-f]{40}$', self.identifier, re.I):
return self.identifier[:8]
return self.identifier
@property
def is_editable(self):
return self.type == BRANCH
@property
def supports_wipe(self):
"""Return True if version is not external."""
return self.type != EXTERNAL
@property
def is_sphinx_type(self):
return self.documentation_type in {SPHINX, SPHINX_HTMLDIR, SPHINX_SINGLEHTML}
def get_subdomain_url(self):
external = self.type == EXTERNAL
return self.project.get_docs_url(
version_slug=self.slug,
lang_slug=self.project.language,
external=external,
)
def get_downloads(self, pretty=False):
project = self.project
data = {}
def prettify(k):
return k if pretty else k.lower()
if self.has_pdf:
data[prettify('PDF')] = project.get_production_media_url(
'pdf',
self.slug,
)
if self.has_htmlzip:
data[prettify('HTML')] = project.get_production_media_url(
'htmlzip',
self.slug,
)
if self.has_epub:
data[prettify('Epub')] = project.get_production_media_url(
'epub',
self.slug,
)
return data
def get_conf_py_path(self):
conf_py_path = self.project.conf_dir(self.slug)
checkout_prefix = self.project.checkout_path(self.slug)
conf_py_path = os.path.relpath(conf_py_path, checkout_prefix)
return conf_py_path
def get_build_path(self):
"""Return version build path if path exists, otherwise `None`."""
path = self.project.checkout_path(version=self.slug)
if os.path.exists(path):
return path
return None
def get_storage_paths(self):
"""
Return a list of all build artifact storage paths for this version.
:rtype: list
"""
paths = []
for type_ in MEDIA_TYPES:
paths.append(
self.project.get_storage_path(
type_=type_,
version_slug=self.slug,
include_file=False,
version_type=self.type,
)
)
return paths
def get_storage_environment_cache_path(self):
"""Return the path of the cached environment tar file."""
return build_environment_storage.join(self.project.slug, f'{self.slug}.tar')
def get_github_url(
self,
docroot,
filename,
source_suffix='.rst',
action='view',
):
"""
Return a GitHub URL for a given filename.
:param docroot: Location of documentation in repository
:param filename: Name of file
:param source_suffix: File suffix of documentation format
:param action: `view` (default) or `edit`
"""
repo_url = self.project.repo
if 'github' not in repo_url:
return ''
if not docroot:
return ''
# Normalize /docroot/
docroot = '/' + docroot.strip('/') + '/'
if action == 'view':
action_string = 'blob'
elif action == 'edit':
action_string = 'edit'
user, repo = get_github_username_repo(repo_url)
if not user and not repo:
return ''
if not filename:
# If there isn't a filename, we don't need a suffix
source_suffix = ''
return GITHUB_URL.format(
user=user,
repo=repo,
version=self.commit_name,
docroot=docroot,
path=filename,
source_suffix=source_suffix,
action=action_string,
)
def get_gitlab_url(
self,
docroot,
filename,
source_suffix='.rst',
action='view',
):
repo_url = self.project.repo
if 'gitlab' not in repo_url:
return ''
if not docroot:
return ''
# Normalize /docroot/
docroot = '/' + docroot.strip('/') + '/'
if action == 'view':
action_string = 'blob'
elif action == 'edit':
action_string = 'edit'
user, repo = get_gitlab_username_repo(repo_url)
if not user and not repo:
return ''
if not filename:
# If there isn't a filename, we don't need a suffix
source_suffix = ''
return GITLAB_URL.format(
user=user,
repo=repo,
version=self.commit_name,
docroot=docroot,
path=filename,
source_suffix=source_suffix,
action=action_string,
)
def get_bitbucket_url(self, docroot, filename, source_suffix='.rst'):
repo_url = self.project.repo
if 'bitbucket' not in repo_url:
return ''
if not docroot:
return ''
# Normalize /docroot/
docroot = '/' + docroot.strip('/') + '/'
user, repo = get_bitbucket_username_repo(repo_url)
if not user and not repo:
return ''
if not filename:
# If there isn't a filename, we don't need a suffix
source_suffix = ''
return BITBUCKET_URL.format(
user=user,
repo=repo,
version=self.commit_name,
docroot=docroot,
path=filename,
source_suffix=source_suffix,
)
class APIVersion(Version):
"""
Version proxy model for API data deserialization.
This replaces the pattern where API data was deserialized into a mocked
:py:class:`Version` object.
This pattern was confusing, as it was not explicit
as to what form of object you were working with -- API backed or database
backed.
This model preserves the Version model methods, allowing for overrides on
model field differences. This model pattern will generally only be used on
builder instances, where we are interacting solely with API data.
"""
project = None
class Meta:
proxy = True
def __init__(self, *args, **kwargs):
self.project = APIProject(**kwargs.pop('project', {}))
# These fields only exist on the API return, not on the model, so we'll
# remove them to avoid throwing exceptions due to unexpected fields
for key in ['resource_uri', 'absolute_url', 'downloads']:
try:
del kwargs[key]
except KeyError:
pass
super().__init__(*args, **kwargs)
def save(self, *args, **kwargs): # pylint: disable=arguments-differ
return 0
class Build(models.Model):
"""Build data."""
project = models.ForeignKey(
Project,
verbose_name=_('Project'),
related_name='builds',
on_delete=models.CASCADE,
)
version = models.ForeignKey(
Version,
verbose_name=_('Version'),
null=True,
related_name='builds',
on_delete=models.SET_NULL,
)
type = models.CharField(
_('Type'),
max_length=55,
choices=BUILD_TYPES,
default='html',
)
# Describe build state as where in the build process the build is. This
# allows us to show progression to the user in the form of a progress bar
# or in the build listing
state = models.CharField(
_('State'),
max_length=55,
choices=BUILD_STATE,
default='finished',
db_index=True,
)
# Describe status as *why* the build is in a particular state. It is
# helpful for communicating more details about state to the user, but it
# doesn't help describe progression
# https://github.com/readthedocs/readthedocs.org/pull/7123#issuecomment-635065807
status = models.CharField(
_('Status'),
choices=BUILD_STATUS_CHOICES,
max_length=32,
null=True,
default=None,
blank=True,
)
date = models.DateTimeField(_('Date'), auto_now_add=True, db_index=True)
success = models.BooleanField(_('Success'), default=True)
# TODO: remove these fields (setup, setup_error, output, error, exit_code)
# since they are not used anymore in the new implementation and only really
# old builds (>5 years ago) only were using these fields.
setup = models.TextField(_('Setup'), null=True, blank=True)
setup_error = models.TextField(_('Setup error'), null=True, blank=True)
output = models.TextField(_('Output'), default='', blank=True)
error = models.TextField(_('Error'), default='', blank=True)
exit_code = models.IntegerField(_('Exit code'), null=True, blank=True)
# Metadata from were the build happened.
# This is also used after the version is deleted.
commit = models.CharField(
_('Commit'),
max_length=255,
null=True,
blank=True,
)
version_slug = models.CharField(
_('Version slug'),
max_length=255,
null=True,
blank=True,
)
version_name = models.CharField(
_('Version name'),
max_length=255,
null=True,
blank=True,
)
version_type = models.CharField(
_('Version type'),
max_length=32,
choices=VERSION_TYPES,
null=True,
blank=True,
)
_config = JSONField(_('Configuration used in the build'), default=dict)
_config_json = models.JSONField(
_('Configuration used in the build'),
null=True,
blank=True,
)
length = models.IntegerField(_('Build Length'), null=True, blank=True)
builder = models.CharField(
_('Builder'),
max_length=255,
null=True,
blank=True,
)
cold_storage = models.BooleanField(
_('Cold Storage'),
null=True,
help_text='Build steps stored outside the database.',
)
# Managers
objects = BuildQuerySet.as_manager()
# Only include BRANCH, TAG, UNKNOWN type Version builds.
internal = InternalBuildManager.from_queryset(BuildQuerySet)()
# Only include EXTERNAL type Version builds.
external = ExternalBuildManager.from_queryset(BuildQuerySet)()
CONFIG_KEY = '__config'
class Meta:
ordering = ['-date']
get_latest_by = 'date'
index_together = [
['version', 'state', 'type'],
['date', 'id'],
]
indexes = [
models.Index(fields=['project', 'date']),
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._config_changed = False
@property
def previous(self):
"""
Returns the previous build to the current one.
Matching the project and version.
"""
date = self.date or timezone.now()
if self.project is not None and self.version is not None:
return (
Build.objects.filter(
project=self.project,
version=self.version,
date__lt=date,
).order_by('-date').first()
)
return None
@property
def config(self):
"""
Get the config used for this build.
Since we are saving the config into the JSON field only when it differs
from the previous one, this helper returns the correct JSON used in this
Build object (it could be stored in this object or one of the previous
ones).
"""
# TODO: now that we are using a proper JSONField here, we could
# probably change this field to be a ForeignKey to avoid repeating the
# config file over and over again and re-use them to save db data as
# well
if self.CONFIG_KEY in self._config:
return (
Build.objects
.only('_config')
.get(pk=self._config[self.CONFIG_KEY])
._config
)
return self._config
@config.setter
def config(self, value):
"""
Set `_config` to value.
`_config` should never be set directly from outside the class.
"""
self._config = value
self._config_changed = True
def save(self, *args, **kwargs): # noqa
"""
Save object.
To save space on the db we only save the config if it's different
from the previous one.
If the config is the same, we save the pk of the object
that has the **real** config under the `CONFIG_KEY` key.
"""
if self.pk is None or self._config_changed:
previous = self.previous
if (
previous is not None
and self._config
and self._config == previous.config
):
previous_pk = previous._config.get(self.CONFIG_KEY, previous.pk)
self._config = {self.CONFIG_KEY: previous_pk}
if self.version:
self.version_name = self.version.verbose_name
self.version_slug = self.version.slug
self.version_type = self.version.type
# TODO: delete copying config after deploy
# Copy `_config` into the new `_config_json` JSONField
self._config_json = self._config
super().save(*args, **kwargs)
self._config_changed = False
def __str__(self):
return gettext(
'Build {project} for {usernames} ({pk})'.format(
project=self.project,
usernames=' '.join(
self.project.users.all().values_list('username', flat=True),
),
pk=self.pk,
),
)
def get_absolute_url(self):
return reverse('builds_detail', args=[self.project.slug, self.pk])
def get_full_url(self):
"""
Get full url of the build including domain.
Example: https://readthedocs.org/projects/pip/builds/99999999/
"""
scheme = 'http' if settings.DEBUG else 'https'
full_url = '{scheme}://{domain}{absolute_url}'.format(
scheme=scheme,
domain=settings.PRODUCTION_DOMAIN,
absolute_url=self.get_absolute_url()
)
return full_url
def get_version_name(self):
if self.version:
return self.version.verbose_name
return self.version_name
def get_version_slug(self):
if self.version:
return self.version.verbose_name
return self.version_name
def get_version_type(self):
if self.version:
return self.version.type
return self.version_type
@property
def vcs_url(self):
if self.version:
return self.version.vcs_url
return get_vcs_url(
project=self.project,
version_type=self.get_version_type(),
version_name=self.get_version_name(),
)
def get_commit_url(self):
"""Return the commit URL."""
repo_url = self.project.repo
if self.is_external:
if 'github' in repo_url:
user, repo = get_github_username_repo(repo_url)
if not user and not repo:
return ''
return GITHUB_PULL_REQUEST_COMMIT_URL.format(
user=user,
repo=repo,
number=self.get_version_name(),
commit=self.commit
)
if 'gitlab' in repo_url:
user, repo = get_gitlab_username_repo(repo_url)
if not user and not repo:
return ''
return GITLAB_MERGE_REQUEST_COMMIT_URL.format(
user=user,
repo=repo,
number=self.get_version_name(),
commit=self.commit
)
# TODO: Add External Version Commit URL for BitBucket.
else:
if 'github' in repo_url:
user, repo = get_github_username_repo(repo_url)
if not user and not repo:
return ''
return GITHUB_COMMIT_URL.format(
user=user,
repo=repo,
commit=self.commit
)
if 'gitlab' in repo_url:
user, repo = get_gitlab_username_repo(repo_url)
if not user and not repo:
return ''
return GITLAB_COMMIT_URL.format(
user=user,
repo=repo,
commit=self.commit
)
if 'bitbucket' in repo_url:
user, repo = get_bitbucket_username_repo(repo_url)
if not user and not repo:
return ''
return BITBUCKET_COMMIT_URL.format(
user=user,
repo=repo,
commit=self.commit
)
return None
@property
def finished(self):
"""Return if build has a finished state."""
return self.state == BUILD_STATE_FINISHED
@property
def is_stale(self):
"""Return if build state is triggered & date more than 5m ago."""
mins_ago = timezone.now() - datetime.timedelta(minutes=5)
return self.state == BUILD_STATE_TRIGGERED and self.date < mins_ago
@property
def is_external(self):
type = self.version_type
if self.version:
type = self.version.type
return type == EXTERNAL
@property
def can_rebuild(self):
"""
Check if external build can be rebuilt.
Rebuild can be done only if the build is external,
build version is active and
it's the latest build for the version.
see https://github.com/readthedocs/readthedocs.org/pull/6995#issuecomment-852918969
"""
if self.is_external:
is_latest_build = (
self == Build.objects.filter(
project=self.project,
version=self.version
).only('id').first()
)
return self.version and self.version.active and is_latest_build
return False
@property
def external_version_name(self):
if self.is_external:
if self.project.git_provider_name == GITHUB_BRAND:
return GITHUB_EXTERNAL_VERSION_NAME
if self.project.git_provider_name == GITLAB_BRAND:
return GITLAB_EXTERNAL_VERSION_NAME
# TODO: Add External Version Name for BitBucket.
return GENERIC_EXTERNAL_VERSION_NAME
return None
def using_latest_config(self):
return int(self.config.get('version', '1')) == LATEST_CONFIGURATION_VERSION
def reset(self):
"""
Reset the build so it can be re-used when re-trying.
Dates and states are usually overridden by the build,
we care more about deleting the commands.
"""
self.state = BUILD_STATE_TRIGGERED
self.status = ''
self.success = True
self.output = ''
self.error = ''
self.exit_code = None
self.builder = ''
self.cold_storage = False
self.commands.all().delete()
self.save()
class BuildCommandResultMixin:
"""
Mixin for common command result methods/properties.
Shared methods between the database model :py:class:`BuildCommandResult` and
non-model respresentations of build command results from the API
"""
@property
def successful(self):
"""Did the command exit with a successful exit code."""
return self.exit_code == 0
@property
def failed(self):
"""
Did the command exit with a failing exit code.
Helper for inverse of :py:meth:`successful`