Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update readthedocs-environment.json file when env vars are added/deleted #5540

Merged
merged 14 commits into from Apr 22, 2019
57 changes: 56 additions & 1 deletion readthedocs/projects/models.py
Expand Up @@ -2,6 +2,7 @@

import fnmatch
import logging
import json
import os
import re
from urllib.parse import urlparse
Expand Down Expand Up @@ -1401,6 +1402,60 @@ class EnvironmentVariable(TimeStampedModel, models.Model):
def __str__(self):
return self.name

def _get_last_built_version(self):
"""Returns the version that was last built."""
version = self.project.versions.all().order_by('-builds__date').first()
return version

def _get_env_json_paths(self, version):
"""
Returns the list containing paths to ``readthedocs-environment.json`` file.

It returns paths for both python and conda environment.
"""
paths = [
os.path.join(
self.project.doc_path,
'conda', # if conda env
version.slug,
'readthedocs-environment.json'
),
os.path.join(
self.project.doc_path,
'envs', # if python env
version.slug,
'readthedocs-environment.json'
),
]

return paths

def update_env_json(self):
dojutsu-user marked this conversation as resolved.
Show resolved Hide resolved
"""Updates the hash value of ``envvars_hash`` in ``readthedocs-environment.json``."""
version = self._get_last_built_version()
paths = self._get_env_json_paths(version)
for path in paths:
if os.path.exists(path):
env_vars = self.project.environmentvariable_set.values_list('name', 'value')
with open(path, 'r+') as file:
data = json.loads(file.read())
data['envvars_hash'] = hash(tuple(env_vars))
file.seek(0)
file.write(json.dumps(data))

def save(self, *args, **kwargs): # pylint: disable=arguments-differ
self.value = shlex_quote(self.value)
return super().save(*args, **kwargs)
saved = super().save(*args, **kwargs)

# Updates the ``readthedocs-environment.json`` file.
self.update_env_json()

return saved

def delete(self, *args, **kwargs): # pylint: disable=arguments-differ
deleted = super().delete(*args, **kwargs)

# Updates the ``readthedocs-environment.json`` file.
self.update_env_json()

return deleted