repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
pre-commit/pre-commit
2,407
pre-commit__pre-commit-2407
[ "2406" ]
44cb80f74ac95f347fd66e0eb8d432b7cee4ca83
diff --git a/pre_commit/commands/hook_impl.py b/pre_commit/commands/hook_impl.py --- a/pre_commit/commands/hook_impl.py +++ b/pre_commit/commands/hook_impl.py @@ -76,6 +76,8 @@ def _ns( remote_name: str | None = None, remote_url: str | None = None, commit_msg_filename: str | None = None, + prepare_commit_message_source: str | None = None, + commit_object_name: str | None = None, checkout_type: str | None = None, is_squash_merge: str | None = None, rewrite_command: str | None = None, @@ -90,6 +92,8 @@ def _ns( remote_name=remote_name, remote_url=remote_url, commit_msg_filename=commit_msg_filename, + prepare_commit_message_source=prepare_commit_message_source, + commit_object_name=commit_object_name, all_files=all_files, checkout_type=checkout_type, is_squash_merge=is_squash_merge, @@ -202,8 +206,20 @@ def _run_ns( _check_args_length(hook_type, args) if hook_type == 'pre-push': return _pre_push_ns(color, args, stdin) - elif hook_type in {'commit-msg', 'prepare-commit-msg'}: + elif hook_type in 'commit-msg': return _ns(hook_type, color, commit_msg_filename=args[0]) + elif hook_type == 'prepare-commit-msg' and len(args) == 1: + return _ns(hook_type, color, commit_msg_filename=args[0]) + elif hook_type == 'prepare-commit-msg' and len(args) == 2: + return _ns( + hook_type, color, commit_msg_filename=args[0], + prepare_commit_message_source=args[1], + ) + elif hook_type == 'prepare-commit-msg' and len(args) == 3: + return _ns( + hook_type, color, commit_msg_filename=args[0], + prepare_commit_message_source=args[1], commit_object_name=args[2], + ) elif hook_type in {'post-commit', 'pre-merge-commit', 'pre-commit'}: return _ns(hook_type, color) elif hook_type == 'post-checkout': diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py --- a/pre_commit/commands/run.py +++ b/pre_commit/commands/run.py @@ -361,6 +361,16 @@ def run( ): return 0 + # Expose prepare_commit_message_source / commit_object_name + # as environment variables for the hooks + if args.prepare_commit_message_source: + environ['PRE_COMMIT_COMMIT_MSG_SOURCE'] = ( + args.prepare_commit_message_source + ) + + if args.commit_object_name: + environ['PRE_COMMIT_COMMIT_OBJECT_NAME'] = args.commit_object_name + # Expose from-ref / to-ref as environment variables for hooks to consume if args.from_ref and args.to_ref: # legacy names diff --git a/pre_commit/main.py b/pre_commit/main.py --- a/pre_commit/main.py +++ b/pre_commit/main.py @@ -107,6 +107,20 @@ def _add_run_options(parser: argparse.ArgumentParser) -> None: '--commit-msg-filename', help='Filename to check when running during `commit-msg`', ) + parser.add_argument( + '--prepare-commit-message-source', + help=( + 'Source of the commit message ' + '(typically the second argument to .git/hooks/prepare-commit-msg)' + ), + ) + parser.add_argument( + '--commit-object-name', + help=( + 'Commit object name ' + '(typically the third argument to .git/hooks/prepare-commit-msg)' + ), + ) parser.add_argument( '--remote-name', help='Remote name used by `git push`.', )
diff --git a/testing/util.py b/testing/util.py --- a/testing/util.py +++ b/testing/util.py @@ -76,6 +76,8 @@ def run_opts( hook_stage='commit', show_diff_on_failure=False, commit_msg_filename='', + prepare_commit_message_source='', + commit_object_name='', checkout_type='', is_squash_merge='', rewrite_command='', @@ -97,6 +99,8 @@ def run_opts( hook_stage=hook_stage, show_diff_on_failure=show_diff_on_failure, commit_msg_filename=commit_msg_filename, + prepare_commit_message_source=prepare_commit_message_source, + commit_object_name=commit_object_name, checkout_type=checkout_type, is_squash_merge=is_squash_merge, rewrite_command=rewrite_command, diff --git a/tests/commands/hook_impl_test.py b/tests/commands/hook_impl_test.py --- a/tests/commands/hook_impl_test.py +++ b/tests/commands/hook_impl_test.py @@ -154,6 +154,42 @@ def test_run_ns_commit_msg(): assert ns.commit_msg_filename == '.git/COMMIT_MSG' +def test_run_ns_prepare_commit_msg_one_arg(): + ns = hook_impl._run_ns( + 'prepare-commit-msg', False, + ('.git/COMMIT_MSG',), b'', + ) + assert ns is not None + assert ns.hook_stage == 'prepare-commit-msg' + assert ns.color is False + assert ns.commit_msg_filename == '.git/COMMIT_MSG' + + +def test_run_ns_prepare_commit_msg_two_arg(): + ns = hook_impl._run_ns( + 'prepare-commit-msg', False, + ('.git/COMMIT_MSG', 'message'), b'', + ) + assert ns is not None + assert ns.hook_stage == 'prepare-commit-msg' + assert ns.color is False + assert ns.commit_msg_filename == '.git/COMMIT_MSG' + assert ns.prepare_commit_message_source == 'message' + + +def test_run_ns_prepare_commit_msg_three_arg(): + ns = hook_impl._run_ns( + 'prepare-commit-msg', False, + ('.git/COMMIT_MSG', 'message', 'HEAD'), b'', + ) + assert ns is not None + assert ns.hook_stage == 'prepare-commit-msg' + assert ns.color is False + assert ns.commit_msg_filename == '.git/COMMIT_MSG' + assert ns.prepare_commit_message_source == 'message' + assert ns.commit_object_name == 'HEAD' + + def test_run_ns_post_commit(): ns = hook_impl._run_ns('post-commit', True, (), b'') assert ns is not None diff --git a/tests/commands/run_test.py b/tests/commands/run_test.py --- a/tests/commands/run_test.py +++ b/tests/commands/run_test.py @@ -810,7 +810,12 @@ def test_prepare_commit_msg_hook(cap_out, store, prepare_commit_msg_repo): cap_out, store, prepare_commit_msg_repo, - {'hook_stage': 'prepare-commit-msg', 'commit_msg_filename': filename}, + { + 'hook_stage': 'prepare-commit-msg', + 'commit_msg_filename': filename, + 'prepare_commit_message_source': 'commit', + 'commit_object_name': 'HEAD', + }, expected_outputs=[b'Add "Signed off by:"', b'Passed'], expected_ret=0, stage=False,
prepare-commit-msg Not passing all parameters ### search tried in the issue tracker Yes ### describe your issue When I run `git commit` with certain arguments I expect to get two or more arguments passed to argv of my script as per the specification: <img width="692" alt="image" src="https://user-images.githubusercontent.com/32771451/170735134-b8162715-0725-4375-b98c-32bbb1333320.png"> ```python def main(argv, argc): print(argv, argc) ``` Will print ``` ['tools/hooks/add-commit-template.py', '.git/COMMIT_EDITMSG'] 2 ``` It looks to me from looking at your auto-created hook installed that you are passing all args to the script so it maybe I haven't configured this correctly. Thanks ### pre-commit --version pre-commit 2.19.0 ### .pre-commit-config.yaml ```yaml repos: - repo: hooks: - id: commit-template-local name: Provide Commit Message Template entry: tools/hooks/add-commit-template.py language: python stages: [ prepare-commit-msg ] ``` ### ~/.cache/pre-commit/pre-commit.log (if present) _No response_
2022-05-28T00:03:41
pre-commit/pre-commit
2,480
pre-commit__pre-commit-2480
[ "2478" ]
49f95b9ef391639d09136666be375d99a3dccd04
diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py --- a/pre_commit/commands/run.py +++ b/pre_commit/commands/run.py @@ -420,7 +420,11 @@ def run( return 1 skips = _get_skips(environ) - to_install = [hook for hook in hooks if hook.id not in skips] + to_install = [ + hook + for hook in hooks + if hook.id not in skips and hook.alias not in skips + ] install_hook_envs(to_install, store) return _run_hooks(config, hooks, skips, args)
diff --git a/tests/commands/run_test.py b/tests/commands/run_test.py --- a/tests/commands/run_test.py +++ b/tests/commands/run_test.py @@ -635,6 +635,32 @@ def test_skip_bypasses_installation(cap_out, store, repo_with_passing_hook): assert ret == 0 +def test_skip_alias_bypasses_installation( + cap_out, store, repo_with_passing_hook, +): + config = { + 'repo': 'local', + 'hooks': [ + { + 'id': 'skipme', + 'name': 'skipme-1', + 'alias': 'skipme-1', + 'entry': 'skipme', + 'language': 'python', + 'additional_dependencies': ['/pre-commit-does-not-exist'], + }, + ], + } + add_config_to_repo(repo_with_passing_hook, config) + + ret, printed = _do_run( + cap_out, store, repo_with_passing_hook, + run_opts(all_files=True), + {'SKIP': 'skipme-1'}, + ) + assert ret == 0 + + def test_hook_id_not_in_non_verbose_output( cap_out, store, repo_with_passing_hook, ):
SKIP skips invocation by alias but doesn't skip "Installing environment" ### search tried in the issue tracker SKIP alias ### describe your issue When I run ```sh SKIP=pylint-alias2 git commit ``` the hook aliased as `pylint-alias2` is properly skipped, however, its environment is still initialized. I would expect that it also skips the lengthy initialization of the environment. Indeed, running a single hook ([run.py#153](https://github.com/pre-commit/pre-commit/blob/49f95b9ef391639d09136666be375d99a3dccd04/pre_commit/commands/run.py#153)) checks against `hook.id` and `hook.alias`, however `install_hook_envs` is invoked with only filtering against `hook.id` ([run.py#423](https://github.com/pre-commit/pre-commit/blob/49f95b9ef391639d09136666be375d99a3dccd04/pre_commit/commands/run.py) Is this inconsistency deliberate? I couldn't find a use case for it. This quick and dirty patch works for us: ```diff - to_install = [hook for hook in hooks if hook.id not in skips] + to_install = [hook for hook in hooks if hook.id not in skips and hook.alias not in skips] ``` In our use case Initialization is not needed for everyone (monorepo where some non-python devs also do non-python work) and also very expensive unfortunately (6minutes currently to install already cached pip packages) (An even better solution would be if initialization wouldn't happen at all if the hook run would we skipped in general (because of `SKIP` variable or because there is no files changed, however, that would be a but bigger patch I suppose)) ### pre-commit --version pre-commit ### .pre-commit-config.yaml ```yaml repos: - repo: https://github.com/PyCQA/pylint rev: v2.14.5 hooks: - name: pylint-alias1 alias: pylint-alias1 id: pylint additional_dependencies: - arrow - name: pylint-alias2 alias: pylint-alias2 id: pylint additional_dependencies: - hdfs ``` ### ~/.cache/pre-commit/pre-commit.log (if present) _No response_
Additional info: we are very well aware of the caching setups (and quite much like it!) and in our CI builds we do cache everything whenever an `additional_dependencies` changes. The most painful use case is really when a developer wants to commit files which has nothing to do with one python project, but since the `additional_dependencies` in another hook, which would not be invoked, changes, then the developer still has to wait for the long initialization step. Respecting `SKIP` would already be a big improvement initialization must happen to resolve the alias -- but it shouldn't be installed -- please don't skip the prompts in the issue template. show the command you ran and the output Sorry, my vocabulary was confused. Initialization should happen yes. **Installing** the environment should not. Here is the output (with cleared `~/.cache` before): ```sh ± SKIP=pylint-alias2 pre-commit run --all-files [INFO] Initializing environment for https://github.com/PyCQA/pylint. [INFO] Initializing environment for https://github.com/PyCQA/pylint:arrow. [INFO] Initializing environment for https://github.com/PyCQA/pylint:hdfs. [INFO] Installing environment for https://github.com/PyCQA/pylint. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/PyCQA/pylint. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... pylint-alias1........................................(no files to check)Skipped pylint-alias2...........................................................Skipped ``` yep seems like an oversight then, send a tested patch please
2022-08-11T07:34:24
pre-commit/pre-commit
2,524
pre-commit__pre-commit-2524
[ "2521" ]
b1de3338efe2d22fce2818e1092684a1ffcd2558
diff --git a/pre_commit/clientlib.py b/pre_commit/clientlib.py --- a/pre_commit/clientlib.py +++ b/pre_commit/clientlib.py @@ -298,6 +298,14 @@ def check(self, dct: dict[str, Any]) -> None: OptionalSensibleRegexAtHook('files', cfgv.check_string), OptionalSensibleRegexAtHook('exclude', cfgv.check_string), ) +LOCAL_HOOK_DICT = cfgv.Map( + 'Hook', 'id', + + *MANIFEST_HOOK_DICT.items, + + OptionalSensibleRegexAtHook('files', cfgv.check_string), + OptionalSensibleRegexAtHook('exclude', cfgv.check_string), +) CONFIG_REPO_DICT = cfgv.Map( 'Repository', 'repo', @@ -308,7 +316,7 @@ def check(self, dct: dict[str, Any]) -> None: 'repo', cfgv.NotIn(LOCAL, META), ), cfgv.ConditionalRecurse( - 'hooks', cfgv.Array(MANIFEST_HOOK_DICT), + 'hooks', cfgv.Array(LOCAL_HOOK_DICT), 'repo', LOCAL, ), cfgv.ConditionalRecurse(
diff --git a/tests/clientlib_test.py b/tests/clientlib_test.py --- a/tests/clientlib_test.py +++ b/tests/clientlib_test.py @@ -15,6 +15,8 @@ from pre_commit.clientlib import MANIFEST_SCHEMA from pre_commit.clientlib import META_HOOK_DICT from pre_commit.clientlib import MigrateShaToRev +from pre_commit.clientlib import OptionalSensibleRegexAtHook +from pre_commit.clientlib import OptionalSensibleRegexAtTop from pre_commit.clientlib import validate_config_main from pre_commit.clientlib import validate_manifest_main from testing.fixtures import sample_local_config @@ -261,6 +263,27 @@ def test_warn_mutable_rev_conditional(): cfgv.validate(config_obj, CONFIG_REPO_DICT) [email protected]( + 'validator_cls', + ( + OptionalSensibleRegexAtHook, + OptionalSensibleRegexAtTop, + ), +) +def test_sensible_regex_validators_dont_pass_none(validator_cls): + key = 'files' + with pytest.raises(cfgv.ValidationError) as excinfo: + validator = validator_cls(key, cfgv.check_string) + validator.check({key: None}) + + assert str(excinfo.value) == ( + '\n' + f'==> At key: {key}' + '\n' + '=====> Expected string got NoneType' + ) + + @pytest.mark.parametrize( ('regex', 'warning'), ( @@ -296,6 +319,22 @@ def test_validate_optional_sensible_regex_at_hook(caplog, regex, warning): assert caplog.record_tuples == [('pre_commit', logging.WARNING, warning)] +def test_validate_optional_sensible_regex_at_local_hook(caplog): + config_obj = sample_local_config() + config_obj['hooks'][0]['files'] = r'dir/*.py' + + cfgv.validate(config_obj, CONFIG_REPO_DICT) + + assert caplog.record_tuples == [ + ( + 'pre_commit', + logging.WARNING, + "The 'files' field in hook 'do_not_commit' is a regex, not a glob " + "-- matching '/*' probably isn't what you want here", + ), + ] + + @pytest.mark.parametrize( ('regex', 'warning'), (
warnings for regexes don't apply to `repo: local` looks like these were left out -- should be a pretty easy patch similar to #1707 / #1750
2022-09-23T02:59:53
pre-commit/pre-commit
2,605
pre-commit__pre-commit-2605
[ "2599" ]
f9b28cc2b01dd516e9c6c282c4cec84b7ee33853
diff --git a/pre_commit/languages/r.py b/pre_commit/languages/r.py --- a/pre_commit/languages/r.py +++ b/pre_commit/languages/r.py @@ -15,6 +15,7 @@ from pre_commit.prefix import Prefix from pre_commit.util import clean_path_on_failure from pre_commit.util import cmd_output_b +from pre_commit.util import win_exe ENVIRONMENT_DIR = 'renv' RSCRIPT_OPTS = ('--no-save', '--no-restore', '--no-site-file', '--no-environ') @@ -63,7 +64,7 @@ def _rscript_exec() -> str: if r_home is None: return 'Rscript' else: - return os.path.join(r_home, 'bin', 'Rscript') + return os.path.join(r_home, 'bin', win_exe('Rscript')) def _entry_validate(entry: Sequence[str]) -> None:
diff --git a/tests/languages/r_test.py b/tests/languages/r_test.py --- a/tests/languages/r_test.py +++ b/tests/languages/r_test.py @@ -6,6 +6,7 @@ from pre_commit import envcontext from pre_commit.languages import r +from pre_commit.util import win_exe from testing.fixtures import make_config_from_repo from testing.fixtures import make_repo from tests.repository_test import _get_hook_no_install @@ -133,7 +134,7 @@ def test_r_parsing_file_local(tempdir_factory, store): def test_rscript_exec_relative_to_r_home(): - expected = os.path.join('r_home_dir', 'bin', 'Rscript') + expected = os.path.join('r_home_dir', 'bin', win_exe('Rscript')) with envcontext.envcontext((('R_HOME', 'r_home_dir'),)): assert r._rscript_exec() == expected
Rscript not found in Windows ### search you tried in the issue tracker Rscript not found ### describe your issue Hi, I was adding hook for R language in pre-commit for the first time. And pre-commit throw me an error as ``` Executable `C:\path\to\R\R-4.0.5\bin\Rscript` not found ``` Because I was using hooks from [lorenzwalthert/precommit](https://github.com/lorenzwalthert/precommit), I found a similar issue was raised(https://github.com/lorenzwalthert/precommit/issues/441). But it looks like this issue is not related to the hooks and it is related to the R language support of pre-commit. The error was raised in `cmd_output_b` of `pre_commit\util.py`, which was called by `install_environment` of `pre_commit/languages/r.py` like. ``` cmd_output_b( _rscript_exec(), *RSCRIPT_OPTS, '-e', _inline_r_setup(r_code_inst_add), *additional_dependencies, cwd=env_dir, ) ``` The `_rscrip_exec()` will return `C:\path\to\R\R-4.0.5\bin\Rscript` in my case because $R_HOME is well set. ``` def _rscript_exec() -> str: r_home = os.environ.get('R_HOME') if r_home is None: return 'Rscript' else: return os.path.join(r_home, 'bin', 'Rscript') ``` When `C:\path\to\R\R-4.0.5\bin\Rscript` was passed to `parse_shebang.normalize_cmd`, and this function uses `normexe` to examine whether `exe` is executable. ``` def cmd_output_b( *cmd: str, retcode: int | None = 0, **kwargs: Any, ) -> tuple[int, bytes, bytes | None]: _setdefault_kwargs(kwargs) try: cmd = parse_shebang.normalize_cmd(cmd) except parse_shebang.ExecutableNotFoundError as e: returncode, stdout_b, stderr_b = e.to_output() else: try: proc = subprocess.Popen(cmd, **kwargs) except OSError as e: returncode, stdout_b, stderr_b = _oserror_to_output(e) else: stdout_b, stderr_b = proc.communicate() returncode = proc.returncode if retcode is not None and retcode != returncode: raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b) return returncode, stdout_b, stderr_b def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]: """Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine """ # Use PATH to determine the executable exe = normexe(cmd[0]) # Figure out the shebang from the resulting command cmd = parse_filename(exe) + (exe,) + cmd[1:] # This could have given us back another bare executable exe = normexe(cmd[0]) return (exe,) + cmd[1:] ``` And it seems that `C:\path\to\R\R-4.0.5\bin\Rscript` didn't pass `normexe`'s test and the code flowed into: ``` except parse_shebang.ExecutableNotFoundError as e: returncode, stdout_b, stderr_b = e.to_output() ``` `normexe` checks `exe`'s executability basing on two conditions: 1. `os.sep not in orig and (not os.altsep or os.altsep not in orig)` 2. `not os.path.isfile(orig)` ``` def normexe(orig: str) -> str: def _error(msg: str) -> NoReturn: raise ExecutableNotFoundError(f'Executable `{orig}` {msg}') if os.sep not in orig and (not os.altsep or os.altsep not in orig): exe = find_executable(orig) if exe is None: _error('not found') return exe elif os.path.isdir(orig): _error('is a directory') elif not os.path.isfile(orig): _error('not found') elif not os.access(orig, os.X_OK): # pragma: win32 no cover _error('is not executable') else: return orig ``` Since `os.sep` is in `C:\path\to\R\R-4.0.5\bin\Rscript`, `orig` will flow into `not os.path.isfile(orig)`. And `os.path.isfile(orig)` is `False`, because in Windows, the actual file is like **`C:\path\to\R\R-4.0.5\bin\Rscript.exe`**. I am wondering, to fix this issue on Windows, can we do an OS check in `_rscrip_exec()` and return `/path/to/bin/Rscript.exe` when the User is using Windows? Thank you! ### pre-commit --version pre-commit 2.20.0 ### .pre-commit-config.yaml ```yaml repos: - repo: https://github.com/lorenzwalthert/precommit rev: v0.3.2.9003 hooks: - id: parsable-R - id: lintr args: [--warn-only, --key=value] - id: style-files args: - --scope=token - id: roxygenize - id: use-tidy-description - repo: https://github.com/asottile/seed-isort-config rev: v2.2.0 hooks: - id: seed-isort-config - repo: https://github.com/pre-commit/mirrors-isort rev: v5.10.1 hooks: - id: isort - repo: https://github.com/psf/black rev: 22.10.0 hooks: - id: black args: - --line-length=79 language_version: python3.9 - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - id: flake8 args: - --extend-ignore=F401, E501, W503 ``` ### ~/.cache/pre-commit/pre-commit.log (if present) ### version information ``` pre-commit version: 2.20.0 git --version: git version 2.37.3.windows.1 sys.version: 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] sys.executable: C:\path\to\scripts\python.exe os.name: nt sys.platform: win32 ``` ### error information ``` An unexpected error has occurred: CalledProcessError: command: ('C:\\path\\to\\R\\R-4.0.5\\bin\\Rscript', '--vanilla', '-e', ' options(install.packages.compile.from.source = "never")\n prefix_dir <- \'C:\\\\path\\\\to\\\\.cache\\\\pre-commit\\\\repoo8yj9t7d\'\n options(\n repos = c(CRAN = "https://cran.rstudio.com"),\n renv.consent = TRUE\n )\n source("renv/activate.R")\n renv::restore()\n activate_statement <- paste0(\n \'suppressWarnings({\',\n \'old <- setwd("\', getwd(), \'"); \',\n \'source("renv/activate.R"); \',\n \'setwd(old); \',\n \'renv::load("\', getwd(), \'");})\'\n )\n writeLines(activate_statement, \'activate.R\')\n is_package <- tryCatch(\n {\n path_desc <- file.path(prefix_dir, \'DESCRIPTION\')\n suppressWarnings(desc <- read.dcf(path_desc))\n "Package" %in% colnames(desc)\n },\n error = function(...) FALSE\n )\n if (is_package) {\n renv::install(prefix_dir)\n }\n \n ') return code: 1 expected return code: 0 stdout: Executable `C:\path\to\R\R-4.0.5\bin\Rscript` not found stderr: (none) ``` ``` Traceback (most recent call last): File "C:\path\to\lib\site-packages\pre_commit\error_handler.py", line 73, in error_handler yield File "C:\path\to\lib\site-packages\pre_commit\main.py", line 358, in main return hook_impl( File "C:\path\to\lib\site-packages\pre_commit\commands\hook_impl.py", line 254, in hook_impl return retv | run(config, store, ns) File "C:\path\to\lib\site-packages\pre_commit\commands\run.py", line 424, in run install_hook_envs(to_install, store) File "C:\path\to\lib\site-packages\pre_commit\repository.py", line 223, in install_hook_envs _hook_install(hook) File "C:\path\to\lib\site-packages\pre_commit\repository.py", line 79, in _hook_install lang.install_environment( File "C:\path\to\lib\site-packages\pre_commit\languages\r.py", line 139, in install_environment cmd_output_b( File "C:\path\to\lib\site-packages\pre_commit\util.py", line 146, in cmd_output_b raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b) pre_commit.util.CalledProcessError: command: ('C:\\path\\to\\R\\R-4.0.5\\bin\\Rscript', '--vanilla', '-e', ' options(install.packages.compile.from.source = "never")\n prefix_dir <- \'C:\\\\path\\\\to\\\\.cache\\\\pre-commit\\\\repoo8yj9t7d\'\n options(\n repos = c(CRAN = "https://cran.rstudio.com"),\n renv.consent = TRUE\n )\n source("renv/activate.R")\n renv::restore()\n activate_statement <- paste0(\n \'suppressWarnings({\',\n \'old <- setwd("\', getwd(), \'"); \',\n \'source("renv/activate.R"); \',\n \'setwd(old); \',\n \'renv::load("\', getwd(), \'");})\'\n )\n writeLines(activate_statement, \'activate.R\')\n is_package <- tryCatch(\n {\n path_desc <- file.path(prefix_dir, \'DESCRIPTION\')\n suppressWarnings(desc <- read.dcf(path_desc))\n "Package" %in% colnames(desc)\n },\n error = function(...) FALSE\n )\n if (is_package) {\n renv::install(prefix_dir)\n }\n \n ') return code: 1 expected return code: 0 stdout: Executable `C:\path\to\R\R-4.0.5\bin\Rscript` not found stderr: (none) ```
probably just needs a call to `pre_commit.util.win_exe` here: https://github.com/pre-commit/pre-commit/blob/1f59f4cba8241ed7e572a1b5818bba74c6f31181/pre_commit/languages/r.py#L66 cc @lorenzwalthert Great issue description and investigation @SInginc. Indeed this might be the same as https://github.com/lorenzwalthert/precommit/issues/441, except that in addition to not finding the executable because of a lacking suffix, there might have been another issue with `~` usage: ``` Executable `C:/PROGRA~1/R/R-41~1.0\bin\Rscript` not found ``` Me and the OP did not take the time to create such a good reprex and description, also because I was not sure it was even reproducible on other people's machines. Now it seems this is the case. Also, how is this not caught with tests? I am trying to expand integration tests in [lorenzwalthert/precommit ](https://github.com/lorenzwalthert/precommit/pull/452) where I run end to end with `pre-commit run`. @SInginc Do you want to make a PR or should I? > Great issue description and investigation @SInginc. Indeed this might be the same as [lorenzwalthert/precommit#441](https://github.com/lorenzwalthert/precommit/issues/441), except that in addition to not finding the executable because of a lacking suffix, there might have been another issue with `~` usage: > > ``` > Executable `C:/PROGRA~1/R/R-41~1.0\bin\Rscript` not found > ``` > > Me and the OP did not take the time to create such a good reprex and description, also because I was not sure it was even reproducible on other people's machines. Now it seems this is the case. Also, how is this not caught with tests? I am trying to expand integration tests in [lorenzwalthert/precommit ](https://github.com/lorenzwalthert/precommit/pull/452) where I run end to end with `pre-commit run`. > > @SInginc Do you want to make a PR or should I? Thank you! @lorenzwalthert Yes, please make a PR because I am still getting familiar with how to use Github...
2022-11-19T12:30:54
pre-commit/pre-commit
2,641
pre-commit__pre-commit-2641
[ "2629" ]
d7b8b123e6f513a20c4709c3eb0c6c07a7b8b608
diff --git a/pre_commit/languages/dotnet.py b/pre_commit/languages/dotnet.py --- a/pre_commit/languages/dotnet.py +++ b/pre_commit/languages/dotnet.py @@ -2,6 +2,9 @@ import contextlib import os.path +import re +import xml.etree.ElementTree +import zipfile from typing import Generator from typing import Sequence @@ -57,10 +60,29 @@ def install_environment( ), ) - # Determine tool from the packaged file <tool_name>.<version>.nupkg - build_outputs = os.listdir(os.path.join(prefix.prefix_dir, build_dir)) - for output in build_outputs: - tool_name = output.split('.')[0] + nupkg_dir = prefix.path(build_dir) + nupkgs = [x for x in os.listdir(nupkg_dir) if x.endswith('.nupkg')] + + if not nupkgs: + raise AssertionError('could not find any build outputs to install') + + for nupkg in nupkgs: + with zipfile.ZipFile(os.path.join(nupkg_dir, nupkg)) as f: + nuspec, = (x for x in f.namelist() if x.endswith('.nuspec')) + with f.open(nuspec) as spec: + tree = xml.etree.ElementTree.parse(spec) + + namespace = re.match(r'{.*}', tree.getroot().tag) + if not namespace: + raise AssertionError('could not parse namespace from nuspec') + + tool_id_element = tree.find(f'.//{namespace[0]}id') + if tool_id_element is None: + raise AssertionError('expected to find an "id" element') + + tool_id = tool_id_element.text + if not tool_id: + raise AssertionError('"id" element missing tool name') # Install to bin dir helpers.run_setup_cmd( @@ -69,7 +91,7 @@ def install_environment( 'dotnet', 'tool', 'install', '--tool-path', os.path.join(envdir, BIN_DIR), '--add-source', build_dir, - tool_name, + tool_id, ), )
diff --git a/testing/resources/dotnet_hooks_csproj_prefix_repo/.gitignore b/testing/resources/dotnet_hooks_csproj_prefix_repo/.gitignore new file mode 100644 --- /dev/null +++ b/testing/resources/dotnet_hooks_csproj_prefix_repo/.gitignore @@ -0,0 +1,3 @@ +bin/ +obj/ +nupkg/ diff --git a/testing/resources/dotnet_hooks_csproj_prefix_repo/.pre-commit-hooks.yaml b/testing/resources/dotnet_hooks_csproj_prefix_repo/.pre-commit-hooks.yaml new file mode 100644 --- /dev/null +++ b/testing/resources/dotnet_hooks_csproj_prefix_repo/.pre-commit-hooks.yaml @@ -0,0 +1,5 @@ +- id: dotnet-example-hook + name: dotnet example hook + entry: testeroni.tool + language: dotnet + files: '' diff --git a/testing/resources/dotnet_hooks_csproj_prefix_repo/Program.cs b/testing/resources/dotnet_hooks_csproj_prefix_repo/Program.cs new file mode 100644 --- /dev/null +++ b/testing/resources/dotnet_hooks_csproj_prefix_repo/Program.cs @@ -0,0 +1,12 @@ +using System; + +namespace dotnet_hooks_repo +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Hello from dotnet!"); + } + } +} diff --git a/testing/resources/dotnet_hooks_csproj_prefix_repo/dotnet_hooks_csproj_prefix_repo.csproj b/testing/resources/dotnet_hooks_csproj_prefix_repo/dotnet_hooks_csproj_prefix_repo.csproj new file mode 100644 --- /dev/null +++ b/testing/resources/dotnet_hooks_csproj_prefix_repo/dotnet_hooks_csproj_prefix_repo.csproj @@ -0,0 +1,9 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>net7.0</TargetFramework> + <PackAsTool>true</PackAsTool> + <ToolCommandName>testeroni.tool</ToolCommandName> + <PackageOutputPath>./nupkg</PackageOutputPath> + </PropertyGroup> +</Project> diff --git a/tests/repository_test.py b/tests/repository_test.py --- a/tests/repository_test.py +++ b/tests/repository_test.py @@ -1031,6 +1031,7 @@ def test_local_perl_additional_dependencies(store): 'dotnet_hooks_csproj_repo', 'dotnet_hooks_sln_repo', 'dotnet_hooks_combo_repo', + 'dotnet_hooks_csproj_prefix_repo', ), ) def test_dotnet_hook(tempdir_factory, store, repo):
dotnet install fails for prefixed packages ### search you tried in the issue tracker dotnet tool ### describe your issue A bit of an oversight when constructing `tool_name` here: https://github.com/pre-commit/pre-commit/blob/cb0bcfd67fc35e91f7b2eca7e33bceda459dca77/pre_commit/languages/dotnet.py#L60-L63 E.g. ```console $ pre-commit try-repo https://github.com/rkm/sample-dotnet-tool [INFO] Initializing environment for https://github.com/rkm/sample-dotnet-tool. =============================================================================== Using config: =============================================================================== repos: - repo: https://github.com/rkm/sample-dotnet-tool rev: e53a3601bc06bb038dac30da813572291dd8d58f hooks: - id: sample-dotnet-tool =============================================================================== [INFO] Installing environment for https://github.com/rkm/sample-dotnet-tool. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexpected error has occurred: CalledProcessError: command: ('/home/rkm/bin/dotnet', 'tool', 'install', '--tool-path', '/tmp/tmp6bk4v26x/repotefhurdg/dotnetenv-default/bin', '--add-source', 'pre-commit-build', 'Rkm') return code: 1 expected return code: 0 stdout: /tmp/1873db78-d0a7-48ba-bbff-10a7ef85a2a6/restore.csproj : error NU1101: Unable to find package rkm. No packages exist with this id in source(s): /tmp/tmp6bk4v26x/repotefhurdg/pre-commit-build, nuget.org stderr: The tool package could not be restored. Tool 'rkm' failed to install. This failure may have been caused by: * You are attempting to install a preview release and did not use the --version option to specify the version. * A package by this name was found, but it was not a .NET tool. * The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem. * You mistyped the name of the tool. For more reasons, including package naming enforcement, visit https://aka.ms/failure-installing-tool Check the log at /home/rkm/.cache/pre-commit/pre-commit.log ``` ### pre-commit --version pre-commit 2.20.0 ### .pre-commit-config.yaml ```yaml repos: - repo: https://github.com/rkm/sample-dotnet-tool rev: e53a3601bc06bb038dac30da813572291dd8d58f hooks: - id: sample-dotnet-tool ``` ### ~/.cache/pre-commit/pre-commit.log (if present) _No response_
2022-12-12T19:25:16
pre-commit/pre-commit
2,651
pre-commit__pre-commit-2651
[ "2649" ]
ceb429b25380dacee34ba6997e5dd3d5f09b811a
diff --git a/pre_commit/languages/golang.py b/pre_commit/languages/golang.py --- a/pre_commit/languages/golang.py +++ b/pre_commit/languages/golang.py @@ -1,9 +1,21 @@ from __future__ import annotations import contextlib +import functools +import json import os.path +import platform +import shutil import sys +import tarfile +import tempfile +import urllib.error +import urllib.request +import zipfile +from typing import ContextManager from typing import Generator +from typing import IO +from typing import Protocol from typing import Sequence import pre_commit.constants as C @@ -17,20 +29,100 @@ from pre_commit.util import rmtree ENVIRONMENT_DIR = 'golangenv' -get_default_version = helpers.basic_get_default_version health_check = helpers.basic_health_check +_ARCH_ALIASES = { + 'x86_64': 'amd64', + 'i386': '386', + 'aarch64': 'arm64', + 'armv8': 'arm64', + 'armv7l': 'armv6l', +} +_ARCH = platform.machine().lower() +_ARCH = _ARCH_ALIASES.get(_ARCH, _ARCH) + + +class ExtractAll(Protocol): + def extractall(self, path: str) -> None: ... + + +if sys.platform == 'win32': # pragma: win32 cover + _EXT = 'zip' + + def _open_archive(bio: IO[bytes]) -> ContextManager[ExtractAll]: + return zipfile.ZipFile(bio) +else: # pragma: win32 no cover + _EXT = 'tar.gz' + + def _open_archive(bio: IO[bytes]) -> ContextManager[ExtractAll]: + return tarfile.open(fileobj=bio) + + [email protected]_cache(maxsize=1) +def get_default_version() -> str: + if helpers.exe_exists('go'): + return 'system' + else: + return C.DEFAULT + + +def get_env_patch(venv: str, version: str) -> PatchesT: + if version == 'system': + return ( + ('PATH', (os.path.join(venv, 'bin'), os.pathsep, Var('PATH'))), + ) -def get_env_patch(venv: str) -> PatchesT: return ( - ('PATH', (os.path.join(venv, 'bin'), os.pathsep, Var('PATH'))), + ('GOROOT', os.path.join(venv, '.go')), + ( + 'PATH', ( + os.path.join(venv, 'bin'), os.pathsep, + os.path.join(venv, '.go', 'bin'), os.pathsep, Var('PATH'), + ), + ), ) [email protected]_cache +def _infer_go_version(version: str) -> str: + if version != C.DEFAULT: + return version + resp = urllib.request.urlopen('https://go.dev/dl/?mode=json') + # TODO: 3.9+ .removeprefix('go') + return json.load(resp)[0]['version'][2:] + + +def _get_url(version: str) -> str: + os_name = platform.system().lower() + version = _infer_go_version(version) + return f'https://dl.google.com/go/go{version}.{os_name}-{_ARCH}.{_EXT}' + + +def _install_go(version: str, dest: str) -> None: + try: + resp = urllib.request.urlopen(_get_url(version)) + except urllib.error.HTTPError as e: # pragma: no cover + if e.code == 404: + raise ValueError( + f'Could not find a version matching your system requirements ' + f'(os={platform.system().lower()}; arch={_ARCH})', + ) from e + else: + raise + else: + with tempfile.TemporaryFile() as f: + shutil.copyfileobj(resp, f) + f.seek(0) + + with _open_archive(f) as archive: + archive.extractall(dest) + shutil.move(os.path.join(dest, 'go'), os.path.join(dest, '.go')) + + @contextlib.contextmanager -def in_env(prefix: Prefix) -> Generator[None, None, None]: - envdir = helpers.environment_dir(prefix, ENVIRONMENT_DIR, C.DEFAULT) - with envcontext(get_env_patch(envdir)): +def in_env(prefix: Prefix, version: str) -> Generator[None, None, None]: + envdir = helpers.environment_dir(prefix, ENVIRONMENT_DIR, version) + with envcontext(get_env_patch(envdir, version)): yield @@ -39,15 +131,23 @@ def install_environment( version: str, additional_dependencies: Sequence[str], ) -> None: - helpers.assert_version_default('golang', version) env_dir = helpers.environment_dir(prefix, ENVIRONMENT_DIR, version) + if version != 'system': + _install_go(version, env_dir) + if sys.platform == 'cygwin': # pragma: no cover gopath = cmd_output('cygpath', '-w', env_dir)[1].strip() else: gopath = env_dir + env = dict(os.environ, GOPATH=gopath) env.pop('GOBIN', None) + if version != 'system': + env['GOROOT'] = os.path.join(env_dir, '.go') + env['PATH'] = os.pathsep.join(( + os.path.join(env_dir, '.go', 'bin'), os.environ['PATH'], + )) helpers.run_setup_cmd(prefix, ('go', 'install', './...'), env=env) for dependency in additional_dependencies: @@ -64,5 +164,5 @@ def run_hook( file_args: Sequence[str], color: bool, ) -> tuple[int, bytes]: - with in_env(hook.prefix): + with in_env(hook.prefix, hook.language_version): return helpers.run_xargs(hook, hook.cmd, file_args, color=color)
diff --git a/testing/resources/golang_hooks_repo/golang-hello-world/main.go b/testing/resources/golang_hooks_repo/golang-hello-world/main.go --- a/testing/resources/golang_hooks_repo/golang-hello-world/main.go +++ b/testing/resources/golang_hooks_repo/golang-hello-world/main.go @@ -3,7 +3,9 @@ package main import ( "fmt" + "runtime" "github.com/BurntSushi/toml" + "os" ) type Config struct { @@ -11,7 +13,11 @@ type Config struct { } func main() { + message := runtime.Version() + if len(os.Args) > 1 { + message = os.Args[1] + } var conf Config toml.Decode("What = 'world'\n", &conf) - fmt.Printf("hello %v\n", conf.What) + fmt.Printf("hello %v from %s\n", conf.What, message) } diff --git a/tests/languages/golang_test.py b/tests/languages/golang_test.py new file mode 100644 --- /dev/null +++ b/tests/languages/golang_test.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import re +from unittest import mock + +import pytest + +import pre_commit.constants as C +from pre_commit.languages import golang +from pre_commit.languages import helpers + + +ACTUAL_GET_DEFAULT_VERSION = golang.get_default_version.__wrapped__ + + [email protected] +def exe_exists_mck(): + with mock.patch.object(helpers, 'exe_exists') as mck: + yield mck + + +def test_golang_default_version_system_available(exe_exists_mck): + exe_exists_mck.return_value = True + assert ACTUAL_GET_DEFAULT_VERSION() == 'system' + + +def test_golang_default_version_system_not_available(exe_exists_mck): + exe_exists_mck.return_value = False + assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT + + +ACTUAL_INFER_GO_VERSION = golang._infer_go_version.__wrapped__ + + +def test_golang_infer_go_version_not_default(): + assert ACTUAL_INFER_GO_VERSION('1.19.4') == '1.19.4' + + +def test_golang_infer_go_version_default(): + version = ACTUAL_INFER_GO_VERSION(C.DEFAULT) + + assert version != C.DEFAULT + assert re.match(r'^\d+\.\d+\.\d+$', version) diff --git a/tests/repository_test.py b/tests/repository_test.py --- a/tests/repository_test.py +++ b/tests/repository_test.py @@ -380,17 +380,36 @@ def test_swift_hook(tempdir_factory, store): ) -def test_golang_hook(tempdir_factory, store): +def test_golang_system_hook(tempdir_factory, store): _test_hook_repo( tempdir_factory, store, 'golang_hooks_repo', - 'golang-hook', [], b'hello world\n', + 'golang-hook', ['system'], b'hello world from system\n', + config_kwargs={ + 'hooks': [{ + 'id': 'golang-hook', + 'language_version': 'system', + }], + }, + ) + + +def test_golang_versioned_hook(tempdir_factory, store): + _test_hook_repo( + tempdir_factory, store, 'golang_hooks_repo', + 'golang-hook', [], b'hello world from go1.18.4\n', + config_kwargs={ + 'hooks': [{ + 'id': 'golang-hook', + 'language_version': '1.18.4', + }], + }, ) def test_golang_hook_still_works_when_gobin_is_set(tempdir_factory, store): gobin_dir = tempdir_factory.get() with envcontext((('GOBIN', gobin_dir),)): - test_golang_hook(tempdir_factory, store) + test_golang_system_hook(tempdir_factory, store) assert os.listdir(gobin_dir) == [] @@ -677,7 +696,7 @@ def test_additional_golang_dependencies_installed( envdir = helpers.environment_dir( hook.prefix, golang.ENVIRONMENT_DIR, - C.DEFAULT, + golang.get_default_version(), ) binaries = os.listdir(os.path.join(envdir, 'bin')) # normalize for windows
Make Go a first class language Hey, as many tools are now built using golang, it would be good to have it as a first class language. I've hacked a little [POC](https://github.com/pre-commit/pre-commit/compare/main...taoufik07:pre-commit:golang_playground?expand=1) heavily inspired by the ruby lang and using https://github.com/stefanmaric/g as a go version manager. Please let me know if that's what you had in mind before I go any further.
we can't depend on `g` -- but go is simple enough to provision by downloading the appropriate prebuilt bundle from the go website Even better, I've updated the [POC](https://github.com/pre-commit/pre-commit/compare/main...taoufik07:pre-commit:golang_playground?expand=1), please let me know if I should open a draft PR. Downloading golang and installing packages (e.g. tfsec) takes ~50s on a relatively speedy connection and a performant computer, I'm not sure if we can do something about that. Having the download language would help, but that's another discussion.
2022-12-23T21:22:42
pre-commit/pre-commit
2,686
pre-commit__pre-commit-2686
[ "2685" ]
dc667ab9fbb75e17f7b57ab1d3c8e39e017df223
diff --git a/pre_commit/commands/migrate_config.py b/pre_commit/commands/migrate_config.py --- a/pre_commit/commands/migrate_config.py +++ b/pre_commit/commands/migrate_config.py @@ -3,8 +3,10 @@ import re import textwrap +import cfgv import yaml +from pre_commit.clientlib import InvalidConfigError from pre_commit.yaml import yaml_load @@ -44,6 +46,13 @@ def migrate_config(config_file: str, quiet: bool = False) -> int: with open(config_file) as f: orig_contents = contents = f.read() + with cfgv.reraise_as(InvalidConfigError): + with cfgv.validate_context(f'File {config_file}'): + try: + yaml_load(orig_contents) + except Exception as e: + raise cfgv.ValidationError(str(e)) + contents = _migrate_map(contents) contents = _migrate_sha_to_rev(contents)
diff --git a/tests/commands/migrate_config_test.py b/tests/commands/migrate_config_test.py --- a/tests/commands/migrate_config_test.py +++ b/tests/commands/migrate_config_test.py @@ -1,6 +1,9 @@ from __future__ import annotations +import pytest + import pre_commit.constants as C +from pre_commit.clientlib import InvalidConfigError from pre_commit.commands.migrate_config import migrate_config @@ -129,3 +132,13 @@ def test_migrate_config_sha_to_rev(tmpdir): ' rev: v1.2.0\n' ' hooks: []\n' ) + + +def test_migrate_config_invalid_yaml(tmpdir): + contents = '[' + cfg = tmpdir.join(C.CONFIG_FILE) + cfg.write(contents) + with tmpdir.as_cwd(), pytest.raises(InvalidConfigError) as excinfo: + migrate_config(C.CONFIG_FILE) + expected = '\n==> File .pre-commit-config.yaml\n=====> ' + assert str(excinfo.value).startswith(expected)
ParserError exception raised for invalid configuration ### search you tried in the issue tracker ParserError and unicode ### describe your issue I executed `pre-commit autoupdate` with an invalid configuration file (the second `- repo` is indented incorrectly) and got this error message: ```` $ pre-commit autoupdate An unexpected error has occurred: ParserError: while parsing a block mapping in "<unicode string>", line 1, column 1 did not find expected key in "<unicode string>", line 7, column 1 Check the log at /home/carsten/.cache/pre-commit/pre-commit.log ```` This is an expected error and I would expect an error message like `Your configuration file "..." is wrongly formatted at <pos>. Please review the format of the content.'. Thank you, Carsten ### pre-commit --version pre-commit 2.21.0 ### .pre-commit-config.yaml ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: check-executables-have-shebangs - repo: https://github.com/shellcheck-py/shellcheck-py rev: v0.9.0.2 hooks: - id: shellcheck ``` ### ~/.cache/pre-commit/pre-commit.log (if present) ### version information ``` pre-commit version: 2.21.0 git --version: git version 2.35.3 sys.version: 3.10.8 (main, Oct 28 2022, 17:28:32) [GCC] sys.executable: /home/carsten/virtualenv/bin/python3.10 os.name: posix sys.platform: linux ``` ### error information ``` An unexpected error has occurred: ParserError: while parsing a block mapping in "<unicode string>", line 1, column 1 did not find expected key in "<unicode string>", line 7, column 1 ``` ``` Traceback (most recent call last): File "/home/carsten/virtualenv/lib64/python3.10/site-packages/pre_commit/error_handler.py", line 73, in error_handler yield File "/home/carsten/virtualenv/lib64/python3.10/site-packages/pre_commit/main.py", line 355, in main return autoupdate( File "/home/carsten/virtualenv/lib64/python3.10/site-packages/pre_commit/commands/autoupdate.py", line 154, in autoupdate migrate_config(config_file, quiet=True) File "/home/carsten/virtualenv/lib64/python3.10/site-packages/pre_commit/commands/migrate_config.py", line 47, in migrate_config contents = _migrate_map(contents) File "/home/carsten/virtualenv/lib64/python3.10/site-packages/pre_commit/commands/migrate_config.py", line 16, in _migrate_map if isinstance(yaml_load(contents), list): File "/home/carsten/virtualenv/lib64/python3.10/site-packages/yaml/__init__.py", line 81, in load return loader.get_single_data() File "/home/carsten/virtualenv/lib64/python3.10/site-packages/yaml/constructor.py", line 49, in get_single_data node = self.get_single_node() File "yaml/_yaml.pyx", line 673, in yaml._yaml.CParser.get_single_node File "yaml/_yaml.pyx", line 687, in yaml._yaml.CParser._compose_document File "yaml/_yaml.pyx", line 731, in yaml._yaml.CParser._compose_node File "yaml/_yaml.pyx", line 847, in yaml._yaml.CParser._compose_mapping_node File "yaml/_yaml.pyx", line 860, in yaml._yaml.CParser._parse_next_event yaml.parser.ParserError: while parsing a block mapping in "<unicode string>", line 1, column 1 did not find expected key in "<unicode string>", line 7, column 1 ```
2023-01-09T17:32:05
pre-commit/pre-commit
2,740
pre-commit__pre-commit-2740
[ "2739" ]
9868b1a3477af88ab77b07ea1d1d3eac7ec16f4f
diff --git a/pre_commit/languages/ruby.py b/pre_commit/languages/ruby.py --- a/pre_commit/languages/ruby.py +++ b/pre_commit/languages/ruby.py @@ -39,7 +39,6 @@ def get_env_patch( ('GEM_HOME', os.path.join(venv, 'gems')), ('GEM_PATH', UNSET), ('BUNDLE_IGNORE_CONFIG', '1'), - ('BUNDLE_GEMFILE', os.devnull), ) if language_version == 'system': patches += (
diff --git a/tests/languages/ruby_test.py b/tests/languages/ruby_test.py --- a/tests/languages/ruby_test.py +++ b/tests/languages/ruby_test.py @@ -123,8 +123,9 @@ def test_ruby_hook_language_version(tmp_path): def test_ruby_with_bundle_disable_shared_gems(tmp_path): workdir = tmp_path.joinpath('workdir') workdir.mkdir() - # this Gemfile is missing `source` - workdir.joinpath('Gemfile').write_text('gem "lol_hai"\n') + # this needs a `source` or there's a deprecation warning + # silencing this with `BUNDLE_GEMFILE` breaks some tools (#2739) + workdir.joinpath('Gemfile').write_text('source ""\ngem "lol_hai"\n') # this bundle config causes things to be written elsewhere bundle = workdir.joinpath('.bundle') bundle.mkdir() @@ -134,5 +135,5 @@ def test_ruby_with_bundle_disable_shared_gems(tmp_path): ) with cwd(workdir): - # `3.2.0` has new enough `gem` requiring `source` and reading `.bundle` + # `3.2.0` has new enough `gem` reading `.bundle` test_ruby_hook_language_version(tmp_path)
/dev/null not found with pre-commit 3.0.2 ### search you tried in the issue tracker /dev/null ### describe your issue After upgrading to pre-commit 3.0.2, one of my users (on up-to-date macos) is reporting that invoking ruby actions fails with `/dev/null` not found. Relevant output: ``` rubocop..................................................................Failed - hook id: rubocop - exit code: 2 /dev/null not found /Users/user/.rvm/rubies/ruby-3.1.3/lib/ruby/3.1.0/bundler/definition.rb:36:in `build' /Users/user/.rvm/rubies/ruby-3.1.3/lib/ruby/3.1.0/bundler.rb:207:in `definition' /Users/user/.rvm/rubies/ruby-3.1.3/lib/ruby/3.1.0/bundler.rb:190:in `load' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/config_loader_resolver.rb:270:in `gem_config_path' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/config_loader_resolver.rb:65:in `block (2 levels) in resolve_inheritance_from_gems' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/config_loader_resolver.rb:63:in `reverse_each' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/config_loader_resolver.rb:63:in `block in resolve_inheritance_from_gems' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/config_loader_resolver.rb:57:in `each_pair' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/config_loader_resolver.rb:57:in `resolve_inheritance_from_gems' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/config_loader.rb:49:in `load_file' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/config_loader.rb:104:in `configuration_from_file' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/config_store.rb:68:in `for_dir' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/config_store.rb:47:in `for_pwd' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/cli.rb:147:in `apply_default_formatter' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/lib/rubocop/cli.rb:47:in `run' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/exe/rubocop:19:in `block in <top (required)>' /Users/user/.rvm/rubies/ruby-3.1.3/lib/ruby/3.1.0/benchmark.rb:311:in `realtime' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/gems/rubocop-1.42.0/exe/rubocop:19:in `<top (required)>' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/bin/rubocop:25:in `load' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/bin/rubocop:25:in `<main>' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/bin/ruby_executable_hooks:22:in `eval' /Users/user/.cache/pre-commit/repojquw8lys/rbenv-default/gems/bin/ruby_executable_hooks:22:in `<main>' ``` This looks closely related to #2727. For what it's worth, I did confirm that the user actually has a working `/dev/null` on their system. ### pre-commit --version pre-commit 3.0.2 ### .pre-commit-config.yaml ```yaml repos: - repo: https://github.com/rubocop/rubocop.git rev: '0f7416a0b3ea4a3d4edb1f2091ce8706ea3e6640' hooks: - id: rubocop additional_dependencies: ["standard:1.22.1"] ``` ### ~/.cache/pre-commit/pre-commit.log (if present) _No response_
ugh ruby -- yep that'd be the one -- I'll get that reverted and fixed up -- thanks for the report!
2023-02-01T22:58:28
pre-commit/pre-commit
2,743
pre-commit__pre-commit-2743
[ "2742" ]
e846829992a84ce8066e6513a72a357709eec56c
diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py --- a/pre_commit/commands/run.py +++ b/pre_commit/commands/run.py @@ -272,7 +272,8 @@ def _all_filenames(args: argparse.Namespace) -> Collection[str]: def _get_diff() -> bytes: _, out, _ = cmd_output_b( - 'git', 'diff', '--no-ext-diff', '--ignore-submodules', check=False, + 'git', 'diff', '--no-ext-diff', '--no-textconv', '--ignore-submodules', + check=False, ) return out @@ -326,8 +327,7 @@ def _has_unmerged_paths() -> bool: def _has_unstaged_config(config_file: str) -> bool: retcode, _, _ = cmd_output_b( - 'git', 'diff', '--no-ext-diff', '--exit-code', config_file, - check=False, + 'git', 'diff', '--quiet', '--no-ext-diff', config_file, check=False, ) # be explicit, other git errors don't mean it has an unstaged config. return retcode == 1
diff --git a/tests/commands/run_test.py b/tests/commands/run_test.py --- a/tests/commands/run_test.py +++ b/tests/commands/run_test.py @@ -766,6 +766,47 @@ def test_lots_of_files(store, tempdir_factory): ) +def test_no_textconv(cap_out, store, repo_with_passing_hook): + # git textconv filters can hide changes from hooks + with open('.gitattributes', 'w') as fp: + fp.write('*.jpeg diff=empty\n') + + with open('.git/config', 'a') as fp: + fp.write('[diff "empty"]\n') + fp.write('textconv = "true"\n') + + config = { + 'repo': 'local', + 'hooks': [ + { + 'id': 'extend-jpeg', + 'name': 'extend-jpeg', + 'language': 'system', + 'entry': ( + f'{shlex.quote(sys.executable)} -c "import sys; ' + 'open(sys.argv[1], \'ab\').write(b\'\\x00\')"' + ), + 'types': ['jpeg'], + }, + ], + } + add_config_to_repo(repo_with_passing_hook, config) + + stage_a_file('example.jpeg') + + _test_run( + cap_out, + store, + repo_with_passing_hook, + {}, + ( + b'Failed', + ), + expected_ret=1, + stage=False, + ) + + def test_stages(cap_out, store, repo_with_passing_hook): config = { 'repo': 'local',
Binary file change by hook not detected due to Git textconv ### search you tried in the issue tracker textconv ### describe your issue I’ve set up Git to use `exiftool` as a text conversion filter for JPEGs, with this in `~/.config/git/config`: ```ini [diff "exiftool"] textconv = exiftool --composite -x 'Exiftool:*' -x 'File:*' -g0 cachetextconv = true xfuncname = "^-.*$" ``` …and this in `~/.config/git/attributes`: ``` *.jpeg diff=exiftool ``` In my repo, I’m using `jpegoptim` to optimize JPEG's with the below `.pre-commit-config.yaml`. Take an unoptimized JPEG: ```console $ git status On branch main Changes to be committed: new file: donut.jpeg ``` Running pre-commit, the hook passes: ```console $ pre-commit run jpegoptim Optimize JPEGs...........................................................Passed ``` (There’s no option to make `jpegoptim` exit with a non-zero status code when it changes files.) However, the tool did actually modify the image: ```console $ git status On branch main Changes to be committed: new file: donut.jpeg Changes not staged for commit: modified: donut.jpeg ``` This behaviour means commits don't include the optimized version of a flie, instead they’re left around unstaged. pre-commit doesn't detect the change because the text conversions of the binary file before/after are the same, leading to an empty diff: ``` $ git diff donut.jpeg ``` But using [`--no-textconv`](https://git-scm.com/docs/git-diff#Documentation/git-diff.txt---no-textconv) shows the tool actually made a change: $ git diff --no-textconv donut.jpeg |cat diff --git a/donut.jpeg b/donut.jpeg index 3bd0743..d66a2f4 100644 Binary files a/donut.jpeg and b/donut.jpeg differ ``` The `git diff` call that pre-commit uses to check for changes, in [`_git_diff()`](https://github.com/pre-commit/pre-commit/blob/e846829992a84ce8066e6513a72a357709eec56c/pre_commit/commands/run.py#L273C6-L277) already uses `--no-ext-diff` to make diffs reproducible I think it should also use `--no-textconv`. This would also make it a little faster. ### pre-commit --version 3.0.3 / main ### .pre-commit-config.yaml ```yaml repos: - repo: local hooks: - id: jpegoptim name: Optimize JPEGs entry: jpegoptim language: system types: [jpeg] ``` ### ~/.cache/pre-commit/pre-commit.log (if present) _No response_
2023-02-02T11:09:43
pre-commit/pre-commit
2,746
pre-commit__pre-commit-2746
[ "2734" ]
0359fae2da2aadb2fbd3afae1777edd3aa856cc9
diff --git a/pre_commit/commands/migrate_config.py b/pre_commit/commands/migrate_config.py --- a/pre_commit/commands/migrate_config.py +++ b/pre_commit/commands/migrate_config.py @@ -42,6 +42,14 @@ def _migrate_sha_to_rev(contents: str) -> str: return re.sub(r'(\n\s+)sha:', r'\1rev:', contents) +def _migrate_python_venv(contents: str) -> str: + return re.sub( + r'(\n\s+)language: python_venv\b', + r'\1language: python', + contents, + ) + + def migrate_config(config_file: str, quiet: bool = False) -> int: with open(config_file) as f: orig_contents = contents = f.read() @@ -55,6 +63,7 @@ def migrate_config(config_file: str, quiet: bool = False) -> int: contents = _migrate_map(contents) contents = _migrate_sha_to_rev(contents) + contents = _migrate_python_venv(contents) if contents != orig_contents: with open(config_file, 'w') as f: diff --git a/pre_commit/repository.py b/pre_commit/repository.py --- a/pre_commit/repository.py +++ b/pre_commit/repository.py @@ -3,6 +3,7 @@ import json import logging import os +import shlex from typing import Any from typing import Sequence @@ -68,6 +69,14 @@ def _hook_install(hook: Hook) -> None: logger.info('Once installed this environment will be reused.') logger.info('This may take a few minutes...') + if hook.language == 'python_venv': + logger.warning( + f'`repo: {hook.src}` uses deprecated `language: python_venv`. ' + f'This is an alias for `language: python`. ' + f'Often `pre-commit autoupdate --repo {shlex.quote(hook.src)}` ' + f'will fix this.', + ) + lang = languages[hook.language] assert lang.ENVIRONMENT_DIR is not None
diff --git a/testing/resources/python_venv_hooks_repo/.pre-commit-hooks.yaml b/testing/resources/python_venv_hooks_repo/.pre-commit-hooks.yaml deleted file mode 100644 --- a/testing/resources/python_venv_hooks_repo/.pre-commit-hooks.yaml +++ /dev/null @@ -1,5 +0,0 @@ -- id: foo - name: Foo - entry: foo - language: python_venv - files: \.py$ diff --git a/testing/resources/python_venv_hooks_repo/foo.py b/testing/resources/python_venv_hooks_repo/foo.py deleted file mode 100644 --- a/testing/resources/python_venv_hooks_repo/foo.py +++ /dev/null @@ -1,9 +0,0 @@ -from __future__ import annotations - -import sys - - -def main(): - print(repr(sys.argv[1:])) - print('Hello World') - return 0 diff --git a/testing/resources/python_venv_hooks_repo/setup.py b/testing/resources/python_venv_hooks_repo/setup.py deleted file mode 100644 --- a/testing/resources/python_venv_hooks_repo/setup.py +++ /dev/null @@ -1,10 +0,0 @@ -from __future__ import annotations - -from setuptools import setup - -setup( - name='foo', - version='0.0.0', - py_modules=['foo'], - entry_points={'console_scripts': ['foo = foo:main']}, -) diff --git a/tests/commands/migrate_config_test.py b/tests/commands/migrate_config_test.py --- a/tests/commands/migrate_config_test.py +++ b/tests/commands/migrate_config_test.py @@ -134,6 +134,39 @@ def test_migrate_config_sha_to_rev(tmpdir): ) +def test_migrate_config_language_python_venv(tmp_path): + src = '''\ +repos: +- repo: local + hooks: + - id: example + name: example + entry: example + language: python_venv + - id: example + name: example + entry: example + language: system +''' + expected = '''\ +repos: +- repo: local + hooks: + - id: example + name: example + entry: example + language: python + - id: example + name: example + entry: example + language: system +''' + cfg = tmp_path.joinpath('cfg.yaml') + cfg.write_text(src) + assert migrate_config(str(cfg)) == 0 + assert cfg.read_text() == expected + + def test_migrate_config_invalid_yaml(tmpdir): contents = '[' cfg = tmpdir.join(C.CONFIG_FILE) diff --git a/tests/languages/all_test.py b/tests/languages/all_test.py new file mode 100644 --- /dev/null +++ b/tests/languages/all_test.py @@ -0,0 +1,7 @@ +from __future__ import annotations + +from pre_commit.languages.all import languages + + +def test_python_venv_is_an_alias_to_python(): + assert languages['python_venv'] is languages['python'] diff --git a/tests/repository_test.py b/tests/repository_test.py --- a/tests/repository_test.py +++ b/tests/repository_test.py @@ -129,11 +129,21 @@ def test_python_hook_weird_setup_cfg(in_git_dir, tempdir_factory, store): ) -def test_python_venv(tempdir_factory, store): - _test_hook_repo( - tempdir_factory, store, 'python_venv_hooks_repo', - 'foo', [os.devnull], - f'[{os.devnull!r}]\nHello World\n'.encode(), +def test_python_venv_deprecation(store, caplog): + config = { + 'repo': 'local', + 'hooks': [{ + 'id': 'example', + 'name': 'example', + 'language': 'python_venv', + 'entry': 'echo hi', + }], + } + _get_hook(config, store, 'example') + assert caplog.messages[-1] == ( + '`repo: local` uses deprecated `language: python_venv`. ' + 'This is an alias for `language: python`. ' + 'Often `pre-commit autoupdate --repo local` will fix this.' )
deprecate `python_venv` language this has been an alias to `python` for a very long time but it cannot be removed without a deprecation period this is going to need a long deprecation period since it's sorta subtle and usually not the user's fault and will need hook authors to (potentially) make updates the plan is to do the following: 1. introduce the following in a minor release - migrate-config will autofix `.pre-commit-config.yaml` usages of `language: python_venv` (there isn't an equivalent `migrate-manifest` -- though users outnumber hook authors by several orders of magnitude) 1. introduce the following in a minor release - a warning is shown for configuration using the `language: python_venv` - a warning is shown for repos using `language: python_venv` (do this at install time so it only shows once as to not be super annoying for users who have no control) - a recommendation for hook authors to also set `minimum_pre_commit_version` to this version 1. a long time passes (typically my deprecation period has been 12-18+ months) 1. introduce the following in a major release - removal of the `python_venv` alias
2023-02-04T19:27:55
pre-commit/pre-commit
2,774
pre-commit__pre-commit-2774
[ "2773" ]
8ba9bc6d890092e81f0b46253bfa22da73ba4759
diff --git a/pre_commit/staged_files_only.py b/pre_commit/staged_files_only.py --- a/pre_commit/staged_files_only.py +++ b/pre_commit/staged_files_only.py @@ -7,6 +7,7 @@ from typing import Generator from pre_commit import git +from pre_commit.errors import FatalError from pre_commit.util import CalledProcessError from pre_commit.util import cmd_output from pre_commit.util import cmd_output_b @@ -49,12 +50,16 @@ def _intent_to_add_cleared() -> Generator[None, None, None]: @contextlib.contextmanager def _unstaged_changes_cleared(patch_dir: str) -> Generator[None, None, None]: tree = cmd_output('git', 'write-tree')[1].strip() - retcode, diff_stdout_binary, _ = cmd_output_b( + diff_cmd = ( 'git', 'diff-index', '--ignore-submodules', '--binary', '--exit-code', '--no-color', '--no-ext-diff', tree, '--', - check=False, ) - if retcode and diff_stdout_binary.strip(): + retcode, diff_stdout, diff_stderr = cmd_output_b(*diff_cmd, check=False) + if retcode == 0: + # There weren't any staged files so we don't need to do anything + # special + yield + elif retcode == 1 and diff_stdout.strip(): patch_filename = f'patch{int(time.time())}-{os.getpid()}' patch_filename = os.path.join(patch_dir, patch_filename) logger.warning('Unstaged files detected.') @@ -62,7 +67,7 @@ def _unstaged_changes_cleared(patch_dir: str) -> Generator[None, None, None]: # Save the current unstaged changes as a patch os.makedirs(patch_dir, exist_ok=True) with open(patch_filename, 'wb') as patch_file: - patch_file.write(diff_stdout_binary) + patch_file.write(diff_stdout) # prevent recursive post-checkout hooks (#1418) no_checkout_env = dict(os.environ, _PRE_COMMIT_SKIP_POST_CHECKOUT='1') @@ -86,10 +91,12 @@ def _unstaged_changes_cleared(patch_dir: str) -> Generator[None, None, None]: _git_apply(patch_filename) logger.info(f'Restored changes from {patch_filename}.') - else: - # There weren't any staged files so we don't need to do anything - # special - yield + else: # pragma: win32 no cover + # some error occurred while requesting the diff + e = CalledProcessError(retcode, diff_cmd, b'', diff_stderr) + raise FatalError( + f'pre-commit failed to diff -- perhaps due to permissions?\n\n{e}', + ) @contextlib.contextmanager
diff --git a/tests/staged_files_only_test.py b/tests/staged_files_only_test.py --- a/tests/staged_files_only_test.py +++ b/tests/staged_files_only_test.py @@ -1,12 +1,15 @@ from __future__ import annotations +import contextlib import itertools import os.path import shutil import pytest +import re_assert from pre_commit import git +from pre_commit.errors import FatalError from pre_commit.staged_files_only import staged_files_only from pre_commit.util import cmd_output from testing.auto_namedtuple import auto_namedtuple @@ -14,6 +17,7 @@ from testing.util import cwd from testing.util import get_resource_path from testing.util import git_commit +from testing.util import xfailif_windows FOO_CONTENTS = '\n'.join(('1', '2', '3', '4', '5', '6', '7', '8', '')) @@ -382,3 +386,51 @@ def test_intent_to_add(in_git_dir, patch_dir): with staged_files_only(patch_dir): assert_no_diff() assert git.intent_to_add_files() == ['foo'] + + [email protected] +def _unreadable(f): + orig = os.stat(f).st_mode + os.chmod(f, 0o000) + try: + yield + finally: + os.chmod(f, orig) + + +@xfailif_windows # pragma: win32 no cover +def test_failed_diff_does_not_discard_changes(in_git_dir, patch_dir): + # stage 3 files + for i in range(3): + with open(str(i), 'w') as f: + f.write(str(i)) + cmd_output('git', 'add', '0', '1', '2') + + # modify all of their contents + for i in range(3): + with open(str(i), 'w') as f: + f.write('new contents') + + with _unreadable('1'): + with pytest.raises(FatalError) as excinfo: + with staged_files_only(patch_dir): + raise AssertionError('should have errored on enter') + + # the diff command failed to produce a diff of `1` + msg, = excinfo.value.args + re_assert.Matches( + r'^pre-commit failed to diff -- perhaps due to permissions\?\n\n' + r'command: .*\n' + r'return code: 128\n' + r'stdout: \(none\)\n' + r'stderr:\n' + r' error: open\("1"\): Permission denied\n' + r' fatal: cannot hash 1\n' + # TODO: not sure why there's weird whitespace here + r' $', + ).assert_matches(msg) + + # even though it errored, the unstaged changes should still be present + for i in range(3): + with open(str(i)) as f: + assert f.read() == 'new contents'
pre-commit can delete/revert unstaged files if error occurs during git diff-index ### search you tried in the issue tracker diff-index ### describe your issue I performed a git commit with some modifications unstaged. After the commit, most of the modifications had been reverted and my work was lost. The diff saved in the patch directory had only a few of the modifications in - the ones that survived. The rest were gone. To reproduce: - Modify four files and stage one with `git add` - Use `git status` to determine the order of the three unstaged files. - Change the permission on the middle one so that git will not be able to read it - Now do `git commit`: the changes to the first unstaged file will be preserved but the other two will be lost. The key point, I think, is that the code in `staged_files_only.py` checks that the return code when creating the diff is non-zero which it takes to mean that the code is `1` meaning that there were diffs. However, in this case the return code is `128` which *is* non-zero but does _not_ mean success - it means error. So the code assumes the diff is OK even though it is incomplete. ### pre-commit --version 2.17.0 ### .pre-commit-config.yaml ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: 56b4a7e506901ff86f8de5c2551bc41f8eacf717 hooks: - id: check-yaml # - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/psf/black rev: 21.11b0 hooks: - id: black language_version: python3.6 - repo: https://github.com/PyCQA/isort rev: 5.10.1 hooks: - id: isort args: ["--profile", "black", "--filter-files"] ``` ### ~/.cache/pre-commit/pre-commit.log (if present) _No response_
quite a weird case -- but I guess it makes sense. in the case of `diff-index` producing an error I think there's not too much `pre-commit` can do other than throwing that error back at the user and hoping they can figure out how to unbreak their checkout > quite a weird case -- but I guess it makes sense. in the case of `diff-index` producing an error I think there's not too much `pre-commit` can do other than throwing that error back at the user and hoping they can figure out how to unbreak their checkout Yes. I would much rather it didn't delete my morning's work and pretend everything is OK. Crashing out at that point is what is required.
2023-02-21T17:09:50
pre-commit/pre-commit
2,827
pre-commit__pre-commit-2827
[ "2823" ]
df2cada973da6ee689cbc8e323caccf5c00df92c
diff --git a/pre_commit/languages/rust.py b/pre_commit/languages/rust.py --- a/pre_commit/languages/rust.py +++ b/pre_commit/languages/rust.py @@ -80,9 +80,9 @@ def _add_dependencies( lang_base.setup_cmd(prefix, ('cargo', 'add', *crates)) -def install_rust_with_toolchain(toolchain: str) -> None: +def install_rust_with_toolchain(toolchain: str, envdir: str) -> None: with tempfile.TemporaryDirectory() as rustup_dir: - with envcontext((('RUSTUP_HOME', rustup_dir),)): + with envcontext((('CARGO_HOME', envdir), ('RUSTUP_HOME', rustup_dir))): # acquire `rustup` if not present if parse_shebang.find_executable('rustup') is None: # We did not detect rustup and need to download it first. @@ -145,7 +145,7 @@ def install_environment( ctx.enter_context(in_env(prefix, version)) if version != 'system': - install_rust_with_toolchain(_rust_toolchain(version)) + install_rust_with_toolchain(_rust_toolchain(version), envdir) tmpdir = ctx.enter_context(tempfile.TemporaryDirectory()) ctx.enter_context(envcontext((('RUSTUP_HOME', tmpdir),)))
Executable `rustup` not found ### search you tried in the issue tracker Executable `rustup` not found ### describe your issue Since pre-commit 3.2.0 our GitHub workflow is broken. This ins one of the last working runs: https://github.com/mixxxdj/mixxx/actions/runs/4448394360/jobs/7811151308 Downloading pre_commit-3.1.1-py2.py3-none-any.whl (202 kB) This is a failing one: https://github.com/mixxxdj/mixxx/actions/runs/4451827087/jobs/7824682752 Downloading pre_commit-3.2.0-py2.py3-none-any.whl (202 kB) ### pre-commit --version pre-commit 3.2.0 ### .pre-commit-config.yaml ```yaml # This is the configuration file for the pre-commit framework, a simple way # to manage, install and run git hooks to catch common problems early on. # See https://pre-commit.com/ for details. # # If you have Python >= 3.7 and python-pip installed, just run: # # $ pip install --user pre-commit # $ git clone https://github.com/your-fork-of/mixxx.git # $ cd mixxx # $ pre-commit install # $ pre-commit install -t pre-push # # It will now run relevant hooks automatically on every `git commit` or # `git push` in the mixxx git repository. # # If you have a problems with a particular hook, you can use the `$SKIP` # environment variable to disable hooks: # # $ SKIP=clang-format,end-of-file-fixer git commit # # This can also be used to separate logic changes and autoformatting into # two subsequent commits. # # Using the `$SKIP` var is preferable to using `git commit --no-verify` # because it won't prevent catching other, unrelated issues. # _anlz.h/_pdb.h: Header files generated by Kaitai Struct exclude: ^(lib/|src/test/.*data/).*|res/translations/.*\.ts|src/.*_(anlz|pdb)\.h$ minimum_pre_commit_version: 2.21.0 default_language_version: python: python3 rust: 1.64.0 repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: fix-byte-order-marker exclude: ^.*(\.cbproj|\.groupproj|\.props|\.sln|\.vcxproj|\.vcxproj.filters)$ - id: check-case-conflict - id: check-json - id: check-merge-conflict - id: check-xml - id: check-yaml exclude: ^\.clang-format$ - id: end-of-file-fixer - id: mixed-line-ending - id: trailing-whitespace exclude: \.(c|cc|cxx|cpp|frag|glsl|h|hpp|hxx|ih|ispc|ipp|java|js|m|mm|proto|vert)$ - id: no-commit-to-branch # protect main and any branch that has a semver-like name args: [-b, main, -p, '^\d+\.\d+(?:\.\d+)?$'] - repo: https://github.com/codespell-project/codespell rev: v2.2.2 hooks: - id: codespell args: [ --exclude-file, .codespellignorelines, --ignore-words, .codespellignore, --ignore-regex, "\\W(?:m_p*(?=[A-Z])|m_(?=\\w)|pp*(?=[A-Z])|k(?=[A-Z])|s_(?=\\w))", ] exclude: ^(packaging/wix/LICENSE.rtf|src/dialog/dlgabout\.cpp|.*\.(?:pot?|ts|wxl|svg))$ - repo: https://github.com/pre-commit/mirrors-eslint rev: v8.25.0 hooks: - id: eslint args: [--fix, --report-unused-disable-directives] files: \.m?js$ types: [file] stages: - commit - manual additional_dependencies: - eslint@^v8.6.0 - eslint-plugin-jsdoc@^v37.5.0 - repo: local hooks: - id: clang-format name: clang-format description: "Run clang-format in two passes (reformat, then break long lines)" entry: python tools/clang_format.py require_serial: true stages: - commit - manual language: python additional_dependencies: - clang-format==14.0.6 files: \.(c|cc|cxx|cpp|frag|glsl|h|hpp|hxx|ih|ispc|ipp|java|m|mm|proto|vert)$ - repo: https://github.com/psf/black rev: 22.10.0 hooks: - id: black files: ^tools/.*$ - repo: https://github.com/pycqa/flake8 rev: "5.0.4" hooks: - id: flake8 files: ^tools/.*$ types: [text, python] - repo: https://github.com/shellcheck-py/shellcheck-py rev: v0.8.0.4 hooks: - id: shellcheck - repo: https://github.com/DavidAnson/markdownlint-cli2 rev: v0.5.1 hooks: - id: markdownlint-cli2 - repo: https://github.com/python-jsonschema/check-jsonschema rev: 0.18.3 hooks: - id: check-github-workflows - repo: https://github.com/pre-commit/mirrors-prettier rev: v2.7.1 hooks: - id: prettier types: [yaml] - repo: https://github.com/qarmin/qml_formatter.git rev: 0.2.0 hooks: - id: qml_formatter - repo: local hooks: - id: qsscheck name: qsscheck description: Run qsscheck to detect broken QSS. entry: python tools/qsscheck.py args: [.] pass_filenames: false language: python additional_dependencies: - tinycss==0.4 types: [text] files: ^.*\.qss$ stages: - commit - manual - id: changelog name: changelog description: Add missing links to changelog. entry: python tools/changelog.py language: python types: [text] files: ^CHANGELOG.md$ - id: qmllint name: qmllint entry: qmllint pass_filenames: true require_serial: true language: system types: [text] files: ^.*\.qml$ - id: metainfo name: metainfo description: Update AppStream metainfo releases from CHANGELOG.md. entry: python tools/update_metainfo.py pass_filenames: false language: python additional_dependencies: - beautifulsoup4==4.11.1 - lxml==4.9.1 - Markdown==3.4.1 types: [text] files: ^(CHANGELOG\.md|res/linux/org\.mixxx\.Mixxx\.metainfo.xml)$ ``` ### ~/.cache/pre-commit/pre-commit.log (if present) 2023-03-18T11:16:24.8724175Z [INFO] Initializing environment for https://github.com/pre-commit/pre-commit-hooks. 2023-03-18T11:16:25.3378859Z [INFO] Initializing environment for https://github.com/codespell-project/codespell. 2023-03-18T11:16:25.8998370Z [INFO] Initializing environment for https://github.com/pre-commit/mirrors-eslint. 2023-03-18T11:16:26.3373046Z [INFO] Initializing environment for https://github.com/pre-commit/mirrors-eslint:eslint@^v8.6.0,eslint-plugin-jsdoc@^v37.5.0. 2023-03-18T11:16:26.7769485Z [INFO] Initializing environment for local:clang-format==14.0.6. 2023-03-18T11:16:26.7823306Z [INFO] Initializing environment for https://github.com/psf/black. 2023-03-18T11:16:27.4353970Z [INFO] Initializing environment for https://github.com/pycqa/flake8. 2023-03-18T11:16:27.9719090Z [INFO] Initializing environment for https://github.com/shellcheck-py/shellcheck-py. 2023-03-18T11:16:28.4303322Z [INFO] Initializing environment for https://github.com/DavidAnson/markdownlint-cli2. 2023-03-18T11:16:28.9106462Z [INFO] Initializing environment for https://github.com/python-jsonschema/check-jsonschema. 2023-03-18T11:16:29.5219475Z [INFO] Initializing environment for https://github.com/pre-commit/mirrors-prettier. 2023-03-18T11:16:29.9463012Z [INFO] Initializing environment for https://github.com/pre-commit/mirrors-prettier:[email protected]. 2023-03-18T11:16:30.3722936Z [INFO] Initializing environment for https://github.com/qarmin/qml_formatter.git. 2023-03-18T11:16:30.7800010Z [INFO] Initializing environment for local:tinycss==0.4. 2023-03-18T11:16:30.7845724Z [INFO] Initializing environment for local. 2023-03-18T11:16:30.7890533Z [INFO] Initializing environment for local:beautifulsoup4==4.11.1,lxml==4.9.1,Markdown==3.4.1. 2023-03-18T11:16:30.7935963Z [INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks. 2023-03-18T11:16:30.7936430Z [INFO] Once installed this environment will be reused. 2023-03-18T11:16:30.7937142Z [INFO] This may take a few minutes... 2023-03-18T11:16:36.1315607Z [INFO] Installing environment for https://github.com/codespell-project/codespell. 2023-03-18T11:16:36.1316105Z [INFO] Once installed this environment will be reused. 2023-03-18T11:16:36.1316598Z [INFO] This may take a few minutes... 2023-03-18T11:16:41.0677859Z [INFO] Installing environment for https://github.com/pre-commit/mirrors-eslint. 2023-03-18T11:16:41.0678364Z [INFO] Once installed this environment will be reused. 2023-03-18T11:16:41.0678749Z [INFO] This may take a few minutes... 2023-03-18T11:16:52.1967027Z [INFO] Installing environment for local. 2023-03-18T11:16:52.1967972Z [INFO] Once installed this environment will be reused. 2023-03-18T11:16:52.1968731Z [INFO] This may take a few minutes... 2023-03-18T11:16:54.9343036Z [INFO] Installing environment for https://github.com/psf/black. 2023-03-18T11:16:54.9343514Z [INFO] Once installed this environment will be reused. 2023-03-18T11:16:54.9343897Z [INFO] This may take a few minutes... 2023-03-18T11:16:59.3853467Z [INFO] Installing environment for https://github.com/pycqa/flake8. 2023-03-18T11:16:59.3853994Z [INFO] Once installed this environment will be reused. 2023-03-18T11:16:59.3854348Z [INFO] This may take a few minutes... 2023-03-18T11:17:01.9111743Z [INFO] Installing environment for https://github.com/shellcheck-py/shellcheck-py. 2023-03-18T11:17:01.9112317Z [INFO] Once installed this environment will be reused. 2023-03-18T11:17:01.9112658Z [INFO] This may take a few minutes... 2023-03-18T11:17:04.9449677Z [INFO] Installing environment for https://github.com/DavidAnson/markdownlint-cli2. 2023-03-18T11:17:04.9450176Z [INFO] Once installed this environment will be reused. 2023-03-18T11:17:04.9450535Z [INFO] This may take a few minutes... 2023-03-18T11:17:25.7010838Z [INFO] Installing environment for https://github.com/python-jsonschema/check-jsonschema. 2023-03-18T11:17:25.7011350Z [INFO] Once installed this environment will be reused. 2023-03-18T11:17:25.7011717Z [INFO] This may take a few minutes... 2023-03-18T11:17:29.8214983Z [INFO] Installing environment for https://github.com/pre-commit/mirrors-prettier. 2023-03-18T11:17:29.8215477Z [INFO] Once installed this environment will be reused. 2023-03-18T11:17:29.8215817Z [INFO] This may take a few minutes... 2023-03-18T11:17:36.7285087Z [INFO] Installing environment for https://github.com/qarmin/qml_formatter.git. 2023-03-18T11:17:36.7285587Z [INFO] Once installed this environment will be reused. 2023-03-18T11:17:36.7285924Z [INFO] This may take a few minutes... 2023-03-18T11:17:37.1457698Z An unexpected error has occurred: CalledProcessError: command: ('rustup', 'toolchain', 'install', '--no-self-update', '1.64.0') 2023-03-18T11:17:37.1458511Z return code: 1 2023-03-18T11:17:37.1458692Z stdout: 2023-03-18T11:17:37.1458924Z Executable `rustup` not found 2023-03-18T11:17:37.1459148Z stderr: (none)
can you get the copy of the pre-commit log? that's the more useful log file ### version information ``` pre-commit version: 3.2.0 git --version: git version 2.37.3 sys.version: 3.10.7 (main, Sep 6 2022, 21:22:27) [GCC 12.2.0] sys.executable: /usr/sbin/python os.name: posix sys.platform: linux ``` ### error information ``` An unexpected error has occurred: CalledProcessError: command: ('rustup', 'toolchain', 'install', '--no-self-update', '1.64.0') return code: 1 stdout: Executable `rustup` not found stderr: (none) ``` ``` Traceback (most recent call last): File "/usr/lib/python3.10/site-packages/pre_commit/error_handler.py", line 73, in error_handler yield File "/usr/lib/python3.10/site-packages/pre_commit/main.py", line 409, in main return run(args.config, store, args) File "/usr/lib/python3.10/site-packages/pre_commit/commands/run.py", line 442, in run install_hook_envs(to_install, store) File "/usr/lib/python3.10/site-packages/pre_commit/repository.py", line 248, in install_hook_envs _hook_install(hook) File "/usr/lib/python3.10/site-packages/pre_commit/repository.py", line 95, in _hook_install lang.install_environment( File "/usr/lib/python3.10/site-packages/pre_commit/languages/rust.py", line 148, in install_environment install_rust_with_toolchain(_rust_toolchain(version)) File "/usr/lib/python3.10/site-packages/pre_commit/languages/rust.py", line 107, in install_rust_with_toolchain cmd_output_b( File "/usr/lib/python3.10/site-packages/pre_commit/util.py", line 110, in cmd_output_b raise CalledProcessError(returncode, cmd, stdout_b, stderr_b) pre_commit.util.CalledProcessError: command: ('rustup', 'toolchain', 'install', '--no-self-update', '1.64.0') return code: 1 stdout: Executable `rustup` not found stderr: (none) ```
2023-03-25T17:06:45
pre-commit/pre-commit
2,836
pre-commit__pre-commit-2836
[ "2235" ]
bb49560dc99a65608c8f9161dd71467af163c0d1
diff --git a/pre_commit/languages/swift.py b/pre_commit/languages/swift.py --- a/pre_commit/languages/swift.py +++ b/pre_commit/languages/swift.py @@ -44,7 +44,7 @@ def install_environment( os.mkdir(envdir) cmd_output_b( 'swift', 'build', - '-C', prefix.prefix_dir, + '--package-path', prefix.prefix_dir, '-c', BUILD_CONFIG, '--build-path', os.path.join(envdir, BUILD_DIR), )
Alternative to stashing files for testing Are there any plans to implement alternatives to stashing the worktree? Ideally this would be hook/scriptable, like some 'prepare-worktree' and 'restore-worktree' options (which default to the current stash behavior) but can also yield some new directory where the tests are run. The rationale here is that my editor reverts files changed on disk and I'd like to add notes to source files while the commit is in progress. In my own pre-commit hooks I use something like: git archive "$(git write-tree)" --prefix="$test_dir/" | tar xf - To create a pristine source tree (actually, I also prime it with `cp -rl` with build artifacts from the previous build to speed up incremental builds). 'git-worktree' and other tools could be used as well... Eventually I have the idea to run some (more expensive) pre-commit checks in the background while one types the commit message. Then in the commit-msg hook wait for the background results and abort the commit there. This should reduce the turn around times significantly.
> Are there any plans to implement alternatives to stashing the worktree? nope! but thanks for the issue nonetheless
2023-04-03T19:53:21
pre-commit/pre-commit
2,866
pre-commit__pre-commit-2866
[ "2865" ]
4c0623963f9cd0735829fec265575fdd003a7659
diff --git a/pre_commit/commands/autoupdate.py b/pre_commit/commands/autoupdate.py --- a/pre_commit/commands/autoupdate.py +++ b/pre_commit/commands/autoupdate.py @@ -67,6 +67,8 @@ def update(self, tags_only: bool, freeze: bool) -> RevInfo: rev, frozen = exact, rev try: + # workaround for windows -- see #2865 + cmd_output_b(*_git, 'show', f'{rev}:{C.MANIFEST_FILE}') cmd_output(*_git, 'checkout', rev, '--', C.MANIFEST_FILE) except CalledProcessError: pass # this will be caught by manifest validating code
pre-commit autoupdate (Windows), reports: `.pre-commit-hooks.yaml is not a file` ### search you tried in the issue tracker is:issue "not a file" ### describe your issue #### Summary The last version I used successfully was `2.17.0` and `pre-commit 3.2.2, installed using Python 3.11.3` #### Additional debugging tried I tried manually specifying the `pre-commit-config.yaml` file, but I realise now that the error is related to the `pre-commit-`**hooks**`.yaml` file. ~~As this works outside of the tox env I suspect it is a bug.~~ I have the following tox file: ```ini [tox] minversion = 4.4.4 # We rely on the build agent configuration for setting the right Py version envlist = py skip_missing_interpreters = True skipdist = True [testenv] usedevelop = True extras = test commands= git clean -xdf src tests pytest {posargs} setenv = # Has problems with spaces in the path in Windows when using: {toxinidir}/constraints.txt PIP_CONSTRAINT=constraints.txt PIP_LOG={envdir}/pip.log PIP_DISABLE_PIP_VERSION_CHECK=1 passenv = PIP_* TWINE_* allowlist_externals = git [testenv:deps] description = Update dependency lock files deps = pip-tools >= 6.4.0 pre-commit >= 2.13.0 commands = # pip-compile --upgrade -o constraints.txt pyproject.toml --extra docs --extra test --extra exe --strip-extras {envpython} -m pre_commit autoupdate --config="{toxinidir}{/}.pre-commit-config.yaml" ``` and this is the full output. (For completeness I should mentioned that `MY_PROJECT` is actually a longer path) ```shell > tox run -e deps ROOT: provision> D:\dev\MY_PROJECT\.tox\.tox\Scripts\python.exe -m tox run -e deps .pkg: _optional_hooks D:\dev\MY_PROJECT> python D:\dev\MY_PROJECT\.tox\.tox\Lib\site-packages\pyproject_api\_backend.py True hatchling.build .pkg: get_requires_for_build_editable D:\dev\MY_PROJECT> python D:\dev\MY_PROJECT\.tox\.tox\Lib\site-packages\pyproject_api\_backend.py True hatchling.build .pkg: build_editable D:\dev\MY_PROJECT> python D:\dev\MY_PROJECT\.tox\.tox\Lib\site-packages\pyproject_api\_backend.py True hatchling.build deps: install_package D:\dev\MY_PROJECT> python -I -m pip install --force-reinstall --no-deps D:\dev\MY_PROJECT\.tox\.tmp\package\8\MY_PROJECT-1.0.1.dev49+ge471ddf.d20230502-py3-none-any.whl deps: commands[0] D:\dev\MY_PROJECT> .tox\deps\Scripts\python.exe -m pre_commit autoupdate --config=D:\dev\MY_PROJECT\.pre-commit-config.yaml [https://github.com/psf/black] =====> C:\Users\ADEHA~1\AppData\Local\Temp\tmp55jx9hj6\.pre-commit-hooks.yaml is not a file [https://github.com/pre-commit/pre-commit-hooks] =====> C:\Users\ADEHA~1\AppData\Local\Temp\tmpkqy_t829\.pre-commit-hooks.yaml is not a file [https://github.com/codespell-project/codespell.git] =====> C:\Users\ADEHA~1\AppData\Local\Temp\tmprw3q8l3b\.pre-commit-hooks.yaml is not a file [https://github.com/charliermarsh/ruff-pre-commit] =====> C:\Users\ADEHA~1\AppData\Local\Temp\tmp27qxr3kd\.pre-commit-hooks.yaml is not a file [https://github.com/adrienverge/yamllint.git] =====> C:\Users\ADEHA~1\AppData\Local\Temp\tmpssemasfd\.pre-commit-hooks.yaml is not a file [https://github.com/pre-commit/mirrors-mypy.git] =====> C:\Users\ADEHA~1\AppData\Local\Temp\tmpasg5xk_r\.pre-commit-hooks.yaml is not a file [https://github.com/asottile/pyupgrade] =====> C:\Users\ADEHA~1\AppData\Local\Temp\tmpo5pgj08h\.pre-commit-hooks.yaml is not a file deps: exit 1 (26.53 seconds) D:\dev\MY_PROJECT> .tox\deps\Scripts\python.exe -m pre_commit autoupdate --config=D:\dev\MY_PROJECT\.pre-commit-config.yaml pid=40900 ``` ### pre-commit --version 3.3.0 ### .pre-commit-config.yaml ```yaml --- repos: - repo: https://github.com/psf/black rev: 23.3.0 hooks: - id: black language_version: python3 - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: end-of-file-fixer - id: trailing-whitespace - id: mixed-line-ending - id: check-byte-order-marker - id: check-executables-have-shebangs - id: check-merge-conflict - id: check-symlinks - id: check-vcs-permalinks - id: debug-statements - id: check-yaml files: .*\.(yaml|yml)$ - repo: https://github.com/codespell-project/codespell rev: v2.2.4 hooks: - id: codespell name: codespell description: Checks for common misspellings in text files. entry: codespell language: python types: [text] args: [] require_serial: false additional_dependencies: [] - repo: https://github.com/charliermarsh/ruff-pre-commit rev: 'v0.0.264' hooks: - id: ruff args: [--fix] - repo: https://github.com/adrienverge/yamllint rev: v1.31.0 hooks: - id: yamllint files: \.(yaml|yml)$ - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.2.0 hooks: - id: mypy additional_dependencies: - .[docs,test] - repo: https://github.com/asottile/pyupgrade rev: v3.3.2 hooks: - id: pyupgrade args: [--py38-plus] ``` ### ~/.cache/pre-commit/pre-commit.log (if present) _No response_
I am getting the same error when running 'pre-commit autoupdate'. i am able to do 'pre-commit run ...' I worked around the issue by running the autoupdate from an admin command prompt or PS. was working fine yesterday with 3.2.2 but not with 3.3.0 this morning. windows 11 python 3.10.11 > I am getting the same error when running 'pre-commit autoupdate'. i am able to do 'pre-commit run ...' I worked around the issue by running the autoupdate from an admin command prompt or PS. > > was working fine yesterday with 3.2.2 but not with 3.3.0 this morning. > > windows 11 python 3.10.11 Looks like I was mistaken on my workaround. It was pre-commit clean, followed by pre-commit run. elevated didn't matter. if it works outside if tox then it's probably an issue with your tox configuration perhaps try playing with passenv ? Sorry, corrected my original post. That was a mistake from when I was first writing the issue. (I thought it worked outside of tox, but that was because I hadn't updated my version outside of tox. I confirm it now doesn't work neither in tox, nor outside) oddly enough I can sort of reproduce this -- but not with the test suite. it appears to be a bug in git for windows so I'm reporting a bug there -- https://marc.info/?l=git&m=168303544023036&w=2 for now I'll add a small workaround in the source and remove it in ~6 months or so after git releases a fix for their bug
2023-05-02T13:55:23
pre-commit/pre-commit
2,885
pre-commit__pre-commit-2885
[ "2870" ]
c389ac0ba86355f42d8b973f0bb96cf77a5bcf48
diff --git a/pre_commit/languages/r.py b/pre_commit/languages/r.py --- a/pre_commit/languages/r.py +++ b/pre_commit/languages/r.py @@ -4,6 +4,8 @@ import os import shlex import shutil +import tempfile +import textwrap from typing import Generator from typing import Sequence @@ -21,6 +23,19 @@ health_check = lang_base.basic_health_check [email protected] +def _r_code_in_tempfile(code: str) -> Generator[str, None, None]: + """ + To avoid quoting and escaping issues, avoid `Rscript [options] -e {expr}` + but use `Rscript [options] path/to/file_with_expr.R` + """ + with tempfile.TemporaryDirectory() as tmpdir: + fname = os.path.join(tmpdir, 'script.R') + with open(fname, 'w') as f: + f.write(_inline_r_setup(textwrap.dedent(code))) + yield fname + + def get_env_patch(venv: str) -> PatchesT: return ( ('R_PROFILE_USER', os.path.join(venv, 'activate.R')), @@ -129,20 +144,19 @@ def install_environment( }} """ - cmd_output_b( - _rscript_exec(), '--vanilla', '-e', - _inline_r_setup(r_code_inst_environment), - cwd=env_dir, - ) + with _r_code_in_tempfile(r_code_inst_environment) as f: + cmd_output_b(_rscript_exec(), '--vanilla', f, cwd=env_dir) + if additional_dependencies: r_code_inst_add = 'renv::install(commandArgs(trailingOnly = TRUE))' with in_env(prefix, version): - cmd_output_b( - _rscript_exec(), *RSCRIPT_OPTS, '-e', - _inline_r_setup(r_code_inst_add), - *additional_dependencies, - cwd=env_dir, - ) + with _r_code_in_tempfile(r_code_inst_add) as f: + cmd_output_b( + _rscript_exec(), *RSCRIPT_OPTS, + f, + *additional_dependencies, + cwd=env_dir, + ) def _inline_r_setup(code: str) -> str: @@ -150,11 +164,16 @@ def _inline_r_setup(code: str) -> str: Some behaviour of R cannot be configured via env variables, but can only be configured via R options once R has started. These are set here. """ - with_option = f"""\ - options(install.packages.compile.from.source = "never", pkgType = "binary") - {code} - """ - return with_option + with_option = [ + textwrap.dedent("""\ + options( + install.packages.compile.from.source = "never", + pkgType = "binary" + ) + """), + code, + ] + return '\n'.join(with_option) def run_hook(
Avoid unquoting weirdness of Windows for `language: r` ### search you tried in the issue tracker never, r, found ### describe your issue Multiple reports in https://github.com/lorenzwalthert/precommit (https://github.com/lorenzwalthert/precommit/issues/441, https://github.com/lorenzwalthert/precommit/issues/473) were raised and describe a problem with (un)quoting the long string that runs when `language: r` is setup in `Rscript -e 'xxx'` where `'xxx'` contains [multiple levels of quotes](https://github.com/pre-commit/pre-commit/blob/6896025288691aafd015a4681c59dc105e61b614/pre_commit/languages/r.py#L101). For the readers convenience, the output looks like: ``` [INFO] Installing environment for https://github.com/lorenzwalthert/precommit. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Restored changes from C:\Users\USER\.cache\pre-commit\patch1678401203-36472. An unexpected error has occurred: CalledProcessError: command: ('C:/PROGRA~1/R/R-41~1.0\\bin\\Rscript.exe', '--vanilla', '-e', ' options(install.packages.compile.from.source = "never", pkgType = "binary")\n prefix_dir <- \'C:\\\\Users\\\\USER\\\\.cache\\\\pre-commit\\\\repovawmpj_r\'\n options(\n repos = c(CRAN = "https://cran.rstudio.com"),\n renv.consent = TRUE\n )\n source("renv/activate.R")\n renv::restore()\n activate_statement <- paste0(\n \'suppressWarnings({\',\n \'old <- setwd("\', getwd(), \'"); \',\n \'source("renv/activate.R"); \',\n \'setwd(old); \',\n \'renv::load("\', getwd(), \'");})\'\n )\n writeLines(activate_statement, \'activate.R\')\n is_package <- tryCatch(\n {\n path_desc <- file.path(prefix_dir, \'DESCRIPTION\')\n suppressWarnings(desc <- read.dcf(path_desc))\n "Package" %in% colnames(desc)\n },\n error = function(...) FALSE\n )\n if (is_package) {\n renv::install(prefix_dir)\n }\n \n ') return code: 1 stdout: (none) stderr: During startup - Warning messages: 1: Setting LC_COLLATE=en_US.UTF-8 failed 2: Setting LC_CTYPE=en_US.UTF-8 failed 3: Setting LC_MONETARY=en_US.UTF-8 failed 4: Setting LC_TIME=en_US.UTF-8 failed Error in options(install.packages.compile.from.source = never, pkgType = binary) : object 'never' not found Execution halted Check the log at C:\Users\USER\.cache\pre-commit\pre-commit.log ``` The solution described by @asottile in https://github.com/lorenzwalthert/precommit/issues/473#issuecomment-1511498032 is to probably write the contents to a temporary file and avoid unquoting within the expression (i.e. the term after `-e`). This should be quite straight forward. Question is if we can create a good test first to reproduce the offending behavior and whether or not there are tools already in pre-commit to deal with temp files etc. that we could use. ### pre-commit --version precommit 3.1.1 ### .pre-commit-config.yaml ```yaml repos: - repo: https://github.com/lorenzwalthert/precommit rev: v0.3.2.9007 hooks: - id: style-files ``` ### ~/.cache/pre-commit/pre-commit.log (if present) _No response_
`tempfile.NamedTemporaryFile` from the stdlib should be fine. arguably this is a bug in R itself since the commandline is correct
2023-05-15T07:49:58
pre-commit/pre-commit
2,905
pre-commit__pre-commit-2905
[ "2799" ]
f073f8e13c443a2d5eba4349bfcc9687c6cd240a
diff --git a/pre_commit/languages/ruby.py b/pre_commit/languages/ruby.py --- a/pre_commit/languages/ruby.py +++ b/pre_commit/languages/ruby.py @@ -114,6 +114,8 @@ def _install_ruby( def install_environment( prefix: Prefix, version: str, additional_dependencies: Sequence[str], ) -> None: + envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version) + if version != 'system': # pragma: win32 no cover _install_rbenv(prefix, version) with in_env(prefix, version): @@ -135,6 +137,8 @@ def install_environment( 'gem', 'install', '--no-document', '--no-format-executable', '--no-user-install', + '--install-dir', os.path.join(envdir, 'gems'), + '--bindir', os.path.join(envdir, 'gems', 'bin'), *prefix.star('.gem'), *additional_dependencies, ), )
No such file or directory: '/github/home/.cache/pre-commit/repo4mrvfeou/rbenv-system/.install_state_v1staging' ### search you tried in the issue tracker Found this one #1658 ### describe your issue Running pre-commit GitHub action in a [custom container](https://github.com/platform-engineering-org/helper/blob/main/Dockerfile). Workflow is [broken](https://github.com/platform-engineering-org/bootstrap/actions/runs/4342905858/jobs/7584289627): ``` [INFO] Installing environment for https://github.com/markdownlint/markdownlint. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexpected error has occurred: FileNotFoundError: [Errno 2] No such file or directory: '/github/home/.cache/pre-commit/repo4mrvfeou/rbenv-system/.install_state_v1staging' ``` ### pre-commit --version pre-commit 2.20.0 ### .pre-commit-config.yaml ```yaml --- ci: skip: [terraform_fmt, terraform_validate, terragrunt_validate] repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: end-of-file-fixer - id: trailing-whitespace args: - --markdown-linebreak-ext=md - id: check-docstring-first - id: requirements-txt-fixer - id: check-merge-conflict - id: no-commit-to-branch args: - "--branch" - "main" - id: check-symlinks - id: detect-private-key - id: detect-aws-credentials args: - --allow-missing-credentials - id: check-json - repo: https://github.com/markdownlint/markdownlint rev: v0.12.0 hooks: - id: markdownlint additional_dependencies: [rake] - repo: https://github.com/maxbrunet/pre-commit-renovate rev: 34.157.1 hooks: - id: renovate-config-validator - repo: https://github.com/antonbabenko/pre-commit-terraform rev: v1.77.1 hooks: - id: terraform_providers_lock args: - --tf-init-args=-upgrade - id: terraform_fmt - id: terraform_validate - id: terragrunt_validate ``` ### ~/.cache/pre-commit/pre-commit.log (if present) _No response_
you found an exact duplicate, why did you make an issue? Because I didn't understand how to fix my problem with the information provided on the other closed issue you've not shown what you've tried so I don't know how to help you. right now it looks like you've tried nothing I've tried to check rbenv is installed in the container. It is not. I've checked the ruby version. It is 3.0.4p208 (2022-04-12 revision 3fa771dded) [x86_64-linux]. What else can I try? clearly that container is broken -- why do you need that container? also looks like your CI is running both pre-commit.ci and github actions pre-commit -- which is kind of wasteful > clearly that container is broken -- why do you need that container? also looks like your CI is running both pre-commit.ci and github actions pre-commit -- which is kind of wasteful Agree. It is broken but I don't have enough ruby expriance to figure out what is broken and fix it. The container is built by me and it used for baking all my team tooling in a container image instead of installing/upgrading them on our laptops. if your company wants paid support I'm happy to provide it -- but this seems like you've already got several solutions which don't involve that container I am pocking the pre-commit code. It seems like the language ruby ENVIRONMENT_DIR is set to `rbenv` while the container image doesn't have it. The error is persistent even if `rbenv` is installed. In repository.py line 108, it tries to write a file in a directory which doesn't exist. Could you provide me a hint where it is created? @asottile I'm seeing the same issue described here, and do not have `rbenv` installed so #1658 doesn't give a solution. I've looked in `~/.cache/pre-commit/pre-commit.log` but I don't see any useful information. Looking at the code: https://github.com/pre-commit/pre-commit/blob/8d84a7a2702b074a8b46f5e38af28bd576291251/pre_commit/languages/ruby.py#L114 This seems to be responsible for creating the environment directory. If the version is `system`, we don't run `rbenv init -`. So are we expecting `gem build ...` to create the `rbenv-system` directory? If the output of `gem build ...` contains some useful information on what's going wrong, it's being dropped: https://github.com/pre-commit/pre-commit/blob/8d84a7a2702b074a8b46f5e38af28bd576291251/pre_commit/util.py#L89 This collects the stdout & stderr of the called process and returns them. https://github.com/pre-commit/pre-commit/blob/8d84a7a2702b074a8b46f5e38af28bd576291251/pre_commit/lang_base.py#L91 This calls `cmd_output_b() but ignores the return values. Perhaps more verbose output is needed in the case of an error. ## Contents of `~/.cache/pre-commit/pre-commit.log` ### version information ``` pre-commit version: 3.2.2 git --version: git version 2.39.2 sys.version: 3.10.10 (main, Mar 26 2023, 19:47:56) [GCC 12.2.1 20230121] sys.executable: /home/pbarker/Projects/pbarker.dev/venv/bin/python os.name: posix sys.platform: linux ``` ### error information ``` An unexpected error has occurred: FileNotFoundError: [Errno 2] No such file or directory: '/home/pbarker/.cache/pre-commit/repoiuzm_cni/rbenv-system/.install_state_v1staging' ``` ``` Traceback (most recent call last): File "/home/pbarker/Projects/pbarker.dev/venv/lib/python3.10/site-packages/pre_commit/error_handler.py", line 73, in error_handler yield File "/home/pbarker/Projects/pbarker.dev/venv/lib/python3.10/site-packages/pre_commit/main.py", line 409, in main return run(args.config, store, args) File "/home/pbarker/Projects/pbarker.dev/venv/lib/python3.10/site-packages/pre_commit/commands/run.py", line 442, in run install_hook_envs(to_install, store) File "/home/pbarker/Projects/pbarker.dev/venv/lib/python3.10/site-packages/pre_commit/repository.py", line 248, in install_hook_envs _hook_install(hook) File "/home/pbarker/Projects/pbarker.dev/venv/lib/python3.10/site-packages/pre_commit/repository.py", line 111, in _hook_install with open(staging, 'w') as state_file: FileNotFoundError: [Errno 2] No such file or directory: '/home/pbarker/.cache/pre-commit/repoiuzm_cni/rbenv-system/.install_state_v1staging' ``` I'm getting the same error on Windows, ruby 3.2.2, no rbenv. [pre-commit.log](https://github.com/pre-commit/pre-commit/files/11664668/pre-commit.log) Seeing same thing as https://github.com/pre-commit/pre-commit/issues/2799#issuecomment-1510465720 Occurs during `pre-commit install-hooks` with this hook: ```yaml repos: - repo: https://github.com/rubocop/rubocop rev: v1.52.0 hooks: - id: rubocop ``` ### version information ``` pre-commit version: 3.3.2 git --version: git version 2.39.3 sys.version: 3.11.2 (main, Mar 9 2023, 21:49:05) [GCC 11.3.1 20220421 (Red Hat 11.3.1-2)] sys.executable: .../bin/python3.11 os.name: posix sys.platform: linux ``` ### error information ``` An unexpected error has occurred: FileNotFoundError: [Errno 2] No such file or directory: '/root/.cache/pre-commit/repo238a8i_c/rbenv-system/.install_state_v1staging' ``` ``` Traceback (most recent call last): File ".../lib/python3.11/site-packages/pre_commit/error_handler.py", line 73, in error_handler yield File ".../lib/python3.11/site-packages/pre_commit/main.py", line 410, in main return install_hooks(args.config, store) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File ".../lib/python3.11/site-packages/pre_commit/commands/install_uninstall.py", line 146, in install_hooks install_hook_envs(all_hooks(load_config(config_file), store), store) File ".../lib/python3.11/site-packages/pre_commit/repository.py", line 248, in install_hook_envs _hook_install(hook) File ".../lib/python3.11/site-packages/pre_commit/repository.py", line 111, in _hook_install with open(staging, 'w') as state_file: ^^^^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: '/root/.cache/pre-commit/repo238a8i_c/rbenv-system/.install_state_v1staging' ``` (I've partially elided the Python paths above.) There directory `/root/.cache/pre-commit/repo238a8i_c/rbenv-system` does NOT exist. I'm not sure what's supposed to create it. Ruby is installed via `dnf -y -q install ruby ruby-devel`: ``` Installed: annobin-11.05-1.el9.x86_64 dwz-0.14-3.el9.x86_64 efi-srpm-macros-6-2.el9_0.0.1.noarch file-5.39-12.el9.x86_64 fonts-srpm-macros-1:2.0.5-7.el9.1.noarch gcc-plugin-annobin-11.3.1-4.3.el9.alma.x86_64 ghc-srpm-macros-1.5.0-6.el9.noarch glibc-gconv-extra-2.34-60.el9.x86_64 go-srpm-macros-3.2.0-1.el9.noarch kernel-srpm-macros-1.0-12.el9.noarch lua-srpm-macros-1-6.el9.noarch ocaml-srpm-macros-6-6.el9.noarch openblas-srpm-macros-2-11.el9.noarch perl-srpm-macros-1-41.el9.noarch pyproject-srpm-macros-1.6.2-1.el9.noarch python-srpm-macros-3.9-52.el9.noarch qt5-srpm-macros-5.15.3-1.el9.noarch redhat-rpm-config-199-1.el9.alma.noarch ruby-3.0.4-160.el9_0.x86_64 ruby-default-gems-3.0.4-160.el9_0.noarch ruby-devel-3.0.4-160.el9_0.x86_64 ruby-libs-3.0.4-160.el9_0.x86_64 rubygem-bigdecimal-3.0.0-160.el9_0.x86_64 rubygem-bundler-2.2.33-160.el9_0.noarch rubygem-io-console-0.5.7-160.el9_0.x86_64 rubygem-json-2.5.1-160.el9_0.x86_64 rubygem-psych-3.3.2-160.el9_0.x86_64 rubygem-rdoc-6.3.3-160.el9_0.noarch rubygems-3.2.33-160.el9_0.noarch rust-srpm-macros-17-4.el9.noarch zip-3.0-35.el9.x86_64 ``` By editing the source code to get the gem output I'm seeing this: ``` [root@e736e09e3d9d foo]# pre-commit install-hooks cmd=('git', 'rev-parse', '--show-cdup') cmd=('git', 'rev-parse', '--is-inside-git-dir') [INFO] Installing environment for https://github.com/rubocop/rubocop. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... cmd=('gem', 'build', 'rubocop.gemspec') stdout: Successfully built RubyGem Name: rubocop Version: 1.52.0 File: rubocop-1.52.0.gem stderr: WARNING: open-ended dependency on parser (>= 3.2.0.0) is not recommended if parser is semantically versioned, use: add_runtime_dependency 'parser', '~> 3.2', '>= 3.2.0.0' WARNING: See https://guides.rubygems.org/specification-reference/ for help cmd=('gem', 'install', '--no-document', '--no-format-executable', '--no-user-install', 'rubocop-1.52.0.gem') stdout: Successfully installed rubocop-1.52.0 1 gem installed stderr: An unexpected error has occurred: FileNotFoundError: [Errno 2] No such file or directory: '/root/.cache/pre-commit/repo98m3m8cs/rbenv-system/.install_state_v1staging' cmd=('git', '--version') Check the log at /root/.cache/pre-commit/pre-commit.log ``` Gem env: ``` RubyGems Environment: - RUBYGEMS VERSION: 3.2.33 - RUBY VERSION: 3.0.4 (2022-04-12 patchlevel 208) [x86_64-linux] - INSTALLATION DIRECTORY: /usr/share/gems - USER INSTALLATION DIRECTORY: /root/.local/share/gem/ruby - RUBY EXECUTABLE: /usr/bin/ruby - GIT EXECUTABLE: /usr/bin/git - EXECUTABLE DIRECTORY: /usr/bin - SPEC CACHE DIRECTORY: /root/.local/share/gem/specs - SYSTEM CONFIGURATION DIRECTORY: /etc - RUBYGEMS PLATFORMS: - ruby - x86_64-linux - GEM PATHS: - /usr/share/gems - /root/.local/share/gem/ruby - /usr/local/share/gems - GEM CONFIGURATION: - :update_sources => true - :verbose => true - :backtrace => false - :bulk_threshold => 1000 - "gem" => "--install-dir=/usr/local/share/gems --bindir /usr/local/bin" - REMOTE SOURCES: - https://rubygems.org/ - SHELL PATH: - /root/.local/bin - /root/bin - /opt/python/bin - /usr/local/sbin - /usr/local/bin - /usr/sbin - /usr/bin - /sbin - /bin ``` can you share your environment and gem and Ruby rc files? @asottile I edited my comment above yours to add more information, including the stdout/stderr of the gem build commands and the output of `gem env`. your `--install-dir` option appears to be breaking gem -- any idea where that's coming from? we use `GEM_HOME` to specify the target installation for gems > your `--install-dir` option appears to be breaking gem -- any idea where that's coming from? we use `GEM_HOME` to specify the target installation for gems Hmm, either Red Hat's packaging or possibly it's something with newer versions of gem? In my experience, you have to set _both_ `GEM_HOME` and `GEM_PATH`. `GEM_PATH` is for lookup, `GEM_HOME` is installation target -- only the latter is necessary for pre-commit since it intends to isolate from others (instead of cascading gem PATH lookup) To be clear, the `gem env` output I shared is running it directly from the shell, not with `GEM_HOME` as set by pre-commit. yes of course -- the useful part from `gem env` appears to be this configuration override: ``` - "gem" => "--install-dir=/usr/local/share/gems --bindir /usr/local/bin" ``` afaik that's coming from some config file -- are you sure this is an otherwise empty image? Here's what `gem env` looks like when I run it from pre-commit: ``` cmd=('gem', 'env') stdout: RubyGems Environment: - RUBYGEMS VERSION: 3.2.33 - RUBY VERSION: 3.0.4 (2022-04-12 patchlevel 208) [x86_64-linux] - INSTALLATION DIRECTORY: /root/.cache/pre-commit/repo98m3m8cs/rbenv-system/gems - USER INSTALLATION DIRECTORY: /root/.local/share/gem/ruby - RUBY EXECUTABLE: /usr/bin/ruby - GIT EXECUTABLE: /usr/bin/git - EXECUTABLE DIRECTORY: /root/.cache/pre-commit/repo98m3m8cs/rbenv-system/gems/bin - SPEC CACHE DIRECTORY: /root/.local/share/gem/specs - SYSTEM CONFIGURATION DIRECTORY: /etc - RUBYGEMS PLATFORMS: - ruby - x86_64-linux - GEM PATHS: - /root/.cache/pre-commit/repo98m3m8cs/rbenv-system/gems - /root/.local/share/gem/ruby - /usr/share/gems - /usr/local/share/gems - GEM CONFIGURATION: - :update_sources => true - :verbose => true - :backtrace => false - :bulk_threshold => 1000 - "gem" => "--install-dir=/usr/local/share/gems --bindir /usr/local/bin" - REMOTE SOURCES: - https://rubygems.org/ - SHELL PATH: - /root/.cache/pre-commit/repo98m3m8cs/rbenv-system/gems/bin - /root/.local/bin - /root/bin - /opt/python/bin - /usr/local/sbin - /usr/local/bin - /usr/sbin - /usr/bin - /sbin - /bin ``` Is that not what we expect? This image is based on Alma 9 and is customized for Python. Ruby is installed via `dnf`. Hmm, you're right, rubocop is installing to `/usr/local/share/gems/gems/rubocop-1.52.`. I gather we want it to be installing to `/root/.cache/pre-commit/repo98m3m8cs/rbenv-system/gems`. Let me see if I can track that down. This is apparently an issue with Alma Linux (aka Red Hat) 9.2. You can repro it with: ``` $ docker run -it almalinux:9.2 bash # dnf -yq install git-core ruby-devel rubygems gcc make pip # pip install pre-commit # git init foo # cd foo # cat >.pre-commit-config.yaml<<EOF repos: - repo: https://github.com/rubocop/rubocop rev: v1.52.0 hooks: - id: rubocop fail_fast: true EOF # pre-commit install-hooks ``` And I gather it's an issue with how Alma Linux packages up rubygems: ``` - "gem" => "--install-dir=/usr/local/share/gems --bindir /usr/local/bin" ``` can you report it to them? unconditionally changing `--install-dir` seems wrong especially when the user is requesting a different one I'm really not a fan of Ruby, but I don't think this is something RedHat is likely to fix. FWIW: ``` [root@f4dbfd9c2ee3 /]# irb irb(main):001:0> Gem.operating_system_defaults => {"gem"=>"--install-dir=/usr/local/share/gems --bindir /usr/local/bin"} ``` That's where it comes from. RedHat's answer will probably be: "Pound sand. You shouldn't be using the system ruby. Install your own ruby." RubyGems accommodated this issue: https://github.com/rubygems/rubygems/pull/5566 Can pre-commit use `--install-dir` instead of `GEM_HOME`? Work-around: ``` $ rm -f /usr/share/rubygems/rubygems/defaults/operating_system.rb ``` Blech. No more time for shaving yaks so that's the solution I'm going to live with. This looks to be an intended use-case by RubyGems: https://github.com/rubygems/rubygems/pull/2116 This means that pre-commit is not compatible with any packaged gem that uses this feature. If you don't want to accommodate it I understand. Would you accept a PR that at least causes pre-commit to emit a more helpful error message? And here's where upstream does their customization: https://src.fedoraproject.org/rpms/ruby/blob/rawhide/f/ruby.spec#_736 https://src.fedoraproject.org/rpms/ruby/blob/rawhide/f/operating_system.rb Note that Gentoo has similar customisation: https://github.com/gentoo/gentoo/blob/master/dev-ruby/rubygems/files/gentoo-defaults-5.rb @jaysoffian did you want to try your idea from https://github.com/pre-commit/pre-commit/issues/2799#issuecomment-1581744060 ? > @jaysoffian did you want to try your idea from [#2799 (comment)](https://github.com/pre-commit/pre-commit/issues/2799#issuecomment-1581744060) ? @asottile this patch works for me under the environment described in https://github.com/pre-commit/pre-commit/issues/2799#issuecomment-1581700041 ```diff diff --git i/pre_commit/languages/ruby.py w/pre_commit/languages/ruby.py index 76631f2532..13cc628d80 100644 --- i/pre_commit/languages/ruby.py +++ w/pre_commit/languages/ruby.py @@ -125,6 +125,7 @@ def install_environment( # Need to call this after installing to set up the shims lang_base.setup_cmd(prefix, ('rbenv', 'rehash')) + envdir = lang_base.environment_dir(prefix, ENVIRONMENT_DIR, version) with in_env(prefix, version): lang_base.setup_cmd( prefix, ('gem', 'build', *prefix.star('.gemspec')), @@ -135,6 +136,8 @@ def install_environment( 'gem', 'install', '--no-document', '--no-format-executable', '--no-user-install', + '--install-dir', os.path.join(envdir, 'gems'), + '--bindir', os.path.join(envdir, 'bin'), *prefix.star('.gem'), *additional_dependencies, ), ) ``` Would you like a PR? do you want to send a pr?
2023-06-13T22:03:27
pre-commit/pre-commit
2,979
pre-commit__pre-commit-2979
[ "2978" ]
9ebda918899ec1f2bb3bb8599b0da2548f74703a
diff --git a/pre_commit/xargs.py b/pre_commit/xargs.py --- a/pre_commit/xargs.py +++ b/pre_commit/xargs.py @@ -24,6 +24,14 @@ def cpu_count() -> int: + try: + # On systems that support it, this will return a more accurate count of + # usable CPUs for the current process, which will take into account + # cgroup limits + return len(os.sched_getaffinity(0)) + except AttributeError: + pass + try: return multiprocessing.cpu_count() except NotImplementedError:
diff --git a/tests/lang_base_test.py b/tests/lang_base_test.py --- a/tests/lang_base_test.py +++ b/tests/lang_base_test.py @@ -30,6 +30,19 @@ def fake_expanduser(pth): yield [email protected] +def no_sched_getaffinity(): + # Simulates an OS without os.sched_getaffinity available (mac/windows) + # https://docs.python.org/3/library/os.html#interface-to-the-scheduler + with mock.patch.object( + os, + 'sched_getaffinity', + create=True, + side_effect=AttributeError, + ): + yield + + def test_exe_exists_does_not_exist(find_exe_mck, homedir_mck): find_exe_mck.return_value = None assert lang_base.exe_exists('ruby') is False @@ -116,7 +129,17 @@ def test_no_env_noop(tmp_path): assert before == inside == after -def test_target_concurrency_normal(): +def test_target_concurrency_sched_getaffinity(no_sched_getaffinity): + with mock.patch.object( + os, + 'sched_getaffinity', + return_value=set(range(345)), + ): + with mock.patch.dict(os.environ, clear=True): + assert lang_base.target_concurrency() == 345 + + +def test_target_concurrency_without_sched_getaffinity(no_sched_getaffinity): with mock.patch.object(multiprocessing, 'cpu_count', return_value=123): with mock.patch.dict(os.environ, {}, clear=True): assert lang_base.target_concurrency() == 123 @@ -134,7 +157,7 @@ def test_target_concurrency_on_travis(): assert lang_base.target_concurrency() == 2 -def test_target_concurrency_cpu_count_not_implemented(): +def test_target_concurrency_cpu_count_not_implemented(no_sched_getaffinity): with mock.patch.object( multiprocessing, 'cpu_count', side_effect=NotImplementedError, ):
CPU count logic does not distinguish "usable" CPUs inside cgroup'd containers (e.g. inside k8s) ### search you tried in the issue tracker multiprocessing, k8s, usable, cpu ### describe your issue When invoking pre-commit from within a container environment with cgroup cpu enforcement, pre-commit fans out more than expected (based on the total number of CPUs rather than the number of _usable_ CPUs). This ends up causing unexpected behaviour and makes it hard to optimise for performance when running hooks in CI inside containers (since [pre-commit's parallelism is non-configurable](https://github.com/pre-commit/pre-commit/issues/1710)), which leaves us with either "shard using too many CPUs" or `require_serial: true`, both of which aren't ideal. The cause is seemingly due to the implementation in xargs.py: https://github.com/pre-commit/pre-commit/blob/bde292b51078357384602ebe6b9b27b1906987e5/pre_commit/xargs.py#L28 which uses `multiprocessing.cpu_count()`, which is documented to [not [be] equivalent to the number of CPUs the current process can use](https://docs.python.org/3/library/multiprocessing.html#:~:text=This%20number%20is%20not%20equivalent%20to%20the%20number%20of%20CPUs%20the%20current%20process%20can%20use.%20The%20number%20of%20usable%20CPUs%20can%20be%20obtained%20with%20len(os.sched_getaffinity(0))). This is confirmed by running `python3 -c 'import multiprocessing; print(multiprocessing.cpu_count())'` inside the container environment: the number is higher than expected. From the docs, it looks like a cgroup-compatible way of grabbing the number of usable CPUs would be to use `len(os.sched_getaffinity(0))`, but I don't know if that has undesirable downsides. I also don't know if this would be a disruptive breaking change to anyone relying on the old behaviour, so I wanted to make this issue first to get your thoughts. ### pre-commit --version pre-commit 2.19.0 ### .pre-commit-config.yaml ```yaml n/a - can provide a dummy config invoking `python3 -c 'import multiprocessing; print(multiprocessing.cpu_count())'` if more info needed, but this isn't specific to any one hook or config option ``` ### ~/.cache/pre-commit/pre-commit.log (if present) _No response_
sched_getaffinity isn't available on other platforms but could probably be used if available
2023-08-29T02:23:20
pre-commit/pre-commit
2,996
pre-commit__pre-commit-2996
[ "1983" ]
e2c6a822c79e3a7dbb206bfa1ab87928ec25848b
diff --git a/pre_commit/languages/node.py b/pre_commit/languages/node.py --- a/pre_commit/languages/node.py +++ b/pre_commit/languages/node.py @@ -93,7 +93,7 @@ def install_environment( # install as if we installed from git local_install_cmd = ( - 'npm', 'install', '--dev', '--prod', + 'npm', 'install', '--include=dev', '--include=prod', '--ignore-prepublish', '--no-progress', '--no-save', ) lang_base.setup_cmd(prefix, local_install_cmd)
Use of --dev deprecated for npm I'm seeing this warning sometimes (output seems to be hidden unless the install fails): ``` npm WARN install Usage of the `--dev` option is deprecated. Use `--include=dev` instead. ``` Which seems to be because of this: https://github.com/pre-commit/pre-commit/blob/fe436f1eb09dfdd67032b4f9f8dfa543fb99cf06/pre_commit/languages/node.py#L104 The problem with this command was that it installed dependencies recursively, rendering them useless (AFAICT, not a node expert). The developers decided it was only a footgun in https://github.com/npm/npm/issues/5554#issuecomment-56121953 and deprecated in https://github.com/npm/npm/issues/6200.
it's a break either way to change it -- since old npm doesn't support the new flag the unfortunate thing is that's the command that was recommended by the npm team so... What about selecting the flag based on npm version, could that be done here? If so I could look up the version that --include=dev was added. good luck parsing npm's version and doing anything reasonable with it 😆 . I don't think that's a solution which gives long term stability did some research on this, and it looks like we can't replace the code we have for this until *at least* npm 6.x is no longer supported. which would be the EOL of node 14 2023-04-30 [@asottile ](https://github.com/pre-commit/pre-commit/issues/1983#issuecomment-908807469) And here we are.
2023-09-08T13:13:36
pre-commit/pre-commit
2,998
pre-commit__pre-commit-2998
[ "2935" ]
0845e4e816885be30b8bb678e70a292ebaf25275
diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py --- a/pre_commit/commands/run.py +++ b/pre_commit/commands/run.py @@ -10,7 +10,8 @@ import time import unicodedata from typing import Any -from typing import Collection +from typing import Generator +from typing import Iterable from typing import MutableMapping from typing import Sequence @@ -57,20 +58,20 @@ def _full_msg( def filter_by_include_exclude( - names: Collection[str], + names: Iterable[str], include: str, exclude: str, -) -> list[str]: +) -> Generator[str, None, None]: include_re, exclude_re = re.compile(include), re.compile(exclude) - return [ + return ( filename for filename in names if include_re.search(filename) if not exclude_re.search(filename) - ] + ) class Classifier: - def __init__(self, filenames: Collection[str]) -> None: + def __init__(self, filenames: Iterable[str]) -> None: self.filenames = [f for f in filenames if os.path.lexists(f)] @functools.lru_cache(maxsize=None) @@ -79,15 +80,14 @@ def _types_for_file(self, filename: str) -> set[str]: def by_types( self, - names: Sequence[str], - types: Collection[str], - types_or: Collection[str], - exclude_types: Collection[str], - ) -> list[str]: + names: Iterable[str], + types: Iterable[str], + types_or: Iterable[str], + exclude_types: Iterable[str], + ) -> Generator[str, None, None]: types = frozenset(types) types_or = frozenset(types_or) exclude_types = frozenset(exclude_types) - ret = [] for filename in names: tags = self._types_for_file(filename) if ( @@ -95,24 +95,24 @@ def by_types( (not types_or or tags & types_or) and not tags & exclude_types ): - ret.append(filename) - return ret - - def filenames_for_hook(self, hook: Hook) -> tuple[str, ...]: - names = self.filenames - names = filter_by_include_exclude(names, hook.files, hook.exclude) - names = self.by_types( - names, + yield filename + + def filenames_for_hook(self, hook: Hook) -> Generator[str, None, None]: + return self.by_types( + filter_by_include_exclude( + self.filenames, + hook.files, + hook.exclude, + ), hook.types, hook.types_or, hook.exclude_types, ) - return tuple(names) @classmethod def from_config( cls, - filenames: Collection[str], + filenames: Iterable[str], include: str, exclude: str, ) -> Classifier: @@ -121,7 +121,7 @@ def from_config( # this also makes improperly quoted shell-based hooks work better # see #1173 if os.altsep == '/' and os.sep == '\\': - filenames = [f.replace(os.sep, os.altsep) for f in filenames] + filenames = (f.replace(os.sep, os.altsep) for f in filenames) filenames = filter_by_include_exclude(filenames, include, exclude) return Classifier(filenames) @@ -148,7 +148,7 @@ def _run_single_hook( verbose: bool, use_color: bool, ) -> tuple[bool, bytes]: - filenames = classifier.filenames_for_hook(hook) + filenames = tuple(classifier.filenames_for_hook(hook)) if hook.id in skips or hook.alias in skips: output.write( @@ -250,7 +250,7 @@ def _compute_cols(hooks: Sequence[Hook]) -> int: return max(cols, 80) -def _all_filenames(args: argparse.Namespace) -> Collection[str]: +def _all_filenames(args: argparse.Namespace) -> Iterable[str]: # these hooks do not operate on files if args.hook_stage in { 'post-checkout', 'post-commit', 'post-merge', 'post-rewrite', diff --git a/pre_commit/meta_hooks/check_hooks_apply.py b/pre_commit/meta_hooks/check_hooks_apply.py --- a/pre_commit/meta_hooks/check_hooks_apply.py +++ b/pre_commit/meta_hooks/check_hooks_apply.py @@ -21,7 +21,7 @@ def check_all_hooks_match_files(config_file: str) -> int: for hook in all_hooks(config, Store()): if hook.always_run or hook.language == 'fail': continue - elif not classifier.filenames_for_hook(hook): + elif not any(classifier.filenames_for_hook(hook)): print(f'{hook.id} does not apply to this repository') retv = 1 diff --git a/pre_commit/meta_hooks/check_useless_excludes.py b/pre_commit/meta_hooks/check_useless_excludes.py --- a/pre_commit/meta_hooks/check_useless_excludes.py +++ b/pre_commit/meta_hooks/check_useless_excludes.py @@ -2,6 +2,7 @@ import argparse import re +from typing import Iterable from typing import Sequence from cfgv import apply_defaults @@ -14,7 +15,7 @@ def exclude_matches_any( - filenames: Sequence[str], + filenames: Iterable[str], include: str, exclude: str, ) -> bool: @@ -50,11 +51,12 @@ def check_useless_excludes(config_file: str) -> int: # Not actually a manifest dict, but this more accurately reflects # the defaults applied during runtime hook = apply_defaults(hook, MANIFEST_HOOK_DICT) - names = classifier.filenames - types = hook['types'] - types_or = hook['types_or'] - exclude_types = hook['exclude_types'] - names = classifier.by_types(names, types, types_or, exclude_types) + names = classifier.by_types( + classifier.filenames, + hook['types'], + hook['types_or'], + hook['exclude_types'], + ) include, exclude = hook['files'], hook['exclude'] if not exclude_matches_any(names, include, exclude): print(
diff --git a/tests/commands/run_test.py b/tests/commands/run_test.py --- a/tests/commands/run_test.py +++ b/tests/commands/run_test.py @@ -1127,8 +1127,8 @@ def test_classifier_empty_types_or(tmpdir): types_or=[], exclude_types=[], ) - assert for_symlink == ['foo'] - assert for_file == ['bar'] + assert tuple(for_symlink) == ('foo',) + assert tuple(for_file) == ('bar',) @pytest.fixture @@ -1142,33 +1142,33 @@ def some_filenames(): def test_include_exclude_base_case(some_filenames): ret = filter_by_include_exclude(some_filenames, '', '^$') - assert ret == [ + assert tuple(ret) == ( '.pre-commit-hooks.yaml', 'pre_commit/git.py', 'pre_commit/main.py', - ] + ) def test_matches_broken_symlink(tmpdir): with tmpdir.as_cwd(): os.symlink('does-not-exist', 'link') ret = filter_by_include_exclude({'link'}, '', '^$') - assert ret == ['link'] + assert tuple(ret) == ('link',) def test_include_exclude_total_match(some_filenames): ret = filter_by_include_exclude(some_filenames, r'^.*\.py$', '^$') - assert ret == ['pre_commit/git.py', 'pre_commit/main.py'] + assert tuple(ret) == ('pre_commit/git.py', 'pre_commit/main.py') def test_include_exclude_does_search_instead_of_match(some_filenames): ret = filter_by_include_exclude(some_filenames, r'\.yaml$', '^$') - assert ret == ['.pre-commit-hooks.yaml'] + assert tuple(ret) == ('.pre-commit-hooks.yaml',) def test_include_exclude_exclude_removes_files(some_filenames): ret = filter_by_include_exclude(some_filenames, '', r'\.py$') - assert ret == ['.pre-commit-hooks.yaml'] + assert tuple(ret) == ('.pre-commit-hooks.yaml',) def test_args_hook_only(cap_out, store, repo_with_passing_hook):
Short-circuit the `check-hooks-apply` hook ### search you tried in the issue tracker check-hooks-apply ### describe your actual problem I was looking at the implementation of `check_hooks_apply` and noticed that while the `filenames_for_hook` function returns multiple matching files, the caller is only interested in whether the tuple is empty or not. I was curious if short-circuiting would have any benefit: I prototyped a function `Classifier.any_filenames_for_hook` which short-circuits: ```python def any_filenames_for_hook(self, hook: Hook) -> bool: include_re, exclude_re = re.compile(hook.files), re.compile(hook.exclude) types, types_or, exclude_types = ( frozenset(hook.types), frozenset(hook.types_or), frozenset(hook.exclude_types), ) for i, name in enumerate(self.filenames): if include_re.search(name) and not exclude_re.search(name): return True tags = self._types_for_file(name) if ( tags >= types and (not types or tags & types_or) and not tags & exclude_types ): return True return False ``` ```diff for hook in all_hooks(config, Store()): if hook.always_run or hook.language == 'fail': continue - elif not classifier.filenames_for_hook(hook): + elif not classifier.any_filenames_for_hook(hook): print(f'{hook.id} does not apply to this repository') retv = 1 ``` Just to try it out, I applied this change in my pre-commit install directory and profiled with `hyperfine` on a local repo. The repo has about 12000 files. The short-circuit version ran about 20% faster. I also added logging and saw the short-circuit version cut out after ~26 files, whereas the existing version looks at all 12000. Old ```console $ hyperfine 'pre-commit run check-hooks-apply --all-files' Benchmark 1: pre-commit run check-hooks-apply --all-files Time (mean ± σ): 1.253 s ± 0.066 s [User: 0.546 s, System: 0.695 s] Range (min … max): 1.193 s … 1.419 s 10 runs ``` New ```console $ hyperfine 'pre-commit run check-hooks-apply --all-files' Benchmark 1: pre-commit run check-hooks-apply --all-files Time (mean ± σ): 969.9 ms ± 65.6 ms [User: 429.0 ms, System: 535.0 ms] Range (min … max): 873.1 ms … 1067.6 ms 10 runs ``` ### pre-commit --version 3.2.2
I'd be concerned that the two functions would drift -- the current implementation directly matches what pre-commit would do. I'm not sure the performance benefits are worth it? Agreed, the POC was to measure the improvement. I can take a stab at unifying the two (for example refactor `filenames_for_hook` to return an iterator) but in general if even that causes more harm than good I'm happy to close this issue sure give that a shot -- though sometimes a generator will be slower but maybe not in this case?
2023-09-10T01:53:16
pre-commit/pre-commit
3,130
pre-commit__pre-commit-3130
[ "2722" ]
15bd0c7993587dc7d739ac6b1ab939eb9639bc1e
diff --git a/pre_commit/languages/golang.py b/pre_commit/languages/golang.py --- a/pre_commit/languages/golang.py +++ b/pre_commit/languages/golang.py @@ -23,6 +23,7 @@ from pre_commit.envcontext import envcontext from pre_commit.envcontext import PatchesT from pre_commit.envcontext import Var +from pre_commit.git import no_git_env from pre_commit.prefix import Prefix from pre_commit.util import cmd_output from pre_commit.util import rmtree @@ -141,7 +142,7 @@ def install_environment( else: gopath = env_dir - env = dict(os.environ, GOPATH=gopath) + env = no_git_env(dict(os.environ, GOPATH=gopath)) env.pop('GOBIN', None) if version != 'system': env['GOROOT'] = os.path.join(env_dir, '.go')
diff --git a/tests/languages/golang_test.py b/tests/languages/golang_test.py --- a/tests/languages/golang_test.py +++ b/tests/languages/golang_test.py @@ -7,10 +7,16 @@ import pre_commit.constants as C from pre_commit import lang_base +from pre_commit.commands.install_uninstall import install from pre_commit.envcontext import envcontext from pre_commit.languages import golang from pre_commit.store import _make_local_repo +from pre_commit.util import cmd_output +from testing.fixtures import add_config_to_repo +from testing.fixtures import make_config_from_repo from testing.language_helpers import run_language +from testing.util import cmd_output_mocked_pre_commit_home +from testing.util import git_commit ACTUAL_GET_DEFAULT_VERSION = golang.get_default_version.__wrapped__ @@ -134,3 +140,28 @@ def test_local_golang_additional_deps(tmp_path): def test_golang_hook_still_works_when_gobin_is_set(tmp_path): with envcontext((('GOBIN', str(tmp_path.joinpath('gobin'))),)): test_golang_system(tmp_path) + + +def test_during_commit_all(tmp_path, tempdir_factory, store, in_git_dir): + hook_dir = tmp_path.joinpath('hook') + hook_dir.mkdir() + _make_hello_world(hook_dir) + hook_dir.joinpath('.pre-commit-hooks.yaml').write_text( + '- id: hello-world\n' + ' name: hello world\n' + ' entry: golang-hello-world\n' + ' language: golang\n' + ' always_run: true\n', + ) + cmd_output('git', 'init', hook_dir) + cmd_output('git', 'add', '.', cwd=hook_dir) + git_commit(cwd=hook_dir) + + add_config_to_repo(in_git_dir, make_config_from_repo(hook_dir)) + + assert not install(C.CONFIG_FILE, store, hook_types=['pre-commit']) + + git_commit( + fn=cmd_output_mocked_pre_commit_home, + tempdir_factory=tempdir_factory, + )
command: `go install` fails with: error obtaining VCS status: exit status 128 while installing check ### search you tried in the issue tracker error obtaining VCS status: exit status ### describe your issue I was just running the pre-commit checks. It looks like the failures started after the update. ```shell git commit -am "My ultimate commit" ``` Output: ``` [INFO] Installing environment for https://github.com/stackrox/kube-linter. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexpected error has occurred: CalledProcessError: command: ('/opt/homebrew/bin/go', 'install', './...') return code: 1 stdout: (none) stderr: go: downloading github.com/fatih/color v1.13.0 go: downloading github.com/Masterminds/sprig/v3 v3.2.3 go: downloading github.com/pkg/errors v0.9.1 ... go: downloading github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. ``` I have also tried to run: `pre-commit clean` but it did not help. ### pre-commit --version pre-commit 3.0.0 ### .pre-commit-config.yaml ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: check-added-large-files - id: check-merge-conflict - id: detect-aws-credentials args: - "--allow-missing-credentials" - id: detect-private-key - id: end-of-file-fixer - id: mixed-line-ending - id: trailing-whitespace - repo: https://github.com/stackrox/kube-linter rev: 0.5.1 hooks: - id: kube-linter args: [lint, --config, .kube-linter.yaml] - repo: https://github.com/adrienverge/yamllint.git rev: v1.28.0 hooks: - id: yamllint args: [-c=.yamllint] - repo: https://github.com/Yelp/detect-secrets rev: v1.4.0 hooks: - id: detect-secrets args: [ "--disable-plugin", "KeywordDetector", "--baseline", ".secrets.baseline", ] exclude: package.lock.json ``` ### ~/.cache/pre-commit/pre-commit.log (if present) ### version information ``` pre-commit version: 3.0.0 git --version: git version 2.39.1 sys.version: 3.11.1 (main, Dec 23 2022, 09:28:24) [Clang 14.0.0 (clang-1400.0.29.202)] sys.executable: /opt/homebrew/Cellar/pre-commit/3.0.0/libexec/bin/python3 os.name: posix sys.platform: darwin ``` ### error information ``` An unexpected error has occurred: CalledProcessError: command: ('/opt/homebrew/bin/go', 'install', './...') return code: 1 stdout: (none) stderr: go: downloading github.com/fatih/color v1.13.0 go: downloading github.com/Masterminds/sprig/v3 v3.2.3 go: downloading github.com/pkg/errors v0.9.1 go: downloading github.com/ghodss/yaml v1.0.0 go: downloading github.com/spf13/cobra v1.6.1 go: downloading github.com/spf13/pflag v1.0.5 go: downloading github.com/owenrumney/go-sarif/v2 v2.1.2 go: downloading github.com/spf13/viper v1.14.0 go: downloading github.com/openshift/api v3.9.0+incompatible go: downloading k8s.io/apimachinery v0.25.4 go: downloading k8s.io/api v0.25.4 go: downloading github.com/stretchr/testify v1.8.1 go: downloading helm.sh/helm/v3 v3.10.2 go: downloading k8s.io/gengo v0.0.0-20211129171323-c02415ce4185 go: downloading k8s.io/client-go v0.25.4 go: downloading github.com/mitchellh/mapstructure v1.5.0 go: downloading gopkg.in/yaml.v2 v2.4.0 go: downloading github.com/mattn/go-colorable v0.1.13 go: downloading github.com/mattn/go-isatty v0.0.16 go: downloading github.com/Masterminds/goutils v1.1.1 go: downloading github.com/Masterminds/semver/v3 v3.2.0 go: downloading github.com/google/uuid v1.3.0 go: downloading github.com/huandu/xstrings v1.3.3 go: downloading github.com/imdario/mergo v0.3.12 go: downloading github.com/mitchellh/copystructure v1.2.0 go: downloading github.com/shopspring/decimal v1.2.0 go: downloading github.com/spf13/cast v1.5.0 go: downloading golang.org/x/crypto v0.3.0 go: downloading github.com/Masterminds/semver v1.5.0 go: downloading github.com/fsnotify/fsnotify v1.6.0 go: downloading github.com/spf13/afero v1.9.2 go: downloading github.com/spf13/jwalterweatherman v1.1.0 go: downloading github.com/gogo/protobuf v1.3.2 go: downloading github.com/google/gofuzz v1.2.0 go: downloading k8s.io/klog/v2 v2.80.1 go: downloading sigs.k8s.io/structured-merge-diff/v4 v4.2.3 go: downloading k8s.io/utils v0.0.0-20220922133306-665eaaec4324 go: downloading sigs.k8s.io/yaml v1.3.0 go: downloading gopkg.in/inf.v0 v0.9.1 go: downloading github.com/BurntSushi/toml v1.2.1 go: downloading github.com/gobwas/glob v0.2.3 go: downloading github.com/cyphar/filepath-securejoin v0.2.3 go: downloading github.com/xeipuuv/gojsonschema v1.2.0 go: downloading k8s.io/apiextensions-apiserver v0.25.2 go: downloading golang.org/x/sys v0.2.0 go: downloading github.com/mitchellh/reflectwalk v1.0.2 go: downloading github.com/subosito/gotenv v1.4.1 go: downloading github.com/hashicorp/hcl v1.0.0 go: downloading gopkg.in/ini.v1 v1.67.0 go: downloading github.com/magiconair/properties v1.8.6 go: downloading github.com/pelletier/go-toml/v2 v2.0.5 go: downloading gopkg.in/yaml.v3 v3.0.1 go: downloading sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 go: downloading golang.org/x/text v0.4.0 go: downloading github.com/davecgh/go-spew v1.1.1 go: downloading github.com/pmezard/go-difflib v1.0.0 go: downloading github.com/go-logr/logr v1.2.3 go: downloading github.com/golang/protobuf v1.5.2 go: downloading github.com/pelletier/go-toml v1.9.5 go: downloading github.com/google/gnostic v0.6.9 go: downloading golang.org/x/net v0.2.0 go: downloading github.com/json-iterator/go v1.1.12 go: downloading github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 go: downloading k8s.io/cli-runtime v0.25.4 go: downloading github.com/containerd/containerd v1.6.6 go: downloading github.com/opencontainers/image-spec v1.0.3-0.20211202183452-c5a74bcca799 go: downloading github.com/sirupsen/logrus v1.9.0 go: downloading oras.land/oras-go v1.2.0 go: downloading google.golang.org/protobuf v1.28.1 go: downloading k8s.io/kube-openapi v0.0.0-20220803164354-a70c9af30aea go: downloading golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783 go: downloading golang.org/x/term v0.2.0 go: downloading golang.org/x/time v0.0.0-20220609170525-579cf78fd858 go: downloading github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd go: downloading github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f go: downloading github.com/modern-go/reflect2 v1.0.2 go: downloading github.com/evanphx/json-patch v5.6.0+incompatible go: downloading github.com/opencontainers/go-digest v1.0.0 go: downloading github.com/docker/cli v20.10.17+incompatible go: downloading github.com/docker/distribution v2.8.1+incompatible go: downloading golang.org/x/sync v0.1.0 go: downloading github.com/docker/docker v20.10.17+incompatible go: downloading github.com/docker/go-connections v0.4.0 go: downloading github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 go: downloading github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de go: downloading sigs.k8s.io/kustomize/api v0.12.1 go: downloading sigs.k8s.io/kustomize/kyaml v0.13.9 go: downloading github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 go: downloading github.com/peterbourgon/diskv v2.0.1+incompatible go: downloading github.com/moby/locker v1.0.1 go: downloading google.golang.org/grpc v1.50.1 go: downloading github.com/emicklei/go-restful/v3 v3.8.0 go: downloading github.com/docker/docker-credential-helpers v0.6.4 go: downloading github.com/go-openapi/swag v0.19.14 go: downloading github.com/go-openapi/jsonreference v0.19.5 go: downloading github.com/google/btree v1.0.1 go: downloading github.com/klauspost/compress v1.14.1 go: downloading github.com/mailru/easyjson v0.7.6 go: downloading github.com/PuerkitoBio/purell v1.1.1 go: downloading github.com/go-openapi/jsonpointer v0.19.5 go: downloading github.com/gorilla/mux v1.8.0 go: downloading github.com/go-errors/errors v1.0.1 go: downloading github.com/josharian/intern v1.0.0 go: downloading google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e go: downloading github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 go: downloading github.com/docker/go-metrics v0.0.1 go: downloading github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 go: downloading github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 go: downloading github.com/xlab/treeprint v1.1.0 go: downloading github.com/docker/go-units v0.4.0 go: downloading github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 go: downloading github.com/morikuni/aec v1.0.0 go: downloading go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 go: downloading github.com/prometheus/client_golang v1.13.0 go: downloading github.com/beorn7/perks v1.0.1 go: downloading github.com/prometheus/common v0.37.0 go: downloading github.com/cespare/xxhash/v2 v2.1.2 go: downloading github.com/prometheus/client_model v0.2.0 go: downloading github.com/prometheus/procfs v0.8.0 go: downloading github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. ``` ``` Traceback (most recent call last): File "/opt/homebrew/Cellar/pre-commit/3.0.0/libexec/lib/python3.11/site-packages/pre_commit/error_handler.py", line 73, in error_handler yield File "/opt/homebrew/Cellar/pre-commit/3.0.0/libexec/lib/python3.11/site-packages/pre_commit/main.py", line 366, in main return hook_impl( ^^^^^^^^^^ File "/opt/homebrew/Cellar/pre-commit/3.0.0/libexec/lib/python3.11/site-packages/pre_commit/commands/hook_impl.py", line 254, in hook_impl return retv | run(config, store, ns) ^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/Cellar/pre-commit/3.0.0/libexec/lib/python3.11/site-packages/pre_commit/commands/run.py", line 436, in run install_hook_envs(to_install, store) File "/opt/homebrew/Cellar/pre-commit/3.0.0/libexec/lib/python3.11/site-packages/pre_commit/repository.py", line 239, in install_hook_envs _hook_install(hook) File "/opt/homebrew/Cellar/pre-commit/3.0.0/libexec/lib/python3.11/site-packages/pre_commit/repository.py", line 86, in _hook_install lang.install_environment( File "/opt/homebrew/Cellar/pre-commit/3.0.0/libexec/lib/python3.11/site-packages/pre_commit/languages/golang.py", line 152, in install_environment helpers.run_setup_cmd(prefix, ('go', 'install', './...'), env=env) File "/opt/homebrew/Cellar/pre-commit/3.0.0/libexec/lib/python3.11/site-packages/pre_commit/languages/helpers.py", line 49, in run_setup_cmd cmd_output_b(*cmd, cwd=prefix.prefix_dir, **kwargs) File "/opt/homebrew/Cellar/pre-commit/3.0.0/libexec/lib/python3.11/site-packages/pre_commit/util.py", line 115, in cmd_output_b raise CalledProcessError(returncode, cmd, stdout_b, stderr_b) pre_commit.util.CalledProcessError: command: ('/opt/homebrew/bin/go', 'install', './...') return code: 1 stdout: (none) stderr: go: downloading github.com/fatih/color v1.13.0 go: downloading github.com/Masterminds/sprig/v3 v3.2.3 go: downloading github.com/pkg/errors v0.9.1 go: downloading github.com/ghodss/yaml v1.0.0 go: downloading github.com/spf13/cobra v1.6.1 go: downloading github.com/spf13/pflag v1.0.5 go: downloading github.com/owenrumney/go-sarif/v2 v2.1.2 go: downloading github.com/spf13/viper v1.14.0 go: downloading github.com/openshift/api v3.9.0+incompatible go: downloading k8s.io/apimachinery v0.25.4 go: downloading k8s.io/api v0.25.4 go: downloading github.com/stretchr/testify v1.8.1 go: downloading helm.sh/helm/v3 v3.10.2 go: downloading k8s.io/gengo v0.0.0-20211129171323-c02415ce4185 go: downloading k8s.io/client-go v0.25.4 go: downloading github.com/mitchellh/mapstructure v1.5.0 go: downloading gopkg.in/yaml.v2 v2.4.0 go: downloading github.com/mattn/go-colorable v0.1.13 go: downloading github.com/mattn/go-isatty v0.0.16 go: downloading github.com/Masterminds/goutils v1.1.1 go: downloading github.com/Masterminds/semver/v3 v3.2.0 go: downloading github.com/google/uuid v1.3.0 go: downloading github.com/huandu/xstrings v1.3.3 go: downloading github.com/imdario/mergo v0.3.12 go: downloading github.com/mitchellh/copystructure v1.2.0 go: downloading github.com/shopspring/decimal v1.2.0 go: downloading github.com/spf13/cast v1.5.0 go: downloading golang.org/x/crypto v0.3.0 go: downloading github.com/Masterminds/semver v1.5.0 go: downloading github.com/fsnotify/fsnotify v1.6.0 go: downloading github.com/spf13/afero v1.9.2 go: downloading github.com/spf13/jwalterweatherman v1.1.0 go: downloading github.com/gogo/protobuf v1.3.2 go: downloading github.com/google/gofuzz v1.2.0 go: downloading k8s.io/klog/v2 v2.80.1 go: downloading sigs.k8s.io/structured-merge-diff/v4 v4.2.3 go: downloading k8s.io/utils v0.0.0-20220922133306-665eaaec4324 go: downloading sigs.k8s.io/yaml v1.3.0 go: downloading gopkg.in/inf.v0 v0.9.1 go: downloading github.com/BurntSushi/toml v1.2.1 go: downloading github.com/gobwas/glob v0.2.3 go: downloading github.com/cyphar/filepath-securejoin v0.2.3 go: downloading github.com/xeipuuv/gojsonschema v1.2.0 go: downloading k8s.io/apiextensions-apiserver v0.25.2 go: downloading golang.org/x/sys v0.2.0 go: downloading github.com/mitchellh/reflectwalk v1.0.2 go: downloading github.com/subosito/gotenv v1.4.1 go: downloading github.com/hashicorp/hcl v1.0.0 go: downloading gopkg.in/ini.v1 v1.67.0 go: downloading github.com/magiconair/properties v1.8.6 go: downloading github.com/pelletier/go-toml/v2 v2.0.5 go: downloading gopkg.in/yaml.v3 v3.0.1 go: downloading sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 go: downloading golang.org/x/text v0.4.0 go: downloading github.com/davecgh/go-spew v1.1.1 go: downloading github.com/pmezard/go-difflib v1.0.0 go: downloading github.com/go-logr/logr v1.2.3 go: downloading github.com/golang/protobuf v1.5.2 go: downloading github.com/pelletier/go-toml v1.9.5 go: downloading github.com/google/gnostic v0.6.9 go: downloading golang.org/x/net v0.2.0 go: downloading github.com/json-iterator/go v1.1.12 go: downloading github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 go: downloading k8s.io/cli-runtime v0.25.4 go: downloading github.com/containerd/containerd v1.6.6 go: downloading github.com/opencontainers/image-spec v1.0.3-0.20211202183452-c5a74bcca799 go: downloading github.com/sirupsen/logrus v1.9.0 go: downloading oras.land/oras-go v1.2.0 go: downloading google.golang.org/protobuf v1.28.1 go: downloading k8s.io/kube-openapi v0.0.0-20220803164354-a70c9af30aea go: downloading golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783 go: downloading golang.org/x/term v0.2.0 go: downloading golang.org/x/time v0.0.0-20220609170525-579cf78fd858 go: downloading github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd go: downloading github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f go: downloading github.com/modern-go/reflect2 v1.0.2 go: downloading github.com/evanphx/json-patch v5.6.0+incompatible go: downloading github.com/opencontainers/go-digest v1.0.0 go: downloading github.com/docker/cli v20.10.17+incompatible go: downloading github.com/docker/distribution v2.8.1+incompatible go: downloading golang.org/x/sync v0.1.0 go: downloading github.com/docker/docker v20.10.17+incompatible go: downloading github.com/docker/go-connections v0.4.0 go: downloading github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 go: downloading github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de go: downloading sigs.k8s.io/kustomize/api v0.12.1 go: downloading sigs.k8s.io/kustomize/kyaml v0.13.9 go: downloading github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 go: downloading github.com/peterbourgon/diskv v2.0.1+incompatible go: downloading github.com/moby/locker v1.0.1 go: downloading google.golang.org/grpc v1.50.1 go: downloading github.com/emicklei/go-restful/v3 v3.8.0 go: downloading github.com/docker/docker-credential-helpers v0.6.4 go: downloading github.com/go-openapi/swag v0.19.14 go: downloading github.com/go-openapi/jsonreference v0.19.5 go: downloading github.com/google/btree v1.0.1 go: downloading github.com/klauspost/compress v1.14.1 go: downloading github.com/mailru/easyjson v0.7.6 go: downloading github.com/PuerkitoBio/purell v1.1.1 go: downloading github.com/go-openapi/jsonpointer v0.19.5 go: downloading github.com/gorilla/mux v1.8.0 go: downloading github.com/go-errors/errors v1.0.1 go: downloading github.com/josharian/intern v1.0.0 go: downloading google.golang.org/genproto v0.0.0-20221024183307-1bc688fe9f3e go: downloading github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 go: downloading github.com/docker/go-metrics v0.0.1 go: downloading github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 go: downloading github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 go: downloading github.com/xlab/treeprint v1.1.0 go: downloading github.com/docker/go-units v0.4.0 go: downloading github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 go: downloading github.com/morikuni/aec v1.0.0 go: downloading go.starlark.net v0.0.0-20200306205701-8dd3e2ee1dd5 go: downloading github.com/prometheus/client_golang v1.13.0 go: downloading github.com/beorn7/perks v1.0.1 go: downloading github.com/prometheus/common v0.37.0 go: downloading github.com/cespare/xxhash/v2 v2.1.2 go: downloading github.com/prometheus/client_model v0.2.0 go: downloading github.com/prometheus/procfs v0.8.0 go: downloading github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. ```
it works fine for me in both 2.21 and 3.0 -- do you have any other `GO` environment variables or other things interfering? I am not sure what the cause might be. One thing I have noticed is when I was doing interactive rebase with renaming commit, the pre-commit check installation/initialization succeeded - what comes to my mind - maybe some timeouts? ``` ❯ git rebase -i origin/master [INFO] Installing environment for https://github.com/stackrox/kube-linter. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/adrienverge/yamllint.git. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... [INFO] Installing environment for https://github.com/Yelp/detect-secrets. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... check for added large files..........................(no files to check)Skipped check for merge conflicts............................(no files to check)Skipped detect aws credentials...............................(no files to check)Skipped detect private key...................................(no files to check)Skipped fix end of files.....................................(no files to check)Skipped mixed line ending....................................(no files to check)Skipped trim trailing whitespace.............................(no files to check)Skipped KubeLinter...........................................(no files to check)Skipped yamllint.............................................(no files to check)Skipped Detect secrets.......................................(no files to check)Skipped [detached HEAD 57ca14ed] stuff Date: Thu Jan 26 09:48:21 2023 +0100 5 files changed, 67 insertions(+), 12 deletions(-) Successfully rebased and updated refs/heads/feat/stuff. ``` ## Additional information: Git version: `2.39.1` This is my `go env` ```shell $ go env GO111MODULE="" GOARCH="arm64" GOBIN="" GOCACHE="/Users/.../Library/Caches/go-build" GOENV="/Users/.../Library/Application Support/go/env" GOEXE="" GOEXPERIMENT="" GOFLAGS="" GOHOSTARCH="arm64" GOHOSTOS="darwin" GOINSECURE="" GOMODCACHE="/Users/.../go/pkg/mod" GONOPROXY="" GONOSUMDB="" GOOS="darwin" GOPATH="/Users/.../go" GOPRIVATE="" GOPROXY="https://proxy.golang.org,direct" GOROOT="/opt/homebrew/Cellar/go/1.19.5/libexec" GOSUMDB="sum.golang.org" GOTMPDIR="" GOTOOLDIR="/opt/homebrew/Cellar/go/1.19.5/libexec/pkg/tool/darwin_arm64" GOVCS="" GOVERSION="go1.19.5" GCCGO="gccgo" AR="ar" CC="clang" CXX="clang++" CGO_ENABLED="1" GOMOD="/dev/null" GOWORK="" CGO_CFLAGS="-g -O2" CGO_CPPFLAGS="" CGO_CXXFLAGS="-g -O2" CGO_FFLAGS="-g -O2" CGO_LDFLAGS="-g -O2" PKG_CONFIG="pkg-config" GOGCCFLAGS="-fPIC -arch arm64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/jh/6dnhwcxn5m592yf4_l1nkr_r0000gn/T/go-build2822682343=/tmp/go-build -gno-record-gcc-switches -fno-common" ``` my guess is the error was needing to upgrade macos CLT or whatever. either way it's working now I'm facing this error right now on my Linux box while it works perfectly on my macOS box. ``` Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/pre_commit/error_handler.py", line 73, in error_handler yield File "/usr/local/lib/python3.8/dist-packages/pre_commit/main.py", line 366, in main return hook_impl( File "/usr/local/lib/python3.8/dist-packages/pre_commit/commands/hook_impl.py", line 254, in hook_impl return retv | run(config, store, ns) File "/usr/local/lib/python3.8/dist-packages/pre_commit/commands/run.py", line 437, in run install_hook_envs(to_install, store) File "/usr/local/lib/python3.8/dist-packages/pre_commit/repository.py", line 239, in install_hook_envs _hook_install(hook) File "/usr/local/lib/python3.8/dist-packages/pre_commit/repository.py", line 86, in _hook_install lang.install_environment( File "/usr/local/lib/python3.8/dist-packages/pre_commit/languages/golang.py", line 152, in install_environment helpers.run_setup_cmd(prefix, ('go', 'install', './...'), env=env) File "/usr/local/lib/python3.8/dist-packages/pre_commit/languages/helpers.py", line 49, in run_setup_cmd cmd_output_b(*cmd, cwd=prefix.prefix_dir, **kwargs) File "/usr/local/lib/python3.8/dist-packages/pre_commit/util.py", line 115, in cmd_output_b raise CalledProcessError(returncode, cmd, stdout_b, stderr_b) pre_commit.util.CalledProcessError: command: ('/home/zedtux/.cache/pre-commit/repo56ywbt73/golangenv-default/.go/bin/go', 'install', './...') return code: 1 stdout: (none) stderr: go: downloading github.com/rs/zerolog v1.26.1 ... go: downloading golang.org/x/text v0.3.6 go: downloading github.com/mattn/go-isatty v0.0.14 error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. ``` I'm running Elementary OS 6 (Ubuntu Focal like) and I did install it using `pip`. can you share the same information as above? -- generally this failure isn't a pre-commit problem and is instead a misconfiguration of `go` Sure, here it is : ## Additional information: Git version: `2.25.1` `go env` fails for me as it is not installed! yeah I need your config and everything else too Oops, sorry : ## pre-commit --version `pre-commit 3.0.4` ## .pre-commit-config.yaml ```yaml repos: - repo: https://github.com/antonbabenko/pre-commit-terraform rev: v1.77.1 # Get the latest from: https://github.com/antonbabenko/pre-commit-terraform/releases hooks: - id: terraform_fmt - id: terraform_docs - id: terraform_tfsec - id: terraform_validate - repo: https://github.com/zricethezav/gitleaks rev: v8.15.3 hooks: - id: gitleaks ``` ## ~/.cache/pre-commit/pre-commit.log if present ### version information ``` pre-commit version: 3.0.4 git --version: git version 2.25.1 sys.version: 3.8.10 (default, Nov 14 2022, 12:59:47) [GCC 9.4.0] sys.executable: /usr/bin/python3 os.name: posix sys.platform: linux ``` ### error information ``` An unexpected error has occurred: CalledProcessError: command: ('/home/zedtux/.cache/pre-commit/repo56ywbt73/golangenv-default/.go/bin/go', 'install', './...') return code: 1 stdout: (none) stderr: go: downloading github.com/rs/zerolog v1.26.1 go: downloading github.com/lucasjones/reggen v0.0.0-20200904144131-37ba4fa293bb go: downloading github.com/gitleaks/go-gitdiff v0.8.0 go: downloading github.com/spf13/viper v1.8.1 go: downloading github.com/spf13/cobra v1.2.1 go: downloading github.com/charmbracelet/lipgloss v0.5.0 go: downloading github.com/petar-dambovaliev/aho-corasick v0.0.0-20211021192214-5ab2d9280aa9 go: downloading github.com/fatih/semgroup v1.2.0 go: downloading github.com/h2non/filetype v1.1.3 go: downloading github.com/spf13/pflag v1.0.5 go: downloading golang.org/x/sync v0.0.0-20210220032951-036812b2e83c go: downloading github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68 go: downloading github.com/lucasb-eyer/go-colorful v1.2.0 go: downloading github.com/mattn/go-runewidth v0.0.13 go: downloading github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0 go: downloading github.com/fsnotify/fsnotify v1.4.9 go: downloading github.com/hashicorp/hcl v1.0.0 go: downloading github.com/magiconair/properties v1.8.5 go: downloading github.com/mitchellh/mapstructure v1.4.1 go: downloading github.com/pelletier/go-toml v1.9.3 go: downloading github.com/spf13/afero v1.6.0 go: downloading github.com/spf13/cast v1.3.1 go: downloading github.com/spf13/jwalterweatherman v1.1.0 go: downloading github.com/subosito/gotenv v1.2.0 go: downloading gopkg.in/ini.v1 v1.62.0 go: downloading gopkg.in/yaml.v2 v2.4.0 go: downloading github.com/rivo/uniseg v0.2.0 go: downloading golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 go: downloading golang.org/x/text v0.3.6 go: downloading github.com/mattn/go-isatty v0.0.14 error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. ``` ``` Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/pre_commit/error_handler.py", line 73, in error_handler yield File "/usr/local/lib/python3.8/dist-packages/pre_commit/main.py", line 366, in main return hook_impl( File "/usr/local/lib/python3.8/dist-packages/pre_commit/commands/hook_impl.py", line 254, in hook_impl return retv | run(config, store, ns) File "/usr/local/lib/python3.8/dist-packages/pre_commit/commands/run.py", line 437, in run install_hook_envs(to_install, store) File "/usr/local/lib/python3.8/dist-packages/pre_commit/repository.py", line 239, in install_hook_envs _hook_install(hook) File "/usr/local/lib/python3.8/dist-packages/pre_commit/repository.py", line 86, in _hook_install lang.install_environment( File "/usr/local/lib/python3.8/dist-packages/pre_commit/languages/golang.py", line 152, in install_environment helpers.run_setup_cmd(prefix, ('go', 'install', './...'), env=env) File "/usr/local/lib/python3.8/dist-packages/pre_commit/languages/helpers.py", line 49, in run_setup_cmd cmd_output_b(*cmd, cwd=prefix.prefix_dir, **kwargs) File "/usr/local/lib/python3.8/dist-packages/pre_commit/util.py", line 115, in cmd_output_b raise CalledProcessError(returncode, cmd, stdout_b, stderr_b) pre_commit.util.CalledProcessError: command: ('/home/zedtux/.cache/pre-commit/repo56ywbt73/golangenv-default/.go/bin/go', 'install', './...') return code: 1 stdout: (none) stderr: go: downloading github.com/rs/zerolog v1.26.1 go: downloading github.com/lucasjones/reggen v0.0.0-20200904144131-37ba4fa293bb go: downloading github.com/gitleaks/go-gitdiff v0.8.0 go: downloading github.com/spf13/viper v1.8.1 go: downloading github.com/spf13/cobra v1.2.1 go: downloading github.com/charmbracelet/lipgloss v0.5.0 go: downloading github.com/petar-dambovaliev/aho-corasick v0.0.0-20211021192214-5ab2d9280aa9 go: downloading github.com/fatih/semgroup v1.2.0 go: downloading github.com/h2non/filetype v1.1.3 go: downloading github.com/spf13/pflag v1.0.5 go: downloading golang.org/x/sync v0.0.0-20210220032951-036812b2e83c go: downloading github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68 go: downloading github.com/lucasb-eyer/go-colorful v1.2.0 go: downloading github.com/mattn/go-runewidth v0.0.13 go: downloading github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0 go: downloading github.com/fsnotify/fsnotify v1.4.9 go: downloading github.com/hashicorp/hcl v1.0.0 go: downloading github.com/magiconair/properties v1.8.5 go: downloading github.com/mitchellh/mapstructure v1.4.1 go: downloading github.com/pelletier/go-toml v1.9.3 go: downloading github.com/spf13/afero v1.6.0 go: downloading github.com/spf13/cast v1.3.1 go: downloading github.com/spf13/jwalterweatherman v1.1.0 go: downloading github.com/subosito/gotenv v1.2.0 go: downloading gopkg.in/ini.v1 v1.62.0 go: downloading gopkg.in/yaml.v2 v2.4.0 go: downloading github.com/rivo/uniseg v0.2.0 go: downloading golang.org/x/sys v0.0.0-20211110154304-99a53858aa08 go: downloading golang.org/x/text v0.3.6 go: downloading github.com/mattn/go-isatty v0.0.14 error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. ``` can you share `env | grep -Ei '(GIT|PRE_COMMIT|GO)' | sort`, your `~/.gitconfig` and `ls -al ~/.cache/pre-commit` ? ## env | grep -Ei '(GIT|PRE_COMMIT|GO)' | sort ``` $ env | grep -Ei '(GIT|PRE_COMMIT|GO)' | sort TF_VAR_OAUTH2_PASS=[redacted] ``` ## ~/.gitconfig ``` [user] name = Guillaume Hain email = [email protected] signingkey = BC63F4AEB4B5092E3104C289D2B2A8B99474CF36 [color] branch = auto status = auto diff = auto ui = always [alias] st = "!git_stash_check; rails_project_cleaner.sh; git status -sb" ci = commit co = checkout restore = checkout HEAD -- uncommit = reset --soft HEAD^ l = log --decorate --show-signature lg = log --decorate --graph --show-signature master = checkout master develop = checkout develop staging = checkout staging cir = "!git_make_a_new_release" branches = branch -a spull = submodule foreach git pull changedfiles = "!git diff --name-only $GIT_DEFAULT_BRANCH `git rev-parse --abbrev-ref HEAD`" rmbranches = "!git branch --merged ${GIT_DEFAULT_BRANCH:-master} | grep -v ${GIT_DEFAULT_BRANCH:-master} | xargs git branch -D" refreshbranches = remote update origin --prune [push] default = tracking followTags = true [status] showUntrackedFiles = all [pack] threads = 2 [core] editor = nano quotepath = false [mergetool] keepBackup = false prompt = false [branch] autosetupmerge = true [filter "media"] clean = git-media-clean %f smudge = git-media-smudge %f [difftool] prompt = false [commit] gpgsign = true [filter "lfs"] clean = git-lfs clean %f smudge = git-lfs smudge %f required = true [merge] tool = meld [gpg] program = gpg [merge "ours"] driver = true ``` ## ls -al ~/.cache/pre-commit ``` ls -al ~/.cache/pre-commit total 48 drwxrwxr-x 4 zedtux zedtux 4096 Feb 15 21:11 . drwxr-xr-x 26 zedtux zedtux 4096 Feb 15 21:28 .. drwx------ 10 zedtux zedtux 4096 Feb 15 21:18 repo56ywbt73 drwx------ 8 zedtux zedtux 4096 Feb 15 21:10 repovpqakma5 -rw------- 1 zedtux zedtux 20480 Feb 15 21:10 db.db -rw-rw-r-- 1 zedtux zedtux 0 Feb 15 21:10 .lock -rw-rw-r-- 1 zedtux zedtux 5917 Feb 15 21:18 pre-commit.log -rw-rw-r-- 1 zedtux zedtux 109 Feb 15 21:10 README ``` tried reproducing in docker and didn't really get anywhere -- any chance you could strace and see what `git` command go is running and why it fails? I'm getting this on MacOS so I can't use strace for me is failing on the same package just a slightly different version. ``` go: downloading github.com/matttproud/golang_protobuf_extensions v1.0.1 error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. ``` I'm encountering this now. ## Workaround I'm able to circumvent this problem by committing once like so: GOFLAGS=-buildvcs=false git commit -av After this succeeded, if I run `pre-commit clean && pre-commit install-hooks`, I don't see the error again. I'd expect to see it, so I might be doing something odd here. I expected to have to do GOFLAGS=-buildvcs=false pre-commit install-hooks after `pre-commit clean`. ## Research and observations Some research indicates that it's related to one or more of the following: * go 1.18 embeds git information at build time * The build directory needing to be in git's `safe.directory` ## Possible remedies 1. Do what it says on the tin: add `-buildvcs=false` [here](https://github.com/pre-commit/pre-commit/blob/bb49560dc99a65608c8f9161dd71467af163c0d1/pre_commit/languages/golang.py#L152), perhaps with end-user control of it 2. Maybe the there needs to be a `go get && git config --global --add safe.directory ${where_go_get_put_it} && go install ${where_go_get_put_it}`; I'm not a Go dev so 🤷 ## See also: * https://github.com/golang/go/issues/49004 * https://github.com/microsoft/CBL-Mariner/issues/3273 * https://www.reddit.com/r/golang/comments/x5e3ld/how_to_set_buildvcsfalse_as_default/ ## Requested troubleshooting information ### version information ``` pre-commit version: 3.2.1 git --version: git version 2.40.0 sys.version: 3.11.2 (main, Feb 16 2023, 02:55:59) [Clang 14.0.0 (clang-1400.0.29.202)] sys.executable: /opt/homebrew/Cellar/pre-commit/3.2.1/libexec/bin/python3 os.name: posix sys.platform: darwin ``` ### error information ``` An unexpected error has occurred: CalledProcessError: command: ('/opt/homebrew/bin/go', 'install', './...') return code: 1 stdout: (none) stderr: error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. ``` ``` Traceback (most recent call last): File "/opt/homebrew/Cellar/pre-commit/3.2.1/libexec/lib/python3.11/site-packages/pre_commit/error_handler.py", line 73, in error_handler yield File "/opt/homebrew/Cellar/pre-commit/3.2.1/libexec/lib/python3.11/site-packages/pre_commit/main.py", line 381, in main return hook_impl( ^^^^^^^^^^ File "/opt/homebrew/Cellar/pre-commit/3.2.1/libexec/lib/python3.11/site-packages/pre_commit/commands/hook_impl.py", line 271, in hook_impl return retv | run(config, store, ns) ^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/Cellar/pre-commit/3.2.1/libexec/lib/python3.11/site-packages/pre_commit/commands/run.py", line 442, in run install_hook_envs(to_install, store) File "/opt/homebrew/Cellar/pre-commit/3.2.1/libexec/lib/python3.11/site-packages/pre_commit/repository.py", line 248, in install_hook_envs _hook_install(hook) File "/opt/homebrew/Cellar/pre-commit/3.2.1/libexec/lib/python3.11/site-packages/pre_commit/repository.py", line 95, in _hook_install lang.install_environment( File "/opt/homebrew/Cellar/pre-commit/3.2.1/libexec/lib/python3.11/site-packages/pre_commit/languages/golang.py", line 152, in install_environment lang_base.setup_cmd(prefix, ('go', 'install', './...'), env=env) File "/opt/homebrew/Cellar/pre-commit/3.2.1/libexec/lib/python3.11/site-packages/pre_commit/lang_base.py", line 87, in setup_cmd cmd_output_b(*cmd, cwd=prefix.prefix_dir, **kwargs) File "/opt/homebrew/Cellar/pre-commit/3.2.1/libexec/lib/python3.11/site-packages/pre_commit/util.py", line 110, in cmd_output_b raise CalledProcessError(returncode, cmd, stdout_b, stderr_b) pre_commit.util.CalledProcessError: command: ('/opt/homebrew/bin/go', 'install', './...') return code: 1 stdout: (none) stderr: error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. ``` ### `env | grep -Ei '(GIT|PRE_COMMIT|GO)' | sort` ``` FZF_CTRL_T_COMMAND=rg --files --no-ignore --hidden --follow -g "!{.git,node_modules,build}/*" 2> /dev/null FZF_DEFAULT_COMMAND=rg --files --no-ignore --hidden --follow -g "!{.git,node_modules,build}/*" 2> /dev/null GIT_PS1_SHOWDIRTYSTATE=true GIT_PS1_SHOWUNTRACKEDFILES=true GOPATH=/Users/colin/.go PATH=/Users/colin/.conscript/bin:/Users/colin/.cache/micromamba/condabin:/Users/colin/.pyenv/shims:/Users/colin/.local/bin:/Users/colin/.bin:/opt/homebrew/opt/curl/bin:/opt/homebrew/opt/llvm/bin:/Library/Java/Home/bin:/Users/colin/.cargo/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/sbin:/Library/TeX/texbin:/Library/Application Support/CDM/bin:/usr/local/munki:/Applications/kitty.app/Contents/MacOS:/usr/local/opt/rust/bin:/Users/colin/.cabal/bin:/usr/local/heroku/bin:/usr/local/opt/go/libexec/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/System/Cryptexes/App/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/sbin:/Library/TeX/texbin:/Library/Application Support/CDM/bin:/usr/local/munki:/Applications/kitty.app/Contents/MacOS PS1=\[\e]133;k;start_kitty\a\]\[\e]133;A\a\]\[\e]133;k;end_kitty\a\]\[\033[1;37m\][\[\033[1;33m\]\t \[\033[0;32m\]\u@\H \[\033[0;36m\]\w \[\033[1;37m\]]\n\[\e]133;k;start_secondary_kitty\a\]\[\e]133;A;k=s\a\]\[\e]133;k;end_secondary_kitty\a\]\[\033[1;31m\]$(if [ ! -z "`command -v __git_ps1`" ]; then _GITPS1="`__git_ps1`"; if [ ! -z "${_GITPS1}" ]; then echo -n "±${_GITPS1}"; echo -n ' '; fi; fi)\[\033[0;37m\]$(if [ $SHLVL -gt 1 ]; then echo "⇟$SHLVL"; fi)$ \[\e]133;k;start_suffix_kitty\a\]\[\e[5 q\]\[\e]2;\w\a\]\[\e]133;k;end_suffix_kitty\a\] __CFBundleIdentifier=net.kovidgoyal.kitty ``` ### `ls -al ~/.cache/pre-commit` ``` $ ls -al ~/.cache/pre-commit total 56 drwxr-xr-x@ 9 colin staff 288 Apr 3 14:46 . drwxr-xr-x 9 colin staff 288 Apr 3 14:46 .. -rw-r--r--@ 1 colin staff 0 Apr 3 14:46 .lock -rw-r--r--@ 1 colin staff 109 Apr 3 14:46 README -rw-------@ 1 colin staff 20480 Apr 3 14:46 db.db -rw-r--r--@ 1 colin staff 2676 Apr 3 14:46 pre-commit.log drwx------@ 30 colin staff 960 Apr 3 14:46 repofs85lks_ drwx------@ 9 colin staff 288 Apr 3 14:46 repogmqgmb7n drwx------@ 20 colin staff 640 Apr 3 14:46 reporuqzcd7b ``` ### .pre-commit-config.yaml ``` $ cat .pre-commit-config.yaml # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.2.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - id: check-json - id: check-added-large-files - id: check-case-conflict - id: check-executables-have-shebangs - id: check-shebang-scripts-are-executable - id: check-symlinks - id: check-merge-conflict - id: destroyed-symlinks - id: check-toml - repo: https://github.com/comkieffer/pre-commit-xmllint.git rev: 1.0.0 hooks: - id: xmllint # keep Makefile tidy and neat - repo: https://github.com/mrtazz/checkmake.git # check this for updates once in a while, look for tags rev: 4e37f3a6ea00208b3f5bd04eaa0f075068237f18 hooks: - id: checkmake ``` I'm encountering this on Linux, too. ``` $ git commit -av [INFO] Initializing environment for https://github.com/mrtazz/checkmake.git. [INFO] Initializing environment for https://github.com/executablebooks/mdformat. [INFO] Initializing environment for https://github.com/executablebooks/mdformat:mdformat-gfm. [INFO] Initializing environment for https://github.com/pre-commit/pre-commit-hooks. [INFO] Installing environment for https://github.com/mrtazz/checkmake.git. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexpected error has occurred: CalledProcessError: command: ('/home/colin/.cache/pre-commit/repoy46vmwin/golangenv-default/.go/bin/go', 'install', './...') return code: 1 stdout: (none) stderr: error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. Check the log at /home/colin/.cache/pre-commit/pre-commit.log ``` ``` $ pre-commit --version pre-commit 3.2.2 $ git --version git version 2.34.1 $ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 22.04.1 LTS Release: 22.04 Codename: jammy ``` can you strace and figure out why git is mad? I can try. I've not used strace before, though. One thing I've noticed on this Linux system is that if I run `pre-commit install-hooks`, the checkmake hook will install correctly and run fine next time I run `git commit`. If I run `pre-commit clean` and then `git commit`, pre-commit prepares the hooks and fails with the above error. If I then run `pre-commit install-hooks` and try to commit again, it works. What's the difference in environment between when pre-commit needs to install hooks at commit time versus what happens when `install-hooks` does its thing? there shouldn't be a difference -- I haven't been able to reproduce the findings either way `strace git commit -av` output: ``` access(".git/hooks/pre-commit", X_OK) = 0 pipe2([3, 5], 0) = 0 openat(AT_FDCWD, "/dev/null", O_RDWR|O_CLOEXEC) = 7 fcntl(7, F_GETFD) = 0x1 (flags FD_CLOEXEC) fcntl(7, F_SETFD, FD_CLOEXEC) = 0 rt_sigprocmask(SIG_SETMASK, ~[RTMIN RT_1], [], 8) = 0 clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f23925eaa10) = 10579 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0 close(5) = 0 read(3, "", 8) = 0 close(3) = 0 close(7) = 0 wait4(10579, [INFO] Installing environment for https://github.com/mrtazz/checkmake.git. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexpected error has occurred: CalledProcessError: command: ('/home/colin/.cache/pre-commit/repoyeyfjm3j/golangenv-default/.go/bin/go', 'install', './...') return code: 1 stdout: (none) stderr: error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. Check the log at /home/colin/.cache/pre-commit/pre-commit.log [{WIFEXITED(s) && WEXITSTATUS(s) == 3}], 0, NULL) = 10579 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=10579, si_uid=1000, si_status=3, si_utime=149, si_stime=61} --- unlink("/home/colin/Source/homebrew-size-analysis/.git/index.lock") = 0 getpid() = 10578 exit_group(1) = ? +++ exited with 1 +++ ``` but I think strace isn't attaching to the process(es) launched from `.git/hooks/pre-commit`, so I altered that to inject strace: exec strace --output pre-commit.strace.log "$INSTALL_PYTHON" -mpre_commit "${ARGS[@]}" The output log is 22 MB. I'm pretty lost in it with the time I have available right now. I've attached it as a ~2.9 MB gzip. Hopefully I'm not leaking anything in this; this Linux system is actually WSL and there's virtually nothing on it. [pre-commit.strace.log.gz](https://github.com/pre-commit/pre-commit/files/11223562/pre-commit.strace.log.gz) I think with `-ff` and `-o` you can get it to follow subprocesses which might help? > I can try. I've not used strace before, though. > > One thing I've noticed on this Linux system is that if I run `pre-commit install-hooks`, the checkmake hook will install correctly and run fine next time I run `git commit`. > > If I run `pre-commit clean` and then `git commit`, pre-commit prepares the hooks and fails with the above error. If I then run `pre-commit install-hooks` and try to commit again, it works. > > What's the difference in environment between when pre-commit needs to install hooks at commit time versus what happens when `install-hooks` does its thing? I've run into the same problem, this post actually fixed the issue for me too. So running Running `pre-commit install-hooks` for some reason is able to download the go-modules when pre-commit is not possible to do so when just running a normal `git commit` command I'm running into the same issue while running `git commit` - on macOS Ventura 13.4.1, - using pre-commit 3.2.0, - and git 2.35.1. This workaround worked for me: prefix the `git commit` command with `GOFLAGS=-buildvcs=false`. I just ran into this. I believe the cause is the fact `go install` is called with a copy of the environment https://github.com/pre-commit/pre-commit/blob/15bd0c7993587dc7d739ac6b1ab939eb9639bc1e/pre_commit/languages/golang.py#L144 which can contain `GIT_INDEX_FILE` when `git commit` is being run. Here's a reproduction using `pre-commit` (tested on `pre-commit 3.3.3`, `go version go1.21.6 linux/amd64`, though I expect the same behaviour for any Go version >= `1.18` when [Go started including VCS info in builds](https://go.dev/doc/go1.18#go-version)): ```bash repo="$(mktemp --directory)" git init "$repo" cd "$repo" cat <<EOF >.pre-commit-config.yaml repos: # repo doesn't matter, anything using Go - repo: https://github.com/segmentio/golines rev: v0.10.0 hooks: - id: golines EOF git add .pre-commit-config.yaml pre-commit install # setup some fresh caches to ensure we do a full download+build mkdir gocache gomodcache pre-commit-cache GOFLAGS='-x' GOCACHE="$PWD/gocache" GOMODCACHE="$PWD/gomodcache" PRE_COMMIT_HOME="$PWD/pre-commit-cache" git commit --all --message 'Install pre-commit' ``` `GOFLAGS='-x'` forces `go` to print commands as it runs them and reports: ``` <--- SNIP: a bunch of download logs ---> cd /tmp/tmp.o1rMm1SgXK/pre-commit-cache/repopbyr_tp4 git status --porcelain # cd /tmp/tmp.o1rMm1SgXK/pre-commit-cache/repopbyr_tp4; git status --porcelain fatal: unable to read 715dc4303df786fdbed5723d06fcca76ba0c9138 error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. error obtaining VCS status: exit status 128 Use -buildvcs=false to disable VCS stamping. Check the log at /tmp/tmp.o1rMm1SgXK/pre-commit-cache/pre-commit.log ``` Note the line `fatal: unable to read 715dc4303df786fdbed5723d06fcca76ba0c9138`: `/tmp/tmp.o1rMm1SgXK/pre-commit-cache/repopbyr_tp4` is the clone of the repo we're trying to build, but `715dc4303df786fdbed5723d06fcca76ba0c9138` is a blob in the repo we're committing in. Maybe the env needs to be cleaned with something like https://github.com/pre-commit/pre-commit/blob/15bd0c7993587dc7d739ac6b1ab939eb9639bc1e/pre_commit/git.py#L27 before running `go install`? Or, as others have noted setting the `buildvcs` build flag: `go install -buildvcs=false ./...` Here's a standalone reproduction, install this under `.git/hooks/pre-commit` and run `go commit -a` with `GOCACHE` and `GOMODCACHE` pointing to some clean caches (like above, so `go` actually tries to build something, and doesn't just reuse the cache): ```bash #!/usr/bin/env bash set -o errexit -o pipefail -o nounset dest="$(mktemp --directory)" trap 'rm -rf -- "$dest"' EXIT # ensure GIT_INDEX_FILE is unset during clone, I believe `pre-commit` does this # otherwise things can fail earlier on, or (confusingly) work fine env --unset GIT_INDEX_FILE git clone --depth 1 https://github.com/segmentio/golines "$dest" cd "$dest" GOFLAGS='-x -v' go install ./... ``` NOTE: I found this didn't reproduce unless the `-a/--all` flag was passed to `git commit`: in this case `GIT_INDEX_FILE` would be an absolute path like `GIT_INDEX_FILE=/tmp/repo/.git/index.lock` but otherwise might be a relative path like: `GIT_INDEX_FILE=.git/index` in which case things can actually work. finally a reproduction! thank you this should be easy enough to fix with the git helper
2024-02-18T18:07:19
pre-commit/pre-commit
3,168
pre-commit__pre-commit-3168
[ "3167" ]
716da1e49c36b8ae46d1dd0ef5aabdb475ee4388
diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py --- a/pre_commit/commands/run.py +++ b/pre_commit/commands/run.py @@ -298,7 +298,7 @@ def _run_hooks( verbose=args.verbose, use_color=args.color, ) retval |= current_retval - if retval and (config['fail_fast'] or hook.fail_fast): + if current_retval and (config['fail_fast'] or hook.fail_fast): break if retval and args.show_diff_on_failure and prior_diff: if args.all_files:
diff --git a/tests/commands/run_test.py b/tests/commands/run_test.py --- a/tests/commands/run_test.py +++ b/tests/commands/run_test.py @@ -1088,6 +1088,22 @@ def test_fail_fast_per_hook(cap_out, store, repo_with_failing_hook): assert printed.count(b'Failing hook') == 1 +def test_fail_fast_not_prev_failures(cap_out, store, repo_with_failing_hook): + with modify_config() as config: + config['repos'].append({ + 'repo': 'meta', + 'hooks': [ + {'id': 'identity', 'fail_fast': True}, + {'id': 'identity', 'name': 'run me!'}, + ], + }) + stage_a_file() + + ret, printed = _do_run(cap_out, store, repo_with_failing_hook, run_opts()) + # should still run the last hook since the `fail_fast` one didn't fail + assert printed.count(b'run me!') == 1 + + def test_classifier_removes_dne(): classifier = Classifier(('this_file_does_not_exist',)) assert classifier.filenames == []
Hook fail_fast stops pre-commit if any prior hook fails ### search you tried in the issue tracker fail fast hook ### describe your issue #### Description Hook `fail_fast` says in the documentation that pre-commit will stop if this hook fails, which suggests it is referring only to the present hook. The actual behaviour appears to be that pre-commit will stop if this *or any previous* hook fails. #### Example Add a Python file containing including a blank line at the end: ```python def my_function(b=): a = "a" ``` Use the config below and call `pre-commit run -a`. #### Expected behaviour All three hooks run. The first and third fail. #### Observed behaviour The first two hooks run. The first hook fails and the second hook passes. #### Note I had previously submitted this as a documentation issue (https://github.com/pre-commit/pre-commit.com/issues/945), because I find the actual behaviour quite useful, as it means we can avoid running a slow hook (e.g. pytest) if any other hook has failed. However, @asottile said this is not the intended behaviour, so resubmitting here as a bug. ### pre-commit --version pre-commit 3.6.2 ### .pre-commit-config.yaml ```yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-ast - id: end-of-file-fixer fail_fast: true - id: double-quote-string-fixer ``` ### ~/.cache/pre-commit/pre-commit.log (if present) Log from terminal, not file. ``` > pre-commit run -a check python ast.........................................................Failed - hook id: check-ast - exit code: 1 file1.py: failed parsing with CPython 3.11.7: Traceback (most recent call last): File "<path_redacted>\check_ast.py", line 21, in main ast.parse(f.read(), filename=filename) File "C:\Program Files\Python311\Lib\ast.py", line 50, in parse return compile(source, filename, mode, flags, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "file1.py", line 1 def my_function(b=): ^ SyntaxError: expected default value expression fix end of files.........................................................Passed ```
2024-03-24T17:17:27
readthedocs/readthedocs.org
467
readthedocs__readthedocs.org-467
[ "349" ]
e95958fd582f1e84c5233ac324de24d7ba244d0c
diff --git a/readthedocs/vcs_support/backends/bzr.py b/readthedocs/vcs_support/backends/bzr.py --- a/readthedocs/vcs_support/backends/bzr.py +++ b/readthedocs/vcs_support/backends/bzr.py @@ -1,4 +1,5 @@ import csv +import re from StringIO import StringIO from projects.exceptions import ProjectImportError @@ -58,7 +59,8 @@ def parse_tags(self, data): 0.2.0-pre-alpha 177 """ # parse the lines into a list of tuples (commit-hash, tag ref name) - raw_tags = csv.reader(StringIO(data), delimiter=' ') + squashed_data = re.sub(r' +', ' ', data) + raw_tags = csv.reader(StringIO(squashed_data), delimiter=' ') vcs_tags = [] for name, commit in raw_tags: vcs_tags.append(VCSVersion(self, commit, name))
Debug bzr tag issue Traceback (most recent call last): File "/home/docs/checkouts/readthedocs.org/readthedocs/projects/tasks.py", line 345, in update_imported_docs tags = version_repo.tags File "/home/docs/checkouts/readthedocs.org/readthedocs/vcs_support/backends/bzr.py", line 46, in tags return self.parse_tags(stdout) File "/home/docs/checkouts/readthedocs.org/readthedocs/vcs_support/backends/bzr.py", line 60, in parse_tags for name, commit in raw_tags: ValueError: too many values to unpack
2013-09-25T11:01:05
readthedocs/readthedocs.org
548
readthedocs__readthedocs.org-548
[ "547" ]
d9942a352812735ed275d004049e7fff0433d758
diff --git a/readthedocs/vcs_support/backends/hg.py b/readthedocs/vcs_support/backends/hg.py --- a/readthedocs/vcs_support/backends/hg.py +++ b/readthedocs/vcs_support/backends/hg.py @@ -1,6 +1,3 @@ -import csv -from StringIO import StringIO - from projects.exceptions import ProjectImportError from vcs_support.base import BaseVCS, VCSVersion @@ -69,19 +66,24 @@ def tags(self): def parse_tags(self, data): """ - Parses output of show-ref --tags, eg: + Parses output of `hg tags`, eg: + + tip 278:c4b2d21db51a + 0.2.2 152:6b0364d98837 + 0.2.1 117:a14b7b6ffa03 + 0.1 50:30c2c6b3a055 + maintenance release 1 10:f83c32fe8126 - tip 278:c4b2d21db51a - 0.2.2 152:6b0364d98837 - 0.2.1 117:a14b7b6ffa03 - 0.1 50:30c2c6b3a055 + Into VCSVersion objects with the tag name as verbose_name and the + commit hash as identifier. """ - # parse the lines into a list of tuples (commit-hash, tag ref name) - raw_tags = csv.reader(StringIO(data), delimiter=' ') vcs_tags = [] - for row in raw_tags: - row = filter(lambda f: f != '', row) - if row == []: + tag_lines = [line.strip() for line in data.splitlines()] + # starting from the rhs of each line, split a single value (changeset) + # off at whitespace; the tag name is the string to the left of that + tag_pairs = [line.rsplit(None, 1) for line in tag_lines] + for row in tag_pairs: + if len(row) != 2: continue name, commit = row if name == 'tip':
mercurial project imported from bitbucket stuck in 'Triggered' state The docs for pylibftdi are set to be built (via a POST trigger) from https://bitbucket.org/codedstructure/pylibftdi, but builds (https://readthedocs.org/builds/pylibftdi/) are stuck at 'Triggered'. Based on comments in #435 I set the project up to build against a github mirror, and that worked successfully, so it seems (from #435) that this is likely an hg issue.
Looks like this is the error: ``` [19/Nov/2013 14:22:49] INFO [vcs_support.base:56] VCS[pylibftdi:latest]: hg tags [19/Nov/2013 14:22:49] INFO [vcs_support.base:60] VCS[pylibftdi:latest]: tip 104:b74c82a64dc6 0.13 102:ff24d3de9a39 0.12 89:88b7b7113d5b 0.11 76:b971b80a8607 0.10.3 65:7e5e09196069 0.10.2 58:8c6471bb5e78 0.10.1 56:9beeef69cefd 0.10 46:36ede894aa9c release 0.9 30:496541913263 release 0.8 19:68d432f9a4cd release 0.7 17:bce2b77265b7 [19/Nov/2013 14:22:49] INFO [vcs_support.utils:42] Lock (pylibftdi): Releasing [19/Nov/2013 14:22:49] ERROR [celery.worker.job:246] Task projects.tasks.update_docs[00f5c839-af52-46f1-9cba-7040c68f48c7] raised exception: ValueError('too many values to unpack',) Traceback (most recent call last): File "/home/docs/local/lib/python2.7/site-packages/celery/task/trace.py", line 233, in trace_task R = retval = fun(*args, **kwargs) File "/home/docs/local/lib/python2.7/site-packages/celery/task/trace.py", line 420, in __protected_call__ return self.run(*args, **kwargs) File "/home/docs/checkouts/readthedocs.org/readthedocs/doc_builder/base.py", line 14, in decorator return fn(*args, **kw) File "/home/docs/checkouts/readthedocs.org/readthedocs/projects/tasks.py", line 142, in update_docs update_output = update_imported_docs(version.pk, api) File "/home/docs/local/lib/python2.7/site-packages/celery/task/trace.py", line 421, in __protected_call__ return orig(self, *args, **kwargs) File "/home/docs/local/lib/python2.7/site-packages/celery/app/task.py", line 329, in __call__ return self.run(*args, **kwargs) File "/home/docs/checkouts/readthedocs.org/readthedocs/projects/tasks.py", line 450, in update_imported_docs } for v in version_repo.tags File "/home/docs/checkouts/readthedocs.org/readthedocs/vcs_support/backends/hg.py", line 68, in tags return self.parse_tags(stdout) File "/home/docs/checkouts/readthedocs.org/readthedocs/vcs_support/backends/hg.py", line 86, in parse_tags name, commit = row ValueError: too many values to unpack ``` https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/vcs_support/backends/hg.py#L80 Looks like we aren't expecting spaces in tags. Yep, was just about to comment that very thing ;-) So it's sort of my fault for having bad tag names earlier on, but at least it exposed a problem. https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/vcs_support/backends/hg.py#L80 Looks like we aren't expecting spaces in tags. On Tue, Nov 19, 2013 at 1:02 PM, Ben Bass [email protected] wrote: > The docs for pylibftdi are set to be built (via a POST trigger) from > https://bitbucket.org/codedstructure/pylibftdi, but builds ( > https://readthedocs.org/builds/pylibftdi/) are stuck at 'Triggered'. > > Based on comments in #435https://github.com/rtfd/readthedocs.org/issues/435I set the project up to build against a github mirror, and that worked > successfully, so it seems (from #435https://github.com/rtfd/readthedocs.org/issues/435) > that this is likely an hg issue. > > — > Reply to this email directly or view it on GitHubhttps://github.com/rtfd/readthedocs.org/issues/547 > . ## Eric Holscher Maker of the internet residing in Portland, Or http://ericholscher.com
2013-11-19T21:42:21
readthedocs/readthedocs.org
596
readthedocs__readthedocs.org-596
[ "561" ]
1cc9b070b7e8307ce33b465c21f06f1376f8b1f7
diff --git a/readthedocs/builds/utils.py b/readthedocs/builds/utils.py --- a/readthedocs/builds/utils.py +++ b/readthedocs/builds/utils.py @@ -30,14 +30,22 @@ def get_bitbucket_username_repo(version): return match.groups() return (None, None) -def get_vcs_version(version): +def get_vcs_version_slug(version): + slug = None if version.slug == 'latest': if version.project.default_branch: - return version.project.default_branch + slug = version.project.default_branch else: - return version.project.vcs_repo().fallback_branch + slug = version.project.vcs_repo().fallback_branch else: - return version.slug + slug = version.slug + # https://github.com/rtfd/readthedocs.org/issues/561 + # version identifiers with / characters in branch name need to un-slugify + # the branch name for remote links to work + if slug.replace('-', '/') in version.identifier: + slug = slug.replace('-', '/') + return slug + def get_conf_py_path(version): conf_py_path = version.project.conf_file(version.slug) diff --git a/readthedocs/doc_builder/backends/sphinx.py b/readthedocs/doc_builder/backends/sphinx.py --- a/readthedocs/doc_builder/backends/sphinx.py +++ b/readthedocs/doc_builder/backends/sphinx.py @@ -126,7 +126,7 @@ def _whitelisted(self, **kwargs): encoding='utf-8', mode='a') outfile.write("\n") conf_py_path = version_utils.get_conf_py_path(self.version) - remote_version = version_utils.get_vcs_version(self.version) + remote_version = version_utils.get_vcs_version_slug(self.version) github_info = version_utils.get_github_username_repo(self.version) bitbucket_info = version_utils.get_bitbucket_username_repo(self.version) if github_info[0] is None:
Edit on GitHub link is broken for branches with e.g. slash in the name If you have docs built from a branch with e.g. slash in the name, like `v1.x/master`, then RTD will "slugify" it and use v1.x-master in URLs. That's OK. The problem is that RTD use this slugified branch name to construct the "Edit on GitHub" URL as well, which then becomes a broken link.
2013-12-28T02:46:57
readthedocs/readthedocs.org
599
readthedocs__readthedocs.org-599
[ "598" ]
1cc9b070b7e8307ce33b465c21f06f1376f8b1f7
diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -724,6 +724,7 @@ def symlink_translations(version): # Hack in the en version for backwards compat symlink = version.project.translations_symlink_path('en') + run_on_app_servers('mkdir -p %s' % '/'.join(symlink.split('/')[:-1])) docs_dir = os.path.join(settings.DOCROOT, version.project.slug, 'rtd-builds') run_on_app_servers('ln -nsf %s %s' % (docs_dir, symlink))
Must create /translations/en directory before symlinking. One of the last steps of the build process is to create the symlink: ``` /user_builds/<project>/translations/en/ -> /user_builds/<project>/rtd_builds/ ``` The symlink creation was failing, because `/translations/en/` must exist before attempting to symlink.
2013-12-31T06:07:18
readthedocs/readthedocs.org
689
readthedocs__readthedocs.org-689
[ "687" ]
d49c3d76e3e02de4d9d3991501674f4b4994e23b
diff --git a/readthedocs/core/views.py b/readthedocs/core/views.py --- a/readthedocs/core/views.py +++ b/readthedocs/core/views.py @@ -4,7 +4,7 @@ """ from django.contrib.auth.models import User -from django.core.urlresolvers import NoReverseMatch, reverse +from django.core.urlresolvers import reverse from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect, Http404, HttpResponseNotFound from django.shortcuts import render_to_response, get_object_or_404, redirect @@ -22,7 +22,6 @@ from core.forms import FacetedSearchForm from projects.models import Project, ImportedFile, ProjectRelationship from projects.tasks import update_docs, remove_dir -from projects.utils import highest_version import json import mimetypes @@ -156,9 +155,11 @@ def _build_branches(project, branch_list): def _build_url(url, branches): try: - projects = Project.objects.filter(repo__contains=url) + projects = Project.objects.filter(repo__endswith=url) if not projects.count(): - raise NoProjectException() + projects = Project.objects.filter(repo__endswith=url + '.git') + if not projects.count(): + raise NoProjectException() for project in projects: (to_build, not_building) = _build_branches(project, branches) if to_build: @@ -301,7 +302,7 @@ def default_docs_kwargs(request, project_slug=None): try: proj = Project.objects.get(slug=project_slug) except (Project.DoesNotExist, ValueError): - # Try with underscore, for legacy + # Try with underscore, for legacy try: proj = Project.objects.get(slug=project_slug.replace('-', '_')) except (Project.DoesNotExist): @@ -312,7 +313,7 @@ def default_docs_kwargs(request, project_slug=None): try: proj = Project.objects.get(slug=request.slug) except (Project.DoesNotExist, ValueError): - # Try with underscore, for legacy + # Try with underscore, for legacy try: proj = Project.objects.get(slug=request.slug.replace('-', '_')) except (Project.DoesNotExist):
build hook has false positives https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/core/views.py#L159 https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/core/views.py#L188 github.com/saltstack/salt will match the following urls: - git://github.com/saltstack/salt.git - https://github.com/saltstack/salt-api - git://github.com/saltstack/salt-cloud.git - git://github.com/saltstack/salt-ui.git Perhaps we should do something like: ``` projects = Project.objects.filter(repo__endswith=url) if projects.count() == 0: projects = Project.objects.filter(repo_endswith=url + '.git') if projects.count() == 0: raise NoProjectException() ``` I'll implement that tonight and see if it works out.
2014-02-20T01:38:49
readthedocs/readthedocs.org
691
readthedocs__readthedocs.org-691
[ "644" ]
123ed2f2a84a5c3d9694757582a651b85e40198a
diff --git a/deploy/scripts/nginx-smoke-test.py b/deploy/scripts/nginx-smoke-test.py --- a/deploy/scripts/nginx-smoke-test.py +++ b/deploy/scripts/nginx-smoke-test.py @@ -173,6 +173,10 @@ def main(): 'https://pip.readthedocs.org/en/latest', 'https://pip.readthedocs.org/en/latest/' ], + [ + 'https://pip.readthedocs.org/en/develop', + 'https://pip.readthedocs.org/en/develop/' + ], [ 'https://pip.readthedocs.org/latest/', 'https://pip.readthedocs.org/en/latest/'
Lack of trailing / in URL breaks links If you don't have the trailing / in the URL i.e. http://sunpy.readthedocs.org/en/latest rather than http://sunpy.readthedocs.org/en/latest/ all the relative URL links on the page, as generated by sphinx, break.
2014-02-20T21:26:48
readthedocs/readthedocs.org
722
readthedocs__readthedocs.org-722
[ "715" ]
9e6009651798c654c3700bafdfa5bbe2414013dd
diff --git a/deploy/salt/readthedocs/site/local_settings.py b/readthedocs/settings/vagrant.py similarity index 97% rename from deploy/salt/readthedocs/site/local_settings.py rename to readthedocs/settings/vagrant.py --- a/deploy/salt/readthedocs/site/local_settings.py +++ b/readthedocs/settings/vagrant.py @@ -1,5 +1,8 @@ # Vagrant development settings +from .base import * # noqa + + REDIS = { 'host': 'localhost', 'port': 6379,
Move vagrant settings to separate file Vagrant provisioning shouldn't use `local_settings`, as pointed out in #709. This moves settings to a separate file and updates the salt states to use the vagrant settings. The vagrant settings don't include an import of `local_settings` because standalone development settings in local_settings could break the vagrant instance configuration.
2014-03-03T18:01:01
readthedocs/readthedocs.org
921
readthedocs__readthedocs.org-921
[ "915" ]
d103d71a5d6670023df6a396f6a0f55f68ceed32
diff --git a/readthedocs/projects/utils.py b/readthedocs/projects/utils.py --- a/readthedocs/projects/utils.py +++ b/readthedocs/projects/utils.py @@ -229,3 +229,21 @@ def make_api_project(project_data): project = Project(**project_data) project.save = _new_save return project + + +def github_paginate(client, url): + """ + Scans trough all github paginates results and returns the concatenated + list of results. + + :param client: requests client instance + :param url: start url to get the data from. + + See https://developer.github.com/v3/#pagination + """ + result = [] + while url: + r = session.get(url) + result.extend(r.json()) + url = r.links.get('next') + return result diff --git a/readthedocs/projects/views/private.py b/readthedocs/projects/views/private.py --- a/readthedocs/projects/views/private.py +++ b/readthedocs/projects/views/private.py @@ -28,6 +28,7 @@ UserForm, EmailHookForm, TranslationForm, AdvancedProjectForm, RedirectForm, WebHookForm) from projects.models import Project, EmailHook, WebHook +from projects.utils import github_paginate from projects import constants from redirects.models import Redirect @@ -457,7 +458,7 @@ def project_import_github(request, sync=False): } ) # Get user repos - owner_resp = session.get('https://api.github.com/user/repos?per_page=100') + owner_resp = github_paginate(session, 'https://api.github.com/user/repos?per_page=100') for repo in owner_resp.json(): log.info('Trying %s' % repo['full_name']) oauth_utils.make_github_project(user=request.user, org=None, privacy=repo_type, repo_json=repo) @@ -465,10 +466,10 @@ def project_import_github(request, sync=False): # Get org repos resp = session.get('https://api.github.com/user/orgs') for org_json in resp.json(): - org_resp = session.get('https://api.github.com/orgs/%s' % org_json['login']) + org_resp = github_paginate(session, 'https://api.github.com/orgs/%s' % org_json['login']) org_obj = oauth_utils.make_github_organization(user=request.user, org_json=org_resp.json()) # Add repos - org_repos_resp = session.get('https://api.github.com/orgs/%s/repos?type=%s' % (org_json['login'], repo_type)) + org_repos_resp = github_paginate(session, 'https://api.github.com/orgs/%s/repos?type=%s' % (org_json['login'], repo_type)) for repo in org_repos_resp.json(): oauth_utils.make_github_project(user=request.user, org=org_obj, privacy=repo_type, repo_json=repo)
Github sync pagination issue After syncing the repos at https://readthedocs.org/dashboard/import/github/ , the ones I'm interested in are now showing up in the list. The issue is that I have more than 100 repos and the code is not using github's pagination over here: - https://github.com/rtfd/readthedocs.org/blob/5c6ff1bd36b1a7e80f6ea7714e9c07c7b2f11769/readthedocs/projects/views/private.py#L460 - https://github.com/rtfd/readthedocs.org/blob/5c6ff1bd36b1a7e80f6ea7714e9c07c7b2f11769/readthedocs/projects/views/private.py#L471 Here is some code I started to implement to replace the session.get(url) call with github_paginate(session, url). I didn't really know where to put it and it's untested. ``` python import re NEXT_MATCH = re.compile('<([^>]+)>;\s*rel="next"') def github_paginate(client, url): """ Scans trough all github paginates results and returns the concatenated result. See https://developer.github.com/v3/#pagination """ result = [] while url: r = session.get(url) result.extend(r.json()) url = None links = r.headers.get('Link') if links: md = NEXT_MATCH.search(links) if md: url = md[0] return result ``` PS: thanks a lot for readthedocs, it's awesome
Great, thanks for the snippet. I believe requests handles the link headers natively, so it should be pretty simple to do. I was wondering how long it would be until someone had more than 100 repos :) Yea, here is the links stuff: http://docs.python-requests.org/en/latest/api/#requests.Response.links Sweet, requests is awesome. Where would you put the helper function in the current code-base ?
2014-09-04T16:14:08
readthedocs/readthedocs.org
1,230
readthedocs__readthedocs.org-1230
[ "1229" ]
4075193cd6e08f62b3e3e99c68977da2c83fb12a
diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -331,7 +331,7 @@ def setup_environment(version): ret_dict['doc_builder'] = run( ( '{cmd} install --use-wheel --find-links={wheeldir} -U {ignore_option} ' - 'sphinx==1.2.2 virtualenv==1.10.1 setuptools==1.1 docutils==0.11 mkdocs==0.11.1 mock==1.0.1 pillow==2.6.1' + 'sphinx==1.2.2 virtualenv==1.10.1 setuptools==1.1 docutils==0.11 mkdocs==0.12.1 mock==1.0.1 pillow==2.6.1' ' readthedocs-sphinx-ext==0.4.4 sphinx-rtd-theme==0.1.6 ' ).format( cmd=project.venv_bin(version=version.slug, bin='pip'),
Mkdocs version 0.11.1 has trailing slash bug with causes problems On a local installation of RTD, latest master, using mkdocs, it looks like files are attempting to be served up with invalid path names: `GET domain.com/docs/project-name/en/latest/queue-work-item` Attempts to serve: `[21/Apr/2015 09:18:13] INFO [core.views:470] Serving queue-work-itemindex.html for Project Name` Notice, the name of the document and `index.html` are mangled without a path separator. I believe the issue stems from `core/views.py` near line 457: ``` python ... and "font" not in filename and not "inv" in filename): filename += "index.html" ... ``` in this case, `filename` is `queue-work-item` so appending `index.html` results in a mangled path.
Actually, upon further inspection, it looks like the `filename` parameter, when referencing a folder, is not being passed correctly. One of the sections is being passed in `filename = communications/` however, the `queue-work-item` section is being passed in without a trailing `/`. This might be a mkdocs issue as the HTML files are sometimes without a trailing slash which is causing the problem. This is a bug with 0.11.1 mkdocs. Updating to 0.12.1 fixes the problem. PR will follow. I've re-titled the bug to correctly reflect the issue.
2015-04-21T17:02:55
readthedocs/readthedocs.org
1,300
readthedocs__readthedocs.org-1300
[ "1073" ]
6f4fb4052ac18affab2270fd7fcc4a778c7d7a89
diff --git a/readthedocs/settings/base.py b/readthedocs/settings/base.py --- a/readthedocs/settings/base.py +++ b/readthedocs/settings/base.py @@ -177,7 +177,8 @@ 'django_gravatar', 'rest_framework', 'corsheaders', - + 'copyright', + # Celery bits 'djcelery', @@ -282,6 +283,8 @@ GRAVATAR_DEFAULT_IMAGE = 'http://media.readthedocs.org/images/silhouette.png' +COPY_START_YEAR = 2010 + LOG_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s" RESTRUCTUREDTEXT_FILTER_SETTINGS = {
Use django-copyright to avoid outdated copyright notice like Copyright 2010-2013. [django-copyright](https://github.com/arteria/django-copyright/) ![screen shot 2014-12-08 at 23 52 36](https://cloud.githubusercontent.com/assets/113043/5349006/828c93cc-7f35-11e4-89b0-c65c9d6a1772.png)
Happily accept a PR adding this. Not a big priority now though :)
2015-05-27T05:03:43
readthedocs/readthedocs.org
1,318
readthedocs__readthedocs.org-1318
[ "1317" ]
2930d83582ff44f41b93cd97d38eccc45b03be1d
diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -336,7 +336,7 @@ def setup_environment(version): 'virtualenv==1.10.1', 'setuptools==1.1', 'docutils==0.11', - 'mkdocs==0.13.2', + 'mkdocs==0.13.3', 'mock==1.0.1', 'pillow==2.6.1', 'readthedocs-sphinx-ext==0.4.4',
Mkdocs missing config argument causes ValidationError I use RTFD service and faced this error in build process>> mkdocs.config.base.ValidationError: The 'site_dir' can't be within the 'docs_dir'. I made indentation changes to a file after the previous passed build, but yet got the above error.
@shravantc Can you show me your config? Basically, it sounds like you have something like this: ``` site_dir: docs/site docs_dir: docs ``` If you do, it will get messy over time. You shouldn't put the site directory within the docs directory (or the other way around). The documentation is hosted in the readthedocs online service and not a local deployment. This is the project : gluster.readthedocs.org This is an error straight from mkdocs, it doesn't seem to be an issue with RTD -- closing this here. This is actually an issue related to the ReadTheDocs integration. The issue is that `docs_dir` can [default to `.` ](https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/doc_builder/base.py#L85) and then the `site_dir` would be `site` and thus relative and within the docs dir. This is an issue because subsequent builds would copy the site dir into itself over and over with each build (MkDocs will copy everything in the docs dir as they are deemed to be static assets). As ReadTheDocs probably does this with a clean env it may not be a problem but in version 0.13, MkDocs stopped users doing this due to the problems people kept seeing. The quick fix would be to move the `site_dir` outside the project directory here: https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/doc_builder/backends/mkdocs.py#L136 I'm not sure if that will cause problems however. Okay, that makes sense. So given the configuration file of: https://github.com/gluster/glusterdocs/blob/master/mkdocs.yml the immediate fix would be to add an explicit `docs_dir`? Is there any reason we need to be setting it in the first place? I'm going to roll a quick MkDocs release to change this to a warning. A docs_dir would be a fix, but in this case the Markdown is in the root of the repo. So the files would also need to be moved. Not ideal. I hadn't considered this use case which is common with RTD. Bug release coming in a few minutes. [Fix in MkDocs](https://github.com/mkdocs/mkdocs/pull/581). Once it passes CI I'll merge and release 0.13.3.
2015-06-02T09:01:47
readthedocs/readthedocs.org
1,330
readthedocs__readthedocs.org-1330
[ "1294" ]
19a114425d74592a780ec08f8caeb3193d252e57
diff --git a/readthedocs/doc_builder/backends/mkdocs.py b/readthedocs/doc_builder/backends/mkdocs.py --- a/readthedocs/doc_builder/backends/mkdocs.py +++ b/readthedocs/doc_builder/backends/mkdocs.py @@ -130,7 +130,7 @@ def build(self, **kwargs): #site_path = os.path.join(checkout_path, 'site') os.chdir(checkout_path) # Actual build - build_command = "{command} {builder} --site-dir={build_dir} --theme=readthedocs".format( + build_command = "{command} {builder} --clean --site-dir={build_dir} --theme=readthedocs".format( command=self.version.project.venv_bin(version=self.version.slug, bin='mkdocs'), builder=self.builder, build_dir=self.build_dir,
Contents are not updated when using mkdocs (md) # Steps to reproduce: Visit http://coala.readthedocs.org/en/latest/ Compare the content listing with http://coala.readthedocs.org/en/latest/Getting_Involved/MAC_Hints/ # Actual results: On the initial landing page the third navigation entry from the bottom is "Writing Commit Messages". On all other pages it is "Writing Good Commits". (Writing commit messages was the old page that doesn't exist anymore in the repository.) # Expected results: The entry should be "Writing Good Commits" in all cases.
Odd. Can you see any errors for the build on https://readthedocs.org/? This is our latest build: https://readthedocs.org/builds/coala/2870604/ I do get some errors because readthedocs tries to install my python project with python 2 but none related to documentation creation. (I tried to turn that off without success.) If you can't access that build info, here's the output: http://pastebin.com/SRUrysrv oh this part might be the interesting one: ``` html ----- Building documentation to directory: _build/html Directory _build/html contains stale files. Use --clean to remove them. ``` @sils1297 Yeah, quite possibly. @d0ugal let me know if you need anything else. ReadTheDocs probably needs to be updated to pass in `--clean`. I am working on updating ReadTheDocs to use the new release of MkDocs, so if it isn't done before I get there I'll add that. Do we just need to add --clean to our call? Possibly yes, I wasn't sure how to try and reproduce this. it certainly won't do any harm.
2015-06-10T08:22:35
readthedocs/readthedocs.org
1,338
readthedocs__readthedocs.org-1338
[ "1337" ]
5c2aeaa6a59084cb13e29538ab1dd188b51b2a75
diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -336,7 +336,7 @@ def setup_environment(version): 'mkdocs==0.13.3', 'mock==1.0.1', 'pillow==2.6.1', - 'readthedocs-sphinx-ext==0.5.3', + 'readthedocs-sphinx-ext==0.5.4', 'sphinx-rtd-theme==0.1.8', 'recommonmark==0.1.1', ])
Failure installing readthedocs-sphinx-ext 0.5.3 We bring in recommonmark as part of the rtd extension, seems it isn't installed as a dependency possibly. ``` Traceback (most recent call last): File "/home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages/sphinx/cmdline.py", line 244, in main opts.warningiserror, opts.tags, opts.verbosity, opts.jobs) File "/home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages/sphinx/application.py", line 126, in __init__ confoverrides or {}, self.tags) File "/home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages/sphinx/config.py", line 277, in __init__ execfile_(filename, config) File "/home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages/sphinx/util/pycompat.py", line 128, in execfile_ exec_(code, _globals) File "conf.py", line 300, in <module> from recommonmark.parser import CommonMarkParser ImportError: No module named 'recommonmark' Exception occurred: File "conf.py", line 300, in <module> from recommonmark.parser import CommonMarkParser ImportError: No module named 'recommonmark' ```
Noticed this as part of JuliaLang/julia#11527 Actually, I should have continued looking at the build errors. Seems this is just a side effect of requirements installation failures: ``` Requirement already up-to-date: sphinx==1.3.1 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages Requirement already up-to-date: Pygments==2.0.2 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages Collecting virtualenv==1.10.1 Collecting setuptools==1.1 Collecting docutils==0.11 Collecting mkdocs==0.13.3 Using cached mkdocs-0.13.3-py2.py3-none-any.whl Collecting mock==1.0.1 Collecting pillow==2.6.1 Collecting readthedocs-sphinx-ext==0.5.3 Using cached readthedocs_sphinx_ext-0.5.3-py2.py3-none-any.whl Collecting sphinx-rtd-theme==0.1.8 Using cached sphinx_rtd_theme-0.1.8-py2.py3-none-any.whl Collecting recommonmark==0.1.1 Using cached recommonmark-0.1.1-py2.py3-none-any.whl Requirement already up-to-date: alabaster<0.8,>=0.7 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) Requirement already up-to-date: snowballstemmer>=1.1 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) Requirement already up-to-date: Jinja2>=2.3 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) Requirement already up-to-date: babel>=1.3 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) Requirement already up-to-date: six>=1.4 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) Collecting PyYAML>=3.10 (from mkdocs==0.13.3) Collecting click>=4.0 (from mkdocs==0.13.3) Using cached click-4.0-py2.py3-none-any.whl Collecting livereload>=2.3.2 (from mkdocs==0.13.3) Using cached livereload-2.4.0-py2.py3-none-any.whl Collecting tornado>=4.1 (from mkdocs==0.13.3) Collecting Markdown>=2.3.1 (from mkdocs==0.13.3) Using cached Markdown-2.6.2-py2.py3-none-any.whl Collecting ghp-import>=0.4.1 (from mkdocs==0.13.3) Collecting nilsimsa (from readthedocs-sphinx-ext==0.5.3) Using cached nilsimsa-0.3.6.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 20, in <module> File "/tmp/pip-build-d5ecjt_7/nilsimsa/setup.py", line 5, in <module> from version import get_git_version File "/tmp/pip-build-d5ecjt_7/nilsimsa/version.py", line 78 except Exception, exc: ^ SyntaxError: invalid syntax ---------------------------------------- ``` Confirmed the server that ran this is using a new readthedocs-sphinx-ext (`0.5.3`), versus the other servers which use `0.4.4`. This seems to possibly be triggered by import of the nilsimsa package via the extension. I believe this is probably a bug where we don't stop building after requirements fail. We should just not try and build docs in that case, which is likely what the real issue is. On Thu, Jun 11, 2015 at 12:39 PM, Anthony [email protected] wrote: > Actually, I should have continued looking at the build errors. Seems this > is just a side effect of requirements installation failures: > > Requirement already up-to-date: sphinx==1.3.1 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages > Requirement already up-to-date: Pygments==2.0.2 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages > Collecting virtualenv==1.10.1 > Collecting setuptools==1.1 > Collecting docutils==0.11 > Collecting mkdocs==0.13.3 > Using cached mkdocs-0.13.3-py2.py3-none-any.whl > Collecting mock==1.0.1 > Collecting pillow==2.6.1 > Collecting readthedocs-sphinx-ext==0.5.3 > Using cached readthedocs_sphinx_ext-0.5.3-py2.py3-none-any.whl > Collecting sphinx-rtd-theme==0.1.8 > Using cached sphinx_rtd_theme-0.1.8-py2.py3-none-any.whl > Collecting recommonmark==0.1.1 > Using cached recommonmark-0.1.1-py2.py3-none-any.whl > Requirement already up-to-date: alabaster<0.8,>=0.7 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) > Requirement already up-to-date: snowballstemmer>=1.1 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) > Requirement already up-to-date: Jinja2>=2.3 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) > Requirement already up-to-date: babel>=1.3 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) > Requirement already up-to-date: six>=1.4 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) > Collecting PyYAML>=3.10 (from mkdocs==0.13.3) > Collecting click>=4.0 (from mkdocs==0.13.3) > Using cached click-4.0-py2.py3-none-any.whl > Collecting livereload>=2.3.2 (from mkdocs==0.13.3) > Using cached livereload-2.4.0-py2.py3-none-any.whl > Collecting tornado>=4.1 (from mkdocs==0.13.3) > Collecting Markdown>=2.3.1 (from mkdocs==0.13.3) > Using cached Markdown-2.6.2-py2.py3-none-any.whl > Collecting ghp-import>=0.4.1 (from mkdocs==0.13.3) > Collecting nilsimsa (from readthedocs-sphinx-ext==0.5.3) > Using cached nilsimsa-0.3.6.tar.gz > Complete output from command python setup.py egg_info: > Traceback (most recent call last): > File "<string>", line 20, in <module> > File "/tmp/pip-build-d5ecjt_7/nilsimsa/setup.py", line 5, in <module> > from version import get_git_version > File "/tmp/pip-build-d5ecjt_7/nilsimsa/version.py", line 78 > except Exception, exc: > ^ > SyntaxError: invalid syntax > > ``` > ---------------------------------------- > ``` > > Confirmed the server that ran this is using a new sphinx-rtd-extension ( > 0.5.3), versus the other servers which use 0.4.4. This seems to possibly > be triggered by import of the nilsimsa package via the extension. > > — > Reply to this email directly or view it on GitHub > https://github.com/rtfd/readthedocs.org/issues/1337#issuecomment-111255787 > . ## Eric Holscher Maker of the internet residing in Portland, Oregon http://ericholscher.com Ah, wonder if that's a py3 issue. On Thu, Jun 11, 2015 at 12:40 PM, Eric Holscher [email protected] wrote: > I believe this is probably a bug where we don't stop building after > requirements fail. We should just not try and build docs in that case, > which is likely what the real issue is. > > On Thu, Jun 11, 2015 at 12:39 PM, Anthony [email protected] > wrote: > > > Actually, I should have continued looking at the build errors. Seems this > > is just a side effect of requirements installation failures: > > > > Requirement already up-to-date: sphinx==1.3.1 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages > > Requirement already up-to-date: Pygments==2.0.2 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages > > Collecting virtualenv==1.10.1 > > Collecting setuptools==1.1 > > Collecting docutils==0.11 > > Collecting mkdocs==0.13.3 > > Using cached mkdocs-0.13.3-py2.py3-none-any.whl > > Collecting mock==1.0.1 > > Collecting pillow==2.6.1 > > Collecting readthedocs-sphinx-ext==0.5.3 > > Using cached readthedocs_sphinx_ext-0.5.3-py2.py3-none-any.whl > > Collecting sphinx-rtd-theme==0.1.8 > > Using cached sphinx_rtd_theme-0.1.8-py2.py3-none-any.whl > > Collecting recommonmark==0.1.1 > > Using cached recommonmark-0.1.1-py2.py3-none-any.whl > > Requirement already up-to-date: alabaster<0.8,>=0.7 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) > > Requirement already up-to-date: snowballstemmer>=1.1 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) > > Requirement already up-to-date: Jinja2>=2.3 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) > > Requirement already up-to-date: babel>=1.3 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) > > Requirement already up-to-date: six>=1.4 in /home/docs/checkouts/readthedocs.org/user_builds/julia/envs/latest/lib/python3.4/site-packages (from sphinx==1.3.1) > > Collecting PyYAML>=3.10 (from mkdocs==0.13.3) > > Collecting click>=4.0 (from mkdocs==0.13.3) > > Using cached click-4.0-py2.py3-none-any.whl > > Collecting livereload>=2.3.2 (from mkdocs==0.13.3) > > Using cached livereload-2.4.0-py2.py3-none-any.whl > > Collecting tornado>=4.1 (from mkdocs==0.13.3) > > Collecting Markdown>=2.3.1 (from mkdocs==0.13.3) > > Using cached Markdown-2.6.2-py2.py3-none-any.whl > > Collecting ghp-import>=0.4.1 (from mkdocs==0.13.3) > > Collecting nilsimsa (from readthedocs-sphinx-ext==0.5.3) > > Using cached nilsimsa-0.3.6.tar.gz > > Complete output from command python setup.py egg_info: > > Traceback (most recent call last): > > File "<string>", line 20, in <module> > > File "/tmp/pip-build-d5ecjt_7/nilsimsa/setup.py", line 5, in <module> > > from version import get_git_version > > File "/tmp/pip-build-d5ecjt_7/nilsimsa/version.py", line 78 > > except Exception, exc: > > ^ > > SyntaxError: invalid syntax > > > > ``` > > ---------------------------------------- > > ``` > > > > Confirmed the server that ran this is using a new sphinx-rtd-extension ( > > 0.5.3), versus the other servers which use 0.4.4. This seems to possibly > > be triggered by import of the nilsimsa package via the extension. > > > > — > > Reply to this email directly or view it on GitHub > > https://github.com/rtfd/readthedocs.org/issues/1337#issuecomment-111255787 > > . > > ## > > Eric Holscher > Maker of the internet residing in Portland, Oregon > http://ericholscher.com ## Eric Holscher Maker of the internet residing in Portland, Oregon http://ericholscher.com It is, on the nilsimsa package, they are working on py3 support still. Opened rtfd/readthedocs-sphinx-ext#8 Testing hack patch now, should have a PR up soon to address this temporarily. > Confirmed the server that ran this is using a new readthedocs-sphinx-ext (0.5.3), versus the other servers which use 0.4.4. I was wondering why only about half of the builds had failures. The trouble module was patched earlier, waiting on a release of readthedocs-sphinx-ext 0.5.4 with more py3 fixes.
2015-06-11T22:52:34
readthedocs/readthedocs.org
1,374
readthedocs__readthedocs.org-1374
[ "1373" ]
b1a9f4c5f85d3a2a1bcbf95da52c8ace1161c2e0
diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -334,7 +334,7 @@ def setup_environment(version): 'virtualenv==1.10.1', 'setuptools==1.1', 'docutils==0.11', - 'mkdocs==0.13.3', + 'mkdocs==0.14.0', 'mock==1.0.1', 'pillow==2.6.1', 'readthedocs-sphinx-ext==0.5.4',
jinja2 exception - unexpected '}' We didn't change anything in the documentation nor the mkdocs config file but the documentation is not built anymore. Here is the link to a failed build: https://readthedocs.org/builds/mongooseim/3000853/ and the repo is cloned from here: https://github.com/esl/MongooseIM
This is an issue that was resolved in MkDocs 0.14, I need to update ReadTheDocs. You can work around it by adding this to your config. Basically, it is trying to discover extra templates in your documentation if we set the setting as blank it wont do that. ``` extra_templates: ``` 0.14 turned this off by default, as although it was useful having it enabled caused some issues. Thanks for the advice. This worked for me: ``` extra_templates: [] ```
2015-06-24T11:24:49
readthedocs/readthedocs.org
1,404
readthedocs__readthedocs.org-1404
[ "1403" ]
5b59828ba14d3409613c7b5302e1cdcd2920eb11
diff --git a/readthedocs/projects/utils.py b/readthedocs/projects/utils.py --- a/readthedocs/projects/utils.py +++ b/readthedocs/projects/utils.py @@ -69,6 +69,10 @@ def run(*commands, **kwargs): del environment['DJANGO_SETTINGS_MODULE'] if 'PYTHONPATH' in environment: del environment['PYTHONPATH'] + # Remove PYTHONHOME env variable if set, otherwise pip install of requirements + # into virtualenv will install incorrectly + if 'PYTHONHOME' in environment: + del environment['PYTHONHOME'] cwd = os.getcwd() if not commands: raise ValueError("run() requires one or more command-line strings")
Pip install failing to install sphinx when PYTHON_HOME is set If the env variable PYTHON_HOME exists, pip install is failing to install spinx into the virtualenv.
2015-07-05T19:54:41
readthedocs/readthedocs.org
1,407
readthedocs__readthedocs.org-1407
[ "1405" ]
c537b05b46c59c26e79ac37136dc1878ff972613
diff --git a/readthedocs/builds/version_slug.py b/readthedocs/builds/version_slug.py --- a/readthedocs/builds/version_slug.py +++ b/readthedocs/builds/version_slug.py @@ -27,10 +27,10 @@ # Regex breakdown: # [a-z0-9] -- start with alphanumeric value # [-._a-z0-9] -- allow dash, dot, underscore, digit, lowercase ascii -# +? -- allow multiple of those, but be not greedy about the matching +# *? -- allow multiple of those, but be not greedy about the matching # (?: ... ) -- wrap everything so that the pattern cannot escape when used in # regexes. -VERSION_SLUG_REGEX = '(?:[a-z0-9][-._a-z0-9]+?)' +VERSION_SLUG_REGEX = '(?:[a-z0-9][-._a-z0-9]*?)' class VersionSlugField(models.CharField):
diff --git a/readthedocs/rtd_tests/tests/test_version_slug.py b/readthedocs/rtd_tests/tests/test_version_slug.py --- a/readthedocs/rtd_tests/tests/test_version_slug.py +++ b/readthedocs/rtd_tests/tests/test_version_slug.py @@ -1,10 +1,30 @@ +import re from django.test import TestCase from builds.models import Version from builds.version_slug import VersionSlugField +from builds.version_slug import VERSION_SLUG_REGEX from projects.models import Project +class VersionSlugPatternTests(TestCase): + pattern = re.compile('^{pattern}$'.format(pattern=VERSION_SLUG_REGEX)) + + def test_single_char(self): + self.assertTrue(self.pattern.match('v')) + self.assertFalse(self.pattern.match('.')) + + def test_trailing_punctuation(self): + self.assertTrue(self.pattern.match('with_')) + self.assertTrue(self.pattern.match('with.')) + self.assertTrue(self.pattern.match('with-')) + self.assertFalse(self.pattern.match('with!')) + + def test_multiple_words(self): + self.assertTrue(self.pattern.match('release-1.0')) + self.assertTrue(self.pattern.match('fix_this-and-that.')) + + class VersionSlugFieldTests(TestCase): fixtures = ["eric", "test_data"]
Migration failing on version slugs Running migrations on #1396, I hit the following error: ``` Traceback (most recent call last): File "/home/docs/bin/django-admin.py", line 5, in <module> management.execute_from_command_line() File "/home/docs/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_li ne utility.execute() File "/home/docs/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/docs/local/lib/python2.7/site-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/home/docs/local/lib/python2.7/site-packages/django/core/management/base.py", line 285, in execute output = self.handle(*args, **options) File "/home/docs/local/lib/python2.7/site-packages/south/management/commands/migrate.py", line 111, in handle ignore_ghosts = ignore_ghosts, File "/home/docs/local/lib/python2.7/site-packages/south/migration/__init__.py", line 220, in migrate_app success = migrator.migrate_many(target, workplan, database) File "/home/docs/local/lib/python2.7/site-packages/south/migration/migrators.py", line 256, in migrate_many result = migrator.__class__.migrate_many(migrator, target, migrations, database) File "/home/docs/local/lib/python2.7/site-packages/south/migration/migrators.py", line 331, in migrate_many result = self.migrate(migration, database) File "/home/docs/local/lib/python2.7/site-packages/south/migration/migrators.py", line 133, in migrate result = self.run(migration, database) File "/home/docs/local/lib/python2.7/site-packages/south/migration/migrators.py", line 114, in run return self.run_migration(migration, database) File "/home/docs/local/lib/python2.7/site-packages/south/migration/migrators.py", line 84, in run_migration migration_function() File "/home/docs/local/lib/python2.7/site-packages/south/migration/migrators.py", line 60, in <lambda> return (lambda: direction(orm)) File "/home/docs/checkouts/readthedocs.org/readthedocs/builds/migrations/0024_fix_slugs_with_leading_placeholders.py", line 21, in forwards version.slug = slug_field.create_slug(version) File "/home/docs/checkouts/readthedocs.org/readthedocs/builds/version_slug.py", line 145, in create_slug 'Invalid generated slug: {slug}'.format(slug=slug)) AssertionError: Invalid generated slug: v ``` cc @gregmuellegger
2015-07-06T10:04:14
readthedocs/readthedocs.org
1,429
readthedocs__readthedocs.org-1429
[ "1428" ]
d0d23dee8ae0163db7beadb061a6d3db385e998f
diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -331,8 +331,8 @@ def setup_environment(version): requirements = ' '.join([ 'sphinx==1.3.1', 'Pygments==2.0.2', - 'virtualenv==1.10.1', - 'setuptools==1.1', + 'virtualenv==13.1.0', + 'setuptools==18.0.1', 'docutils==0.11', 'mkdocs==0.14.0', 'mock==1.0.1',
setuptools being downgraded This is a follow-on to #1426. With the newer virtualenv the requirements.txt processing does manage to complete, but the install target fails due to very old setuptools (1.1!) - the doc_builder target appears to be downgrading it to 1.1 in the middle. :(. ``` doc_builder ----- Collecting sphinx==1.3.1 ... Collecting virtualenv==1.10.1 Collecting setuptools==1.1 ... Found existing installation: setuptools 18.0.1 Uninstalling setuptools-18.0.1: Successfully uninstalled setuptools-18.0.1 Successfully installed Jinja2-2.7.3 Markdown-2.6.2 PyYAML-3.11 Pygments-2.0.2 alabaster-0.7.6 babel-1.3 backports.ssl-match-hostname-3.4.0.2 certifi-2015.4.28 click-4.0 commonmark-0.5.4 docutils-0.11 livereload-2.4.0 markupsafe-0.23 mkdocs-0.14.0 mock-1.0.1 nilsimsa-0.3.7 pillow-2.6.1 pytz-2015.4 readthedocs-sphinx-ext-0.5.4 recommonmark-0.1.1 requests-2.7.0 setuptools-1.1 six-1.9.0 snowballstemmer-1.2.0 sphinx-1.3.1 sphinx-rtd-theme-0.1.8 tornado-4.2 virtualenv-1.10.1 ``` This is from https://readthedocs.org/builds/mock/3074098/
And https://github.com/rtfd/readthedocs.org/blob/b4c6c7bcd750bd0751c7a151b485b22df932a435/readthedocs/projects/tasks.py#L335 seems to be the culprit. I don't know why setuptools 1.1 is being pinned - but its really rather old. In fact - https://github.com/rtfd/readthedocs.org/commit/d5d71c0d1e326a38ab607d2e688982e439b3c35e is where it was introduced. Would a PR to bump that to 18 be acceptable?
2015-07-13T07:44:48
readthedocs/readthedocs.org
1,431
readthedocs__readthedocs.org-1431
[ "1425" ]
d0d23dee8ae0163db7beadb061a6d3db385e998f
diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -607,9 +607,13 @@ def has_aliases(self): return self.aliases.exists() def has_pdf(self, version_slug=LATEST): + if not self.enable_pdf_build: + return False return os.path.exists(self.get_production_media_path(type='pdf', version_slug=version_slug)) def has_epub(self, version_slug=LATEST): + if not self.enable_epub_build: + return False return os.path.exists(self.get_production_media_path(type='epub', version_slug=version_slug)) def has_htmlzip(self, version_slug=LATEST):
diff --git a/readthedocs/rtd_tests/mocks/paths.py b/readthedocs/rtd_tests/mocks/paths.py new file mode 100644 --- /dev/null +++ b/readthedocs/rtd_tests/mocks/paths.py @@ -0,0 +1,53 @@ +import os +import re +import mock + + +def fake_paths(check): + """ + >>> with fake_paths(lambda path: True if path.endswith('.pdf') else None): + ... assert os.path.exists('my.pdf') + ... assert os.path.exists('Nopdf.txt') + + The first assertion will be ok, the second assertion is not faked as the + ``check`` returned ``None`` for this path. + """ + + original_exists = os.path.exists + + def patched_exists(path): + result = check(path) + if result is None: + return original_exists(path) + return result + + return mock.patch.object(os.path, 'exists', patched_exists) + + +def fake_paths_lookup(path_dict): + """ + >>> paths = {'my.txt': True, 'no.txt': False} + >>> with fake_paths_lookup(paths): + ... assert os.path.exists('my.txt') == True + ... assert os.path.exists('no.txt') == False + """ + def check(path): + return path_dict.get(path, None) + return fake_paths(check) + + +def fake_paths_by_regex(pattern, exists=True): + """ + >>> with fake_paths_by_regex('\.pdf$'): + ... assert os.path.exists('my.pdf') == True + >>> with fake_paths_by_regex('\.pdf$', exists=False): + ... assert os.path.exists('my.pdf') == False + """ + regex = re.compile(pattern) + + def check(path): + if regex.search(path): + return exists + return None + + return fake_paths(check) diff --git a/readthedocs/rtd_tests/tests/test_builds.py b/readthedocs/rtd_tests/tests/test_builds.py --- a/readthedocs/rtd_tests/tests/test_builds.py +++ b/readthedocs/rtd_tests/tests/test_builds.py @@ -6,6 +6,7 @@ from projects.tasks import build_docs from rtd_tests.factories.projects_factories import ProjectFactory +from rtd_tests.mocks.paths import fake_paths_lookup from doc_builder.loader import get_builder_class @@ -29,22 +30,6 @@ def build_subprocess_side_effect(*args, **kwargs): return subprocess.Popen(*args, **kwargs) -def fake_paths(*paths): - """ - Returns a context manager that patches ``os.path.exists`` to return - ``True`` for the given ``paths``. - """ - - original_exists = os.path.exists - - def patched_exists(path): - if path in paths: - return True - return original_exists(path) - - return mock.patch.object(os.path, 'exists', patched_exists) - - class BuildTests(TestCase): @mock.patch('slumber.Resource') @@ -68,11 +53,13 @@ def test_build(self, mock_Popen, mock_api_versions, mock_chdir, mock_apiv2_downl mock_apiv2_downloads.get.return_value = {'downloads': "no_url_here"} - conf_path = os.path.join(project.checkout_path(version.slug), project.conf_py_file) + conf_path = os.path.join( + project.checkout_path(version.slug), + project.conf_py_file) # Mock open to simulate existing conf.py file with mock.patch('codecs.open', mock.mock_open(), create=True): - with fake_paths(conf_path): + with fake_paths_lookup({conf_path: True}): built_docs = build_docs(version, False, False, @@ -136,7 +123,7 @@ def test_build_respects_pdf_flag(self, # Mock open to simulate existing conf.py file with mock.patch('codecs.open', mock.mock_open(), create=True): - with fake_paths(conf_path): + with fake_paths_lookup({conf_path: True}): built_docs = build_docs(version, False, False, @@ -180,7 +167,7 @@ def test_build_respects_epub_flag(self, # Mock open to simulate existing conf.py file with mock.patch('codecs.open', mock.mock_open(), create=True): - with fake_paths(conf_path): + with fake_paths_lookup({conf_path: True}): built_docs = build_docs(version, False, False, diff --git a/readthedocs/rtd_tests/tests/test_footer.py b/readthedocs/rtd_tests/tests/test_footer.py --- a/readthedocs/rtd_tests/tests/test_footer.py +++ b/readthedocs/rtd_tests/tests/test_footer.py @@ -2,6 +2,7 @@ from django.test import TestCase +from rtd_tests.mocks.paths import fake_paths_by_regex from projects.models import Project @@ -28,3 +29,30 @@ def test_footer(self): self.assertEqual(resp['version_active'], False) self.assertEqual(r.status_code, 200) + def test_pdf_build_mentioned_in_footer(self): + with fake_paths_by_regex('\.pdf$'): + response = self.client.get( + '/api/v2/footer_html/?project=pip&version=latest&page=index', {}) + self.assertContains(response, 'pdf') + + def test_pdf_not_mentioned_in_footer_when_build_is_disabled(self): + self.pip.enable_pdf_build = False + self.pip.save() + with fake_paths_by_regex('\.pdf$'): + response = self.client.get( + '/api/v2/footer_html/?project=pip&version=latest&page=index', {}) + self.assertNotContains(response, 'pdf') + + def test_epub_build_mentioned_in_footer(self): + with fake_paths_by_regex('\.epub$'): + response = self.client.get( + '/api/v2/footer_html/?project=pip&version=latest&page=index', {}) + self.assertContains(response, 'epub') + + def test_epub_not_mentioned_in_footer_when_build_is_disabled(self): + self.pip.enable_epub_build = False + self.pip.save() + with fake_paths_by_regex('\.epub$'): + response = self.client.get( + '/api/v2/footer_html/?project=pip&version=latest&page=index', {}) + self.assertNotContains(response, 'epub') diff --git a/readthedocs/rtd_tests/tests/test_project.py b/readthedocs/rtd_tests/tests/test_project.py --- a/readthedocs/rtd_tests/tests/test_project.py +++ b/readthedocs/rtd_tests/tests/test_project.py @@ -1,11 +1,13 @@ from bamboo_boy.utils import with_canopy import json from django.test import TestCase +from builds.constants import LATEST from projects.models import Project from rtd_tests.factories.projects_factories import OneProjectWithTranslationsOneWithout,\ ProjectFactory from rest_framework.reverse import reverse from restapi.serializers import ProjectSerializer +from rtd_tests.mocks.paths import fake_paths_by_regex @with_canopy(OneProjectWithTranslationsOneWithout) @@ -50,3 +52,33 @@ def test_token(self): resp = json.loads(r.content) self.assertEqual(r.status_code, 200) self.assertEqual(resp['token'], None) + + def test_has_pdf(self): + # The project has a pdf if the PDF file exists on disk. + with fake_paths_by_regex('\.pdf$'): + self.assertTrue(self.pip.has_pdf(LATEST)) + + # The project has no pdf if there is no file on disk. + with fake_paths_by_regex('\.pdf$', exists=False): + self.assertFalse(self.pip.has_pdf(LATEST)) + + def test_has_pdf_with_pdf_build_disabled(self): + # The project has NO pdf if pdf builds are disabled + self.pip.enable_pdf_build = False + with fake_paths_by_regex('\.pdf$'): + self.assertFalse(self.pip.has_pdf(LATEST)) + + def test_has_epub(self): + # The project has a epub if the PDF file exists on disk. + with fake_paths_by_regex('\.epub$'): + self.assertTrue(self.pip.has_epub(LATEST)) + + # The project has no epub if there is no file on disk. + with fake_paths_by_regex('\.epub$', exists=False): + self.assertFalse(self.pip.has_epub(LATEST)) + + def test_has_epub_with_epub_build_disabled(self): + # The project has NO epub if epub builds are disabled + self.pip.enable_epub_build = False + with fake_paths_by_regex('\.epub$'): + self.assertFalse(self.pip.has_epub(LATEST))
Link to PDF in RTD popup menu shows even though PDF build is turned off See https://github.com/rtfd/readthedocs.org/pull/1344#issuecomment-120510729 The link is in the RTD popup menu ![RTD popup menu](http://i.imgur.com/9E5C1Sl.png) An example is in [Pyramid docs](http://docs.pylonsproject.org/projects/pyramid/en/latest/).
2015-07-13T09:04:46
readthedocs/readthedocs.org
1,448
readthedocs__readthedocs.org-1448
[ "1442" ]
fad2c311ee3198bc59ba829b73656b64eaa82590
diff --git a/readthedocs/core/views.py b/readthedocs/core/views.py --- a/readthedocs/core/views.py +++ b/readthedocs/core/views.py @@ -249,6 +249,31 @@ def github_build(request): return HttpResponse("You must POST to this resource.") +@csrf_exempt +def gitlab_build(request): + """ + A post-commit hook for GitLab. + """ + if request.method == 'POST': + try: + # GitLab RTD integration + obj = json.loads(request.POST['payload']) + except: + # Generic post-commit hook + obj = json.loads(request.body) + url = obj['repository']['homepage'] + ghetto_url = url.replace('http://', '').replace('https://', '') + branch = obj['ref'].replace('refs/heads/', '') + pc_log.info("(Incoming GitLab Build) %s [%s]" % (ghetto_url, branch)) + try: + return _build_url(ghetto_url, [branch]) + except NoProjectException: + pc_log.error( + "(Incoming GitLab Build) Repo not found: %s" % ghetto_url) + return HttpResponseNotFound('Repo not found: %s' % ghetto_url) + else: + return HttpResponse("You must POST to this resource.") + @csrf_exempt def bitbucket_build(request): if request.method == 'POST': diff --git a/readthedocs/urls.py b/readthedocs/urls.py --- a/readthedocs/urls.py +++ b/readthedocs/urls.py @@ -101,6 +101,7 @@ url(r'^admin/', include(admin.site.urls)), url(r'^dashboard/', include('projects.urls.private')), url(r'^github', 'core.views.github_build', name='github_build'), + url(r'^gitlab', 'core.views.gitlab_build', name='gitlab_build'), url(r'^bitbucket', 'core.views.bitbucket_build', name='bitbucket_build'), url((r'^build/' r'(?P<project_id_or_slug>{project_slug})'.format(**pattern_opts)),
diff --git a/readthedocs/rtd_tests/tests/test_post_commit_hooks.py b/readthedocs/rtd_tests/tests/test_post_commit_hooks.py --- a/readthedocs/rtd_tests/tests/test_post_commit_hooks.py +++ b/readthedocs/rtd_tests/tests/test_post_commit_hooks.py @@ -8,6 +8,101 @@ log = logging.getLogger(__name__) +class GitLabWebHookTest(TestCase): + fixtures = ["eric", "test_data"] + + def tearDown(self): + tasks.update_docs = self.old_bd + + def setUp(self): + self.old_bd = tasks.update_docs + + def mock(*args, **kwargs): + log.info("Mocking for great profit and speed.") + tasks.update_docs = mock + tasks.update_docs.delay = mock + + self.client.login(username='eric', password='test') + self.payload = { + "object_kind": "push", + "before": "95790bf891e76fee5e1747ab589903a6a1f80f22", + "after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", + "ref": "refs/heads/awesome", + "user_id": 4, + "user_name": "John Smith", + "user_email": "[email protected]", + "project_id": 15, + "repository": { + "name": "Diaspora", + "url": "[email protected]:rtfd/readthedocs.org.git", + "description": "", + "homepage": "http://github.com/rtfd/readthedocs.org", + "git_http_url": "http://github.com/rtfd/readthedocs.org.git", + "git_ssh_url": "[email protected]:rtfd/readthedocs.org.git", + "visibility_level":0 + }, + "commits": [ + { + "id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", + "message": "Update Catalan translation to e38cb41.", + "timestamp": "2011-12-12T14:27:31+02:00", + "url": "http://github.com/mike/diaspora/commit/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327", + "author": { + "name": "Jordi Mallach", + "email": "[email protected]" + } + }, + { + "id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7", + "message": "fixed readme", + "timestamp": "2012-01-03T23:36:29+02:00", + "url": "http://github.com/mike/diaspora/commit/da1560886d4f094c3e6c9ef40349f7d38b5d27d7", + "author": { + "name": "GitLab dev user", + "email": "gitlabdev@dv6700.(none)" + } + } + ], + "total_commits_count": 4 + } + + def test_gitlab_post_commit_hook_builds_branch_docs_if_it_should(self): + """ + Test the github post commit hook to see if it will only build + versions that are set to be built if the branch they refer to + is updated. Otherwise it is no op. + """ + r = self.client.post('/gitlab/', {'payload': json.dumps(self.payload)}) + self.assertEqual(r.status_code, 200) + self.assertEqual(r.content, '(URL Build) Build Started: github.com/rtfd/readthedocs.org [awesome]') + self.payload['ref'] = 'refs/heads/not_ok' + r = self.client.post('/gitlab/', {'payload': json.dumps(self.payload)}) + self.assertEqual(r.status_code, 200) + self.assertEqual(r.content, '(URL Build) Not Building: github.com/rtfd/readthedocs.org [not_ok]') + self.payload['ref'] = 'refs/heads/unknown' + r = self.client.post('/gitlab/', {'payload': json.dumps(self.payload)}) + self.assertEqual(r.status_code, 200) + self.assertEqual(r.content, '(URL Build) Not Building: github.com/rtfd/readthedocs.org []') + + def test_gitlab_post_commit_knows_default_branches(self): + """ + Test the gitlab post commit hook so that the default branch + will be respected and built as the latest version. + """ + rtd = Project.objects.get(slug='read-the-docs') + old_default = rtd.default_branch + rtd.default_branch = 'master' + rtd.save() + self.payload['ref'] = 'refs/heads/master' + + r = self.client.post('/gitlab/', {'payload': json.dumps(self.payload)}) + self.assertEqual(r.status_code, 200) + self.assertEqual(r.content, '(URL Build) Build Started: github.com/rtfd/readthedocs.org [latest]') + + rtd.default_branch = old_default + rtd.save() + + class PostCommitTest(TestCase): fixtures = ["eric", "test_data"]
Add GitLab Web Hook End-Point Need to add an end-point to Read the Docs to received on-push events from a GitLab installation. The GitLab end-point would be similar to Read the Docs' existing [GitHub support](https://github.com/rtfd/readthedocs.org/blob/1511716c9c984e7a53521c0fcc91e50f49e1473c/readthedocs/core/views.py#L197-L274) with only minor changes needed to support the slightly different response sent by a GitLab web hook POST. POST body sent as a result of a push event is documented [here](https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/web_hooks/web_hooks.md).
2015-07-18T15:55:40
readthedocs/readthedocs.org
1,499
readthedocs__readthedocs.org-1499
[ "1463" ]
69bb655991bc954def743dc73ac0a806f0343fd8
diff --git a/readthedocs/api/base.py b/readthedocs/api/base.py --- a/readthedocs/api/base.py +++ b/readthedocs/api/base.py @@ -18,8 +18,7 @@ from builds.models import Build, Version from core.utils import trigger_build from projects.models import Project, ImportedFile -from projects.version_handling import highest_version -from projects.version_handling import parse_version_failsafe +from restapi.views.footer_views import get_version_compare_data from .utils import SearchMixin, PostAuthentication @@ -144,34 +143,16 @@ def get_object_list(self, request): self._meta.queryset = Version.objects.api(user=request.user, only_active=False) return super(VersionResource, self).get_object_list(request) - def version_compare(self, request, **kwargs): - project = get_object_or_404(Project, slug=kwargs['project_slug']) - highest_version_obj, highest_version_comparable = highest_version( - project.versions.filter(active=True)) - base = kwargs.get('base', None) - ret_val = { - 'project': highest_version_obj, - 'version': highest_version_comparable, - 'is_highest': True, - } - if highest_version_obj: - ret_val['url'] = highest_version_obj.get_absolute_url() - ret_val['slug'] = highest_version_obj.slug, + def version_compare(self, request, project_slug, base=None, **kwargs): + project = get_object_or_404(Project, slug=project_slug) if base and base != LATEST: try: - base_version_obj = project.versions.get(slug=base) - base_version_comparable = parse_version_failsafe( - base_version_obj.verbose_name) - if base_version_comparable: - # This is only place where is_highest can get set. All - # error cases will be set to True, for non- standard - # versions. - ret_val['is_highest'] = ( - base_version_comparable >= highest_version_comparable) - else: - ret_val['is_highest'] = True + base_version = project.versions.get(slug=base) except (Version.DoesNotExist, TypeError): - ret_val['is_highest'] = True + base_version = None + else: + base_version = None + ret_val = get_version_compare_data(project, base_version) return self.create_response(request, ret_val) def build_version(self, request, **kwargs): diff --git a/readthedocs/restapi/views/footer_views.py b/readthedocs/restapi/views/footer_views.py --- a/readthedocs/restapi/views/footer_views.py +++ b/readthedocs/restapi/views/footer_views.py @@ -7,9 +7,39 @@ from rest_framework.renderers import JSONPRenderer, JSONRenderer, BrowsableAPIRenderer from rest_framework.response import Response +from builds.constants import LATEST from builds.models import Version -from projects.models import Project from donate.models import SupporterPromo +from projects.models import Project +from projects.version_handling import highest_version +from projects.version_handling import parse_version_failsafe + + +def get_version_compare_data(project, base_version=None): + highest_version_obj, highest_version_comparable = highest_version( + project.versions.filter(active=True)) + ret_val = { + 'project': unicode(highest_version_obj), + 'version': unicode(highest_version_comparable), + 'is_highest': True, + } + if highest_version_obj: + ret_val['url'] = highest_version_obj.get_absolute_url() + ret_val['slug'] = highest_version_obj.slug, + if base_version and base_version.slug != LATEST: + try: + base_version_comparable = parse_version_failsafe( + base_version.verbose_name) + if base_version_comparable: + # This is only place where is_highest can get set. All error + # cases will be set to True, for non- standard versions. + ret_val['is_highest'] = ( + base_version_comparable >= highest_version_comparable) + else: + ret_val['is_highest'] = True + except (Version.DoesNotExist, TypeError): + ret_val['is_highest'] = True + return ret_val @decorators.api_view(['GET']) @@ -64,6 +94,8 @@ def footer_html(request): if not promo_obj: show_promo = False + version_compare_data = get_version_compare_data(project, version) + context = Context({ 'project': project, 'path': path, @@ -88,6 +120,7 @@ def footer_html(request): resp_data = { 'html': html, 'version_active': version.active, + 'version_compare': version_compare_data, 'version_supported': version.supported, 'promo': show_promo, }
diff --git a/readthedocs/rtd_tests/tests/test_api_version_compare.py b/readthedocs/rtd_tests/tests/test_api_version_compare.py new file mode 100644 --- /dev/null +++ b/readthedocs/rtd_tests/tests/test_api_version_compare.py @@ -0,0 +1,33 @@ +from django.test import TestCase + +from builds.constants import LATEST +from projects.models import Project +from restapi.views.footer_views import get_version_compare_data + + +class VersionCompareTests(TestCase): + fixtures = ['eric.json', 'test_data.json'] + + def test_not_highest(self): + project = Project.objects.get(slug='read-the-docs') + version = project.versions.get(slug='0.2.1') + + data = get_version_compare_data(project, version) + self.assertEqual(data['is_highest'], False) + + def test_latest_version_highest(self): + project = Project.objects.get(slug='read-the-docs') + + data = get_version_compare_data(project) + self.assertEqual(data['is_highest'], True) + + version = project.versions.get(slug=LATEST) + data = get_version_compare_data(project, version) + self.assertEqual(data['is_highest'], True) + + def test_real_highest(self): + project = Project.objects.get(slug='read-the-docs') + version = project.versions.get(slug='0.2.2') + + data = get_version_compare_data(project, version) + self.assertEqual(data['is_highest'], True) diff --git a/readthedocs/rtd_tests/tests/test_footer.py b/readthedocs/rtd_tests/tests/test_footer.py --- a/readthedocs/rtd_tests/tests/test_footer.py +++ b/readthedocs/rtd_tests/tests/test_footer.py @@ -1,4 +1,5 @@ import json +import mock from django.test import TestCase @@ -18,6 +19,7 @@ def test_footer(self): r = self.client.get('/api/v2/footer_html/?project=pip&version=latest&page=index', {}) resp = json.loads(r.content) self.assertEqual(resp['version_active'], True) + self.assertEqual(resp['version_compare']['is_highest'], True) self.assertEqual(resp['version_supported'], True) self.assertEqual(r.context['main_project'], self.pip) self.assertEqual(r.status_code, 200) @@ -29,6 +31,19 @@ def test_footer(self): self.assertEqual(resp['version_active'], False) self.assertEqual(r.status_code, 200) + def test_footer_uses_version_compare(self): + version_compare = 'restapi.views.footer_views.get_version_compare_data' + with mock.patch(version_compare) as get_version_compare_data: + get_version_compare_data.return_value = { + 'MOCKED': True + } + + r = self.client.get('/api/v2/footer_html/?project=pip&version=latest&page=index', {}) + self.assertEqual(r.status_code, 200) + + resp = json.loads(r.content) + self.assertEqual(resp['version_compare'], {'MOCKED': True}) + def test_pdf_build_mentioned_in_footer(self): with fake_paths_by_regex('\.pdf$'): response = self.client.get(
Add Version Compare information to the RTD Footer Response We want to unify the API calls for `/api/v1/<project>/highest/<version>` and `/api/v2/footer_html` in order to reduce the number of API calls.
@ericholscher I have a few questions regarding this task. 1. The version comparison call is part of API v1. Shall this be moved into API v2? Do we need to stay backwards compatible? 2. The API calls are made from the `readthedocs/core/static-src/core/js/readthedocs-doc-embed.js` file. I noticed that the API is also called from the `media/javascript/rtd.js` file. Is this file still relevant? We should just move the logic into the footer response. I don't believe we need to maintain backwards compat, I don't think. It might make sense to keep the logic seperate, and have an API endpoint for it, but to embed it in the footer response on doc page load to decrease server requests, but keep it available. I believe rtd.js is old -- likely around for docs that haven't been rebuilt in a long time. On Tue, Jul 21, 2015 at 6:41 AM, Gregor Müllegger [email protected] wrote: > @ericholscher https://github.com/ericholscher I have a few questions > regarding this task. > 1. The version comparison call is part of API v1. Shall this be moved > into API v2? Do we need to stay backwards compatible? > 2. The API calls are made from the > readthedocs/core/static-src/core/js/readthedocs-doc-embed.js file. I > noticed that the API is also called from the media/javascript/rtd.js > file. Is this file still relevant? > > — > Reply to this email directly or view it on GitHub > https://github.com/rtfd/readthedocs.org/issues/1463#issuecomment-123308650 > . ## Eric Holscher Maker of the internet residing in Portland, Oregon http://ericholscher.com > The API calls are made from the readthedocs/core/static-src/core/js/readthedocs-doc-embed.js file. I noticed that the API is also called from the media/javascript/rtd.js file. Is this file still relevant? @ericholscher What's your take on this? Sorry ignore my comment. Your take on the rtd.js was hidden in the github UI because it thought it was part of the quoted email text...
2015-07-30T10:18:12
readthedocs/readthedocs.org
1,503
readthedocs__readthedocs.org-1503
[ "1341" ]
fb1489eb1cbb18eb21c0a3f1832c9b4529cc0ae4
diff --git a/readthedocs/projects/forms.py b/readthedocs/projects/forms.py --- a/readthedocs/projects/forms.py +++ b/readthedocs/projects/forms.py @@ -14,6 +14,7 @@ from readthedocs.redirects.models import Redirect from readthedocs.projects import constants from readthedocs.projects.models import Project, EmailHook, WebHook +from readthedocs.privacy.loader import AdminPermission class ProjectForm(forms.ModelForm): @@ -309,7 +310,8 @@ class SubprojectForm(forms.Form): subproject = forms.CharField() def __init__(self, *args, **kwargs): - self.parent = kwargs.pop('parent', None) + self.user = kwargs.pop('user') + self.parent = kwargs.pop('parent') super(SubprojectForm, self).__init__(*args, **kwargs) def clean_subproject(self): @@ -318,11 +320,16 @@ def clean_subproject(self): if not subproject_qs.exists(): raise forms.ValidationError((_("Project %(name)s does not exist") % {'name': subproject_name})) - self.subproject = subproject_qs[0] - return subproject_name + subproject = subproject_qs.first() + if not AdminPermission.is_admin(self.user, subproject): + raise forms.ValidationError(_( + 'You need to be admin of {name} in order to add it as ' + 'a subproject.'.format(name=subproject_name))) + return subproject def save(self): - relationship = self.parent.add_subproject(self.subproject) + relationship = self.parent.add_subproject( + self.cleaned_data['subproject']) return relationship diff --git a/readthedocs/projects/views/private.py b/readthedocs/projects/views/private.py --- a/readthedocs/projects/views/private.py +++ b/readthedocs/projects/views/private.py @@ -400,13 +400,19 @@ def project_subprojects(request, project_slug): project = get_object_or_404(Project.objects.for_admin_user(request.user), slug=project_slug) - form = SubprojectForm(data=request.POST or None, parent=project) - - if request.method == 'POST' and form.is_valid(): - form.save() - project_dashboard = reverse( - 'projects_subprojects', args=[project.slug]) - return HttpResponseRedirect(project_dashboard) + form_kwargs = { + 'parent': project, + 'user': request.user, + } + if request.method == 'POST': + form = SubprojectForm(request.POST, **form_kwargs) + if form.is_valid(): + form.save() + project_dashboard = reverse( + 'projects_subprojects', args=[project.slug]) + return HttpResponseRedirect(project_dashboard) + else: + form = SubprojectForm(**form_kwargs) subprojects = project.subprojects.all() @@ -420,7 +426,7 @@ def project_subprojects(request, project_slug): @login_required def project_subprojects_delete(request, project_slug, child_slug): parent = get_object_or_404(Project.objects.for_admin_user(request.user), slug=project_slug) - child = get_object_or_404(Project.objects.for_admin_user(request.user), slug=child_slug) + child = get_object_or_404(Project.objects.all(), slug=child_slug) parent.remove_subproject(child) return HttpResponseRedirect(reverse('projects_subprojects', args=[parent.slug]))
diff --git a/readthedocs/rtd_tests/tests/test_subproject.py b/readthedocs/rtd_tests/tests/test_subproject.py new file mode 100644 --- /dev/null +++ b/readthedocs/rtd_tests/tests/test_subproject.py @@ -0,0 +1,56 @@ +from django.contrib.auth.models import User +from django.test import TestCase +from django_dynamic_fixture import get + +from readthedocs.projects.forms import SubprojectForm +from readthedocs.projects.models import Project + + +class SubprojectFormTests(TestCase): + def test_name_validation(self): + user = get(User) + project = get(Project, slug='mainproject') + + form = SubprojectForm({}, + parent=project, user=user) + form.full_clean() + self.assertTrue('subproject' in form.errors) + + form = SubprojectForm({'name': 'not-existent'}, + parent=project, user=user) + form.full_clean() + self.assertTrue('subproject' in form.errors) + + def test_adding_subproject_fails_when_user_is_not_admin(self): + # Make sure that a user cannot add a subproject that he is not the + # admin of. + + user = get(User) + project = get(Project, slug='mainproject') + project.users.add(user) + subproject = get(Project, slug='subproject') + + form = SubprojectForm({'subproject': subproject.slug}, + parent=project, user=user) + # Fails because user does not own subproject. + form.full_clean() + self.assertTrue('subproject' in form.errors) + + def test_admin_of_subproject_can_add_it(self): + user = get(User) + project = get(Project, slug='mainproject') + project.users.add(user) + subproject = get(Project, slug='subproject') + subproject.users.add(user) + + # Works now as user is admin of subproject. + form = SubprojectForm({'subproject': subproject.slug}, + parent=project, user=user) + # Fails because user does not own subproject. + form.full_clean() + self.assertTrue(form.is_valid()) + form.save() + + self.assertEqual( + [r.child for r in project.subprojects.all()], + [subproject]) diff --git a/readthedocs/rtd_tests/tests/test_views.py b/readthedocs/rtd_tests/tests/test_views.py --- a/readthedocs/rtd_tests/tests/test_views.py +++ b/readthedocs/rtd_tests/tests/test_views.py @@ -2,10 +2,13 @@ from django.core.urlresolvers import reverse from django.test import TestCase from django.utils.six.moves.urllib.parse import urlsplit +from django_dynamic_fixture import get +from django_dynamic_fixture import new from readthedocs.builds.constants import LATEST from readthedocs.projects.models import Project from readthedocs.projects.forms import UpdateProjectForm +from readthedocs.privacy.loader import AdminPermission class Testmaker(TestCase): @@ -168,3 +171,38 @@ def test_project_redirects(self): def test_project_redirects_delete(self): response = self.client.get('/dashboard/pip/redirects/delete/') self.assertRedirectToLogin(response) + + +class SubprojectViewTests(TestCase): + def setUp(self): + self.user = new(User, username='test') + self.user.set_password('test') + self.user.save() + + self.project = get(Project, slug='my-mainproject') + self.subproject = get(Project, slug='my-subproject') + self.project.add_subproject(self.subproject) + + self.client.login(username='test', password='test') + + def test_deny_delete_for_non_project_admins(self): + response = self.client.get('/dashboard/my-mainproject/subprojects/delete/my-subproject/') + self.assertEqual(response.status_code, 404) + + self.assertTrue(self.subproject in [r.child for r in self.project.subprojects.all()]) + + def test_admins_can_delete_subprojects(self): + self.project.users.add(self.user) + self.subproject.users.add(self.user) + + response = self.client.get('/dashboard/my-mainproject/subprojects/delete/my-subproject/') + self.assertEqual(response.status_code, 302) + self.assertTrue(self.subproject not in [r.child for r in self.project.subprojects.all()]) + + def test_project_admins_can_delete_subprojects_that_they_are_not_admin_of(self): + self.project.users.add(self.user) + self.assertFalse(AdminPermission.is_admin(self.user, self.subproject)) + + response = self.client.get('/dashboard/my-mainproject/subprojects/delete/my-subproject/') + self.assertEqual(response.status_code, 302) + self.assertTrue(self.subproject not in [r.child for r in self.project.subprojects.all()])
Cannot delete subproject Hi, I have added a subproject to test, what this is about. Now I can't delete it anymore. This url: `https://readthedocs.org/dashboard/<prj>/subprojects/delete/<subprj>/` does not exist.
That seems odd. Which project is this on? Could you please give the link that you are actually trying to click and get a 404 back for? This is the link that gives me a 404: https://readthedocs.org/dashboard/fvf/subprojects/delete/manual/ Thanks, I will have a look at this.
2015-07-30T16:51:18
readthedocs/readthedocs.org
1,507
readthedocs__readthedocs.org-1507
[ "1463" ]
44164796bd904df45321e81a997d895b19ba293e
diff --git a/readthedocs/api/base.py b/readthedocs/api/base.py --- a/readthedocs/api/base.py +++ b/readthedocs/api/base.py @@ -18,8 +18,7 @@ from readthedocs.builds.models import Build, Version from readthedocs.core.utils import trigger_build from readthedocs.projects.models import Project, ImportedFile -from readthedocs.projects.version_handling import highest_version -from readthedocs.projects.version_handling import parse_version_failsafe +from readthedocs.restapi.views.footer_views import get_version_compare_data from .utils import SearchMixin, PostAuthentication @@ -144,34 +143,16 @@ def get_object_list(self, request): self._meta.queryset = Version.objects.api(user=request.user, only_active=False) return super(VersionResource, self).get_object_list(request) - def version_compare(self, request, **kwargs): - project = get_object_or_404(Project, slug=kwargs['project_slug']) - highest_version_obj, highest_version_comparable = highest_version( - project.versions.filter(active=True)) - base = kwargs.get('base', None) - ret_val = { - 'project': highest_version_obj, - 'version': highest_version_comparable, - 'is_highest': True, - } - if highest_version_obj: - ret_val['url'] = highest_version_obj.get_absolute_url() - ret_val['slug'] = highest_version_obj.slug, + def version_compare(self, request, project_slug, base=None, **kwargs): + project = get_object_or_404(Project, slug=project_slug) if base and base != LATEST: try: - base_version_obj = project.versions.get(slug=base) - base_version_comparable = parse_version_failsafe( - base_version_obj.verbose_name) - if base_version_comparable: - # This is only place where is_highest can get set. All - # error cases will be set to True, for non- standard - # versions. - ret_val['is_highest'] = ( - base_version_comparable >= highest_version_comparable) - else: - ret_val['is_highest'] = True + base_version = project.versions.get(slug=base) except (Version.DoesNotExist, TypeError): - ret_val['is_highest'] = True + base_version = None + else: + base_version = None + ret_val = get_version_compare_data(project, base_version) return self.create_response(request, ret_val) def build_version(self, request, **kwargs): diff --git a/readthedocs/restapi/views/footer_views.py b/readthedocs/restapi/views/footer_views.py --- a/readthedocs/restapi/views/footer_views.py +++ b/readthedocs/restapi/views/footer_views.py @@ -7,9 +7,39 @@ from rest_framework.renderers import JSONPRenderer, JSONRenderer, BrowsableAPIRenderer from rest_framework.response import Response +from readthedocs.builds.constants import LATEST from readthedocs.builds.models import Version -from readthedocs.projects.models import Project from readthedocs.donate.models import SupporterPromo +from readthedocs.projects.models import Project +from readthedocs.projects.version_handling import highest_version +from readthedocs.projects.version_handling import parse_version_failsafe + + +def get_version_compare_data(project, base_version=None): + highest_version_obj, highest_version_comparable = highest_version( + project.versions.filter(active=True)) + ret_val = { + 'project': unicode(highest_version_obj), + 'version': unicode(highest_version_comparable), + 'is_highest': True, + } + if highest_version_obj: + ret_val['url'] = highest_version_obj.get_absolute_url() + ret_val['slug'] = highest_version_obj.slug, + if base_version and base_version.slug != LATEST: + try: + base_version_comparable = parse_version_failsafe( + base_version.verbose_name) + if base_version_comparable: + # This is only place where is_highest can get set. All error + # cases will be set to True, for non- standard versions. + ret_val['is_highest'] = ( + base_version_comparable >= highest_version_comparable) + else: + ret_val['is_highest'] = True + except (Version.DoesNotExist, TypeError): + ret_val['is_highest'] = True + return ret_val @decorators.api_view(['GET']) @@ -64,6 +94,8 @@ def footer_html(request): if not promo_obj: show_promo = False + version_compare_data = get_version_compare_data(project, version) + context = Context({ 'project': project, 'path': path, @@ -88,6 +120,7 @@ def footer_html(request): resp_data = { 'html': html, 'version_active': version.active, + 'version_compare': version_compare_data, 'version_supported': version.supported, 'promo': show_promo, }
diff --git a/readthedocs/rtd_tests/tests/test_api_version_compare.py b/readthedocs/rtd_tests/tests/test_api_version_compare.py new file mode 100644 --- /dev/null +++ b/readthedocs/rtd_tests/tests/test_api_version_compare.py @@ -0,0 +1,33 @@ +from django.test import TestCase + +from readthedocs.builds.constants import LATEST +from readthedocs.projects.models import Project +from readthedocs.restapi.views.footer_views import get_version_compare_data + + +class VersionCompareTests(TestCase): + fixtures = ['eric.json', 'test_data.json'] + + def test_not_highest(self): + project = Project.objects.get(slug='read-the-docs') + version = project.versions.get(slug='0.2.1') + + data = get_version_compare_data(project, version) + self.assertEqual(data['is_highest'], False) + + def test_latest_version_highest(self): + project = Project.objects.get(slug='read-the-docs') + + data = get_version_compare_data(project) + self.assertEqual(data['is_highest'], True) + + version = project.versions.get(slug=LATEST) + data = get_version_compare_data(project, version) + self.assertEqual(data['is_highest'], True) + + def test_real_highest(self): + project = Project.objects.get(slug='read-the-docs') + version = project.versions.get(slug='0.2.2') + + data = get_version_compare_data(project, version) + self.assertEqual(data['is_highest'], True) diff --git a/readthedocs/rtd_tests/tests/test_footer.py b/readthedocs/rtd_tests/tests/test_footer.py --- a/readthedocs/rtd_tests/tests/test_footer.py +++ b/readthedocs/rtd_tests/tests/test_footer.py @@ -1,4 +1,5 @@ import json +import mock from django.test import TestCase @@ -18,6 +19,7 @@ def test_footer(self): r = self.client.get('/api/v2/footer_html/?project=pip&version=latest&page=index', {}) resp = json.loads(r.content) self.assertEqual(resp['version_active'], True) + self.assertEqual(resp['version_compare']['is_highest'], True) self.assertEqual(resp['version_supported'], True) self.assertEqual(r.context['main_project'], self.pip) self.assertEqual(r.status_code, 200) @@ -29,6 +31,19 @@ def test_footer(self): self.assertEqual(resp['version_active'], False) self.assertEqual(r.status_code, 200) + def test_footer_uses_version_compare(self): + version_compare = 'readthedocs.restapi.views.footer_views.get_version_compare_data' + with mock.patch(version_compare) as get_version_compare_data: + get_version_compare_data.return_value = { + 'MOCKED': True + } + + r = self.client.get('/api/v2/footer_html/?project=pip&version=latest&page=index', {}) + self.assertEqual(r.status_code, 200) + + resp = json.loads(r.content) + self.assertEqual(resp['version_compare'], {'MOCKED': True}) + def test_pdf_build_mentioned_in_footer(self): with fake_paths_by_regex('\.pdf$'): response = self.client.get(
Add Version Compare information to the RTD Footer Response We want to unify the API calls for `/api/v1/<project>/highest/<version>` and `/api/v2/footer_html` in order to reduce the number of API calls.
@ericholscher I have a few questions regarding this task. 1. The version comparison call is part of API v1. Shall this be moved into API v2? Do we need to stay backwards compatible? 2. The API calls are made from the `readthedocs/core/static-src/core/js/readthedocs-doc-embed.js` file. I noticed that the API is also called from the `media/javascript/rtd.js` file. Is this file still relevant? We should just move the logic into the footer response. I don't believe we need to maintain backwards compat, I don't think. It might make sense to keep the logic seperate, and have an API endpoint for it, but to embed it in the footer response on doc page load to decrease server requests, but keep it available. I believe rtd.js is old -- likely around for docs that haven't been rebuilt in a long time. On Tue, Jul 21, 2015 at 6:41 AM, Gregor Müllegger [email protected] wrote: > @ericholscher https://github.com/ericholscher I have a few questions > regarding this task. > 1. The version comparison call is part of API v1. Shall this be moved > into API v2? Do we need to stay backwards compatible? > 2. The API calls are made from the > readthedocs/core/static-src/core/js/readthedocs-doc-embed.js file. I > noticed that the API is also called from the media/javascript/rtd.js > file. Is this file still relevant? > > — > Reply to this email directly or view it on GitHub > https://github.com/rtfd/readthedocs.org/issues/1463#issuecomment-123308650 > . ## Eric Holscher Maker of the internet residing in Portland, Oregon http://ericholscher.com > The API calls are made from the readthedocs/core/static-src/core/js/readthedocs-doc-embed.js file. I noticed that the API is also called from the media/javascript/rtd.js file. Is this file still relevant? @ericholscher What's your take on this? Sorry ignore my comment. Your take on the rtd.js was hidden in the github UI because it thought it was part of the quoted email text...
2015-07-30T22:22:42
readthedocs/readthedocs.org
1,529
readthedocs__readthedocs.org-1529
[ "1515" ]
1f2c785992670a6c69a1948aeeaae156e3149e35
diff --git a/readthedocs/core/management/commands/pull.py b/readthedocs/core/management/commands/pull.py --- a/readthedocs/core/management/commands/pull.py +++ b/readthedocs/core/management/commands/pull.py @@ -6,7 +6,6 @@ from readthedocs.builds.constants import LATEST from readthedocs.projects import tasks, utils -import redis log = logging.getLogger(__name__) diff --git a/readthedocs/core/views.py b/readthedocs/core/views.py --- a/readthedocs/core/views.py +++ b/readthedocs/core/views.py @@ -16,7 +16,6 @@ from haystack.query import EmptySearchQuerySet from haystack.query import SearchQuerySet -from celery.task.control import inspect # noqa: pylint false positive import stripe from readthedocs.builds.models import Build @@ -35,7 +34,6 @@ import mimetypes import os import logging -import redis import re log = logging.getLogger(__name__) @@ -77,42 +75,6 @@ def random_page(request, project_slug=None): return HttpResponseRedirect(url) -def queue_depth(request): - r = redis.Redis(**settings.REDIS) - return HttpResponse(r.llen('celery')) - - -def queue_info(request): - i = inspect() - active_pks = [] - reserved_pks = [] - resp = "" - - active = i.active() - if active: - try: - for obj in active['build']: - kwargs = eval(obj['kwargs']) - active_pks.append(str(kwargs['pk'])) - active_resp = "Active: %s " % " ".join(active_pks) - resp += active_resp - except Exception, e: - resp += str(e) - - reserved = i.reserved() - if reserved: - try: - for obj in reserved['build']: - kwrags = eval(obj['kwargs']) - reserved_pks.append(str(kwargs['pk'])) - reserved_resp = " | Reserved: %s" % " ".join(reserved_pks) - resp += reserved_resp - except Exception, e: - resp += str(e) - - return HttpResponse(resp) - - def live_builds(request): builds = Build.objects.filter(state='building')[:5] websocket_host = getattr(settings, 'WEBSOCKET_HOST', 'localhost:8088') diff --git a/readthedocs/urls.py b/readthedocs/urls.py --- a/readthedocs/urls.py +++ b/readthedocs/urls.py @@ -111,8 +111,6 @@ name='random_page'), url(r'^random/$', 'readthedocs.core.views.random_page', name='random_page'), url(r'^sustainability/', include('readthedocs.donate.urls')), - url(r'^depth/$', 'readthedocs.core.views.queue_depth', name='queue_depth'), - url(r'^queue_info/$', 'readthedocs.core.views.queue_info', name='queue_info'), url(r'^live/$', 'readthedocs.core.views.live_builds', name='live_builds'), url(r'^500/$', 'readthedocs.core.views.divide_by_zero', name='divide_by_zero'), url(r'^filter/version/$',
Bug in core.views.queue_info, is it used anymore? The code in `core.views.queue_info` contains this: ``` python for obj in reserved['build']: kwrags = eval(obj['kwargs']) reserved_pks.append(str(kwargs['pk'])) ``` So it has a typo in `kwrags`. That means the third line of the example won't pick up the correct variable. It might still succeed without a `NameError` as it might be already initialized by another for loop above in the same function. See https://github.com/rtfd/readthedocs.org/blob/291d7d61e626c1dfb998d9e5d4e5b734a44a7024/readthedocs/core/views.py#L102 I didn't fix it straight away as it seems that the `queue_info` URL is not used anywhere in the project? Do we still have a use for it? ``` $ grep -r queue_info . ./readthedocs/core/views.py:def queue_info(request): ./readthedocs/urls.py: url(r'^queue_info/$', 'readthedocs.core.views.queue_info', name='queue_info'), ```
It was mainly used for debugging celery, but we now have real monitoring for it, so it can likely be deleted. On Fri, Jul 31, 2015 at 4:26 AM, Gregor Müllegger [email protected] wrote: > The code in core.views.queue_info contains this: > > ``` > for obj in reserved['build']: > kwrags = eval(obj['kwargs']) > reserved_pks.append(str(kwargs['pk'])) > ``` > > So it has a typo in kwrags. That means the third line of the example > won't pick up the correct variable. It might still succeed without a > NameError as it might be already initialized by another for loop above in > the same function. > > See > https://github.com/rtfd/readthedocs.org/blob/291d7d61e626c1dfb998d9e5d4e5b734a44a7024/readthedocs/core/views.py#L102 > > I didn't fix it straight away as it seems that the queue_info URL is not > used anywhere in the project? Do we still have a use for it? > > $ grep -r queue_info . > ./readthedocs/core/views.py:def queue_info(request): > ./readthedocs/urls.py: url(r'^queue_info/$', 'readthedocs.core.views.queue_info', name='queue_info'), > > — > Reply to this email directly or view it on GitHub > https://github.com/rtfd/readthedocs.org/issues/1515. ## Eric Holscher Maker of the internet residing in Portland, Oregon http://ericholscher.com
2015-08-03T09:10:58
readthedocs/readthedocs.org
1,530
readthedocs__readthedocs.org-1530
[ "1520" ]
1f2c785992670a6c69a1948aeeaae156e3149e35
diff --git a/readthedocs/settings/postgres.py b/readthedocs/settings/postgres.py --- a/readthedocs/settings/postgres.py +++ b/readthedocs/settings/postgres.py @@ -69,6 +69,9 @@ 'github': {'SCOPE': ['user:email', 'read:org', 'admin:repo_hook', 'repo:status']} } +# allauth settings +ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' + if not os.environ.get('DJANGO_SETTINGS_SKIP_LOCAL', False): try: from local_settings import * # noqa
Social Network Login Failure When clicking on connect GitHub on the [social accounts page](https://readthedocs.org/accounts/social/connections/?) I get a message: > An error occurred while attempting to login via your social network account. There's a `?` in the url. Could that be a hint? Is it missing some request arguments? If I omit it, the bug persists. Cheers!
I am having the same issue. I do have 2 Factor Authentication enabled on GH, so maybe it's the response from that? It's not that. I disabled 2 Factor Authentication and just tried again and it still failed. As a workaround, I managed to manually import a GitHub repository by entering the repo url and adding Read The Docs as a service to notify of new commits in the repo's settings on GitHub. Explained [here](https://read-the-docs.readthedocs.org/en/latest/webhooks.html). This is the Error in the URL: ``` The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application ``` If I attempt to link to github from `https://www.readthedocs.org` the redirect with the error sends me back to `https://readthedocs.org` From the OAuth Flow it looks like: ``` &redirect_uri=http%3A%2F%2Freadthedocs.org%2Faccounts%2Fgithub%2Flogin%2Fcallback%2F ``` sans www is indeed the redirect_uri so the next question is, how is the app registered on github? The plot thickens! So using Charles, I got the GH Auth URL and indeed, the redirect_uri is the issue. It's set to `http://` which fails, but if I get a clean auth url and set the redirect_uri to be `https://` I get the GH auth screen for the RTD app. Now when I get redirected, I still get an error, but 1 problem at a time. So I assume some ENV var for the app is probably set `http` and it should be set to `https` More info.. It looks like it has to do with how `allauth` is doing it's job: https://github.com/pennersr/django-allauth/blob/8efc7e5ebb3326d467248de3350853407e3fc73b/allauth/account/app_settings.py#L42-L44 ``` python @property def DEFAULT_HTTP_PROTOCOL(self): return self._setting("DEFAULT_HTTP_PROTOCOL", "http") ``` where `self._setting` is: ``` python def _setting(self, name, dflt): from django.conf import settings getter = getattr(settings, 'ALLAUTH_SETTING_GETTER', lambda name, dflt: getattr(settings, name, dflt)) return getter(self.prefix + name, dflt) ``` So my guess now is all the production app at `https://readthedocs.org` has to do to fix this issue is to set `DEFAULT_HTTP_PROTOCOL` in the django app's settings.
2015-08-03T09:52:06
readthedocs/readthedocs.org
1,548
readthedocs__readthedocs.org-1548
[ "77" ]
53e29499cdf95548e84fd50e8c73bf007a71c8d2
diff --git a/readthedocs/core/hacks.py b/readthedocs/core/hacks.py deleted file mode 100644 --- a/readthedocs/core/hacks.py +++ /dev/null @@ -1,40 +0,0 @@ -import imp -import sys - - -class ErrorlessImport(object): - def find_module(self, name, path): - try: - return imp.find_module(name, path) - except ImportError: - # raise - return FreeLoader() - - -class Mock(object): - def __repr__(self): - return "<Silly Human, I'm not real>" - - def __eq__(self, b): - return True - - def __getattr__(self, *args, **kwargs): - return Mock() - - def __call__(self, *args, **kwargs): - return Mock() - - -class FreeLoader(object): - def load_module(self, fullname): - return Mock() - - -def patch_meta_path(): - FreeLoader._class = ErrorlessImport() - sys.meta_path += [FreeLoader._class] - - -def unpatch_meta_path(): - sys.meta_path.remove(FreeLoader._class) - # sys.meta_path = []
diff --git a/readthedocs/rtd_tests/tests/test_hacks.py b/readthedocs/rtd_tests/tests/test_hacks.py deleted file mode 100644 --- a/readthedocs/rtd_tests/tests/test_hacks.py +++ /dev/null @@ -1,20 +0,0 @@ -from django.test import TestCase -from readthedocs.core import hacks - - -class TestHacks(TestCase): - fixtures = ['eric.json', 'test_data.json'] - - def setUp(self): - hacks.patch_meta_path() - - def tearDown(self): - hacks.unpatch_meta_path() - - def test_hack_failed_import(self): - import boogy - self.assertTrue(str(boogy), "<Silly Human, I'm not real>") - - #def test_hack_correct_import(self): - #import itertools - #self.assertFalse(str(itertools), "<Silly Human, I'm not real>")
Add import error handling By registering an import hook we can trick projects whose modules are not able to be build and installed on the server that they exist. See http://www.python.org/dev/peps/pep-0302/
Here's a spike for the object we could import if the required one is missing, https://gist.github.com/1039121 I wonder if it would be easier if we just did this for known... rabbitholes to install like mysql - not for everything. Its certainly a good idea to start with that as a known use case, but we're going to need to either register those import hooks or override `__import__`. For what is worth, what I added to sphinx's conf.py file with my project to mock the modules that were causing problems is as follows: https://gist.github.com/1167446 Note: I had to mock argparse also since readthedocs seems to use python2.6 at the moment. @jcollado this works for me. I'll try it with my original issue, and if it works there, I'll try to document it and then hopefully we can close it. for posterity: http://docs.python.org/library/sys.html#sys.meta_path bam! Looks like this is harder than it appears, so I think documenting it in the FAQ is probably the right solution to this for now.
2015-08-06T14:26:42
readthedocs/readthedocs.org
1,597
readthedocs__readthedocs.org-1597
[ "1550" ]
1c1b2ab3adcdf37e48ffaf7130a3d4681ce063f9
diff --git a/readthedocs/doc_builder/backends/sphinx.py b/readthedocs/doc_builder/backends/sphinx.py --- a/readthedocs/doc_builder/backends/sphinx.py +++ b/readthedocs/doc_builder/backends/sphinx.py @@ -43,7 +43,7 @@ def __init__(self, *args, **kwargs): docs_dir = self.docs_dir() self.old_artifact_path = os.path.join(docs_dir, self.sphinx_build_dir) - def _write_config(self): + def _write_config(self, master_doc='index'): """ Create ``conf.py`` if it doesn't exist. """ @@ -52,6 +52,7 @@ def _write_config(self): {'project': self.project, 'version': self.version, 'template_dir': TEMPLATE_DIR, + 'master_doc': master_doc, }) conf_file = os.path.join(docs_dir, 'conf.py') safe_write(conf_file, conf_template) @@ -64,8 +65,8 @@ def append_conf(self, **kwargs): try: conf_py_path = self.version.get_conf_py_path() except ProjectImportError: - self._write_config() - self.create_index(extension='rst') + master_doc = self.create_index(extension='rst') + self._write_config(master_doc=master_doc) project = self.project # Open file for appending. diff --git a/readthedocs/doc_builder/base.py b/readthedocs/doc_builder/base.py --- a/readthedocs/doc_builder/base.py +++ b/readthedocs/doc_builder/base.py @@ -98,8 +98,7 @@ def create_index(self, extension='md', **kwargs): if not os.path.exists(index_filename): readme_filename = os.path.join(docs_dir, 'README.{ext}'.format(ext=extension)) if os.path.exists(readme_filename): - os.system('mv {readme} {index}'.format(index=index_filename, - readme=readme_filename)) + return 'README' else: index_file = open(index_filename, 'w+') index_text = """ @@ -116,6 +115,7 @@ def create_index(self, extension='md', **kwargs): index_file.write(index_text.format(dir=docs_dir, ext=extension)) index_file.close() + return 'index' def run(self, *args, **kwargs): '''Proxy run to build environment'''
wrong link for "Edit on GitHub" of README.rst (if index.rst does not exist) Currently, `doc_builder/base.py` will rename `README.rst` to `index.rst` if repo does not have `index.rst`. And this make the generated index.html finding `index.rst` as source. Then, it cause 404 when user click "Edit on GitHub". (repo only have `README.rst`)
Example: http://python-best-practices.readthedocs.org/en/latest/ I believe our servers will now serve README.html as an index file, so we can probably stop transforming the files and be good. @ericholscher I tried this in #1585, but it seems to be more complicated. See there for comments.
2015-08-26T08:36:52
readthedocs/readthedocs.org
1,629
readthedocs__readthedocs.org-1629
[ "1553" ]
caea59ba7da8bf7b6176f4eb2c9b0d423c83a7a7
diff --git a/readthedocs/builds/models.py b/readthedocs/builds/models.py --- a/readthedocs/builds/models.py +++ b/readthedocs/builds/models.py @@ -184,10 +184,10 @@ def get_downloads(self, pretty=False): return data def get_conf_py_path(self): - conf_py_path = self.project.conf_file(self.slug) - conf_py_path = conf_py_path.replace( - self.project.checkout_path(self.slug), '') - return conf_py_path.replace('conf.py', '') + 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`''' diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -597,7 +597,7 @@ def conf_file(self, version=LATEST): def conf_dir(self, version=LATEST): conf_file = self.conf_file(version) if conf_file: - return conf_file.replace('/conf.py', '') + return os.path.dirname(conf_file) @property def is_type_sphinx(self):
Uninformative error when branch name contains a dot We were just experimenting with some docs stuff, and @minrk created a branch name with a dot (`.`) in it. Builds on this branch all failed, and the only error message in the logs was "top level build failure". It took us a while to work out that the branch name was the problem. I don't think it's especially important to allow branch names with dots, but it would be nice to at least get an error that pointed us to the branch name.
Agreed, this could be an edge case bug that wasn't covered with some changes to branch name slugging. Hm, I tried locally with the pypy project and built their `release-2.6.x` branch which worked. @takluyver could you provide us with the branch you have problems with? I think it was a docs project @minrk had set up with his fork of the ipython/ipython GH repo to experiment. He might have more details. The branch name was 'conf.py-hacks' Pushing the same commit to a new branch 'target' resulted in a successful build.
2015-09-07T07:01:16
readthedocs/readthedocs.org
1,630
readthedocs__readthedocs.org-1630
[ "1605" ]
caea59ba7da8bf7b6176f4eb2c9b0d423c83a7a7
diff --git a/readthedocs/projects/views/public.py b/readthedocs/projects/views/public.py --- a/readthedocs/projects/views/public.py +++ b/readthedocs/projects/views/public.py @@ -159,23 +159,12 @@ def project_downloads(request, project_slug): if data: version_data[version] = data - # in case the MEDIA_URL is a protocol relative URL we just assume - # we want http as the protcol, so that Dash is able to handle the URL - if settings.MEDIA_URL.startswith('//'): - media_url_prefix = u'http:' - # but in case we're in debug mode and the MEDIA_URL is just a path - # we prefix it with a hardcoded host name and protocol - elif settings.MEDIA_URL.startswith('/') and settings.DEBUG: - media_url_prefix = u'http://%s' % request.get_host() - else: - media_url_prefix = '' return render_to_response( 'projects/project_downloads.html', { 'project': project, 'version_data': version_data, 'versions': versions, - 'media_url_prefix': media_url_prefix, }, context_instance=RequestContext(request), )
Remove unused variable media_url_prefix This code appears to no longer be in use. If you look at the template being rendered, `media_url_prefix` is never used. https://github.com/rtfd/readthedocs.org/commit/35a942b71c047c2518f96bea9a2f9bdc0aa921d6#diff-4fcca638684a1c1611b72a6dd6f1119aR34
2015-09-07T08:09:22
readthedocs/readthedocs.org
1,634
readthedocs__readthedocs.org-1634
[ "1480" ]
bc1decf4524c8a876c344d08d2da42aeeea19c72
diff --git a/readthedocs/doc_builder/backends/mkdocs.py b/readthedocs/doc_builder/backends/mkdocs.py --- a/readthedocs/doc_builder/backends/mkdocs.py +++ b/readthedocs/doc_builder/backends/mkdocs.py @@ -122,7 +122,10 @@ def append_conf(self, **kwargs): data_file = open(os.path.join(self.root_path, docs_dir, 'readthedocs-data.js'), 'w+') data_file.write(data_string) - data_file.write('\nREADTHEDOCS_DATA["page"] = mkdocs_page_name') + data_file.write(''' +READTHEDOCS_DATA["page"] = mkdocs_page_input_path.substr( + 0, mkdocs_page_input_path.lastIndexOf(READTHEDOCS_DATA.source_suffix)); +''') data_file.close() include_ctx = { diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -101,7 +101,7 @@ def install_core_requirements(self): 'Pygments==2.0.2', 'setuptools==18.6.1', 'docutils==0.12', - 'mkdocs==0.14.0', + 'mkdocs==0.15.0', 'mock==1.0.1', 'pillow==2.6.1', 'readthedocs-sphinx-ext==0.5.4', @@ -210,7 +210,7 @@ def install_core_requirements(self): # Install pip-only things. pip_requirements = [ - 'mkdocs==0.14.0', + 'mkdocs==0.15.0', 'readthedocs-sphinx-ext==0.5.4', 'commonmark==0.5.4', 'recommonmark==0.1.1',
Documentation version selection broken with Mkdocs If we switch versions from the options to release-3.7.0-1 on http://gluster.readthedocs.org/en/latest/ the resultant URL gets appended with "None" as in http://gluster.readthedocs.org/en/release-3.7.0-1/None/ also from any page, we cannot view the different versions of the documents, what I observed is the URL fired is mis matching the directory. ![image](https://cloud.githubusercontent.com/assets/10970993/8822127/d4c729ac-3080-11e5-9b3c-bbd2d1c36148.png)
For some reason it is adding a None to the end of the url. I am not sure why. I guess there is an issue getting the current path? Yeah, so this line isn't working for some reason: https://github.com/mkdocs/mkdocs/blob/master/mkdocs/themes/readthedocs/base.html#L29 and actually, page title isn't the right thing to put there. We should be putting the URL. You can see it being used incorrectly when you change the version here: http://gluster.readthedocs.org/en/latest/Quick-Start-Guide/Terminologies/ I'm getting the same behavior on this site: http://vic.readthedocs.org/en/master/. All the links under `Versions` and `On GitHub` send you to a url with the word "None" at the end. @d0ugal I tried using https://github.com/mkdocs/mkdocs/commit/74031a084d776f45ad43568e334da2b89133986b of mkdocs, but it still appended `None` on the version select links. Is there anything that we need to adjust on the RTD end? @gregmuellegger Yeah, I think so. I just made the data available, I don't really know how it works on your end, but it looked like you were using the Title incorrectly as the URL so I added that. I was planning to come and figure it out, but hadn't found the time yet :) I tried to install the mkdocs master in the venv that is used for the rtd build, but the change didn't pick up. The base.html in the filesystem contains the change ... but the build doesn't seem to use it. @d0ugal could there be any other path in RTD that is loading the mkdocs theme templates from except from the mkdocs package in the venv? @d0ugal and @gregmuellegger - Can either of you give us an update on where this issue is at? We have live docs on RTD that are not working because of this bug. If there is something I can do to help move this forward, let me know.
2015-09-07T17:23:42
readthedocs/readthedocs.org
1,645
readthedocs__readthedocs.org-1645
[ "1501" ]
b2b6d0308bb5e5f2ed6c7afa6733b2fe44836e72
diff --git a/fabfile.py b/fabfile.py --- a/fabfile.py +++ b/fabfile.py @@ -6,20 +6,6 @@ fabfile_dir = os.path.dirname(__file__) -def update_theme(): - theme_dir = os.path.join(fabfile_dir, 'readthedocs', 'templates', 'sphinx') - if not os.path.exists('/tmp/sphinx_rtd_theme'): - local('git clone https://github.com/snide/sphinx_rtd_theme.git /tmp/sphinx_rtd_theme') - with lcd('/tmp/sphinx_rtd_theme'): - local('git remote update') - local('git reset --hard origin/master ') - local('cp -r /tmp/sphinx_rtd_theme/sphinx_rtd_theme %s' % theme_dir) - local('cp -r /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/fonts/ %s' % os.path.join(fabfile_dir, 'media', 'font')) - local('cp /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/css/badge_only.css %s' % os.path.join(fabfile_dir, 'media', 'css')) - local('cp /tmp/sphinx_rtd_theme/sphinx_rtd_theme/static/css/theme.css %s' % - os.path.join(fabfile_dir, 'media', 'css', 'sphinx_rtd_theme.css')) - - def i18n(): with lcd('readthedocs'): local('rm -rf rtd_tests/tests/builds/') diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -252,7 +252,8 @@ def setup_environment(self): 'mock==1.0.1', 'pillow==2.6.1', 'readthedocs-sphinx-ext==0.5.4', - 'sphinx-rtd-theme==0.1.8', + 'git+http://github.com/snide/sphinx-rtd-theme@js-refactor#egg=sphinx-rtd-theme', + # 'sphinx-rtd-theme==0.1.8', 'alabaster>=0.7,<0.8,!=0.7.5', 'recommonmark==0.1.1', ] diff --git a/readthedocs/templates/sphinx/sphinx_rtd_theme/__init__.py b/readthedocs/templates/sphinx/sphinx_rtd_theme/__init__.py deleted file mode 100644 --- a/readthedocs/templates/sphinx/sphinx_rtd_theme/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -"""Sphinx ReadTheDocs theme. - -From https://github.com/ryan-roemer/sphinx-bootstrap-theme. - -""" -import os - -VERSION = (0, 1, 8) - -__version__ = ".".join(str(v) for v in VERSION) -__version_full__ = __version__ - - -def get_html_theme_path(): - """Return list of HTML theme paths.""" - cur_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) - return cur_dir
Use sphinx_rtd_theme directly instead of vendoring it Are there any reasons why the sphinx rtd theme is copied into the RTD code base instead of referenced as dependency? There were bugs like #1497 that would not have been raised if the theme would have been up to date.
ha, read my mind :) I have a refactor that i'd like in v0.1.9 of the theme which will allow us to use it as a bower dependency @agjohnson Whats the planned ETA for this? Why not integrating as a python dependency? Our two options here: - Bring it in as a python dependency and import the global declaration in our bundled javascript for built docs. - Treat it as a javascript dependency as part of the bundling process and bundle the theme javascript into our bundles I still lean towards the latter, as it's more consistent with how we treat the rest of our javascript dependencies. It's one less spurious script include as well, as it would be bundled in, if that's important. I think the only argument for the python package method is that we're already installing the theme on RTD. This should change though, as I can't think of any reason why the theme should exist outside version virtualenvs. I'm going to try for this week, it's at the top of my list. I had to bump it from my list last week as my focus wasn't on rtd.org.
2015-09-10T22:18:56
readthedocs/readthedocs.org
1,652
readthedocs__readthedocs.org-1652
[ "1115" ]
b2b6d0308bb5e5f2ed6c7afa6733b2fe44836e72
diff --git a/readthedocs/projects/views/public.py b/readthedocs/projects/views/public.py --- a/readthedocs/projects/views/public.py +++ b/readthedocs/projects/views/public.py @@ -90,18 +90,17 @@ def get_context_data(self, **kwargs): if self.request.is_secure(): protocol = 'https' + version_slug = project.get_default_version() + context['badge_url'] = "%s://%s%s?version=%s" % ( protocol, settings.PRODUCTION_DOMAIN, reverse('project_badge', args=[project.slug]), project.get_default_version(), ) - context['site_url'] = "%s://%s%s?badge=%s" % ( - protocol, - settings.PRODUCTION_DOMAIN, - reverse('projects_detail', args=[project.slug]), - project.get_default_version(), - ) + context['site_url'] = "{url}?badge={version}".format( + url=project.get_docs_url(version_slug), + version=version_slug) return context
[Suggestion] Use a link to the doc rather than the project for the badge The Markdown snippet provided for the badge currently uses a link to the project page on ReadTheDocs. I think it might be more useful for people seeing the badge on the package if the link was actually pointing to the rendered doc. They are more likely to be interested in the documentation of the package rather than the config used to build it. What do you think about this ?
The badge alternative text says `Documentation Status` so this was meant to display the status I guess. But for documentation status doesn't really mean much because it's unlikely somebody will break the documentation :) :+1: I would like, given that the badge says `docs: latest`, that clicking on the badge would take me to the build artifacts associated with the `latest` label in ReadTheDocs. The same would go for `docs: stable`, which would point to documentation associated with the latest tagged version. I agree: the badge should link to the docs themselves. No one but me is going to want to see the project page. I'm a :+1: as well. However we need a decision by @ericholscher or @agjohnson here. I think this makes sense, it is in line with our thoughts on redesigning what "failing" builds mean in the context of authorship and in consuming documentation. This was implemented as an author feature, but really should be a reader feature.
2015-09-14T14:54:40
readthedocs/readthedocs.org
1,665
readthedocs__readthedocs.org-1665
[ "943" ]
25caabbf036b54972b0b7365a02e205646e7455f
diff --git a/readthedocs/builds/models.py b/readthedocs/builds/models.py --- a/readthedocs/builds/models.py +++ b/readthedocs/builds/models.py @@ -8,7 +8,6 @@ from django.db import models from django.utils.translation import ugettext_lazy as _, ugettext -from guardian.shortcuts import assign from taggit.managers import TaggableManager from readthedocs.privacy.loader import (VersionManager, RelatedProjectManager, @@ -153,8 +152,6 @@ def save(self, *args, **kwargs): Add permissions to the Version for all owners on save. """ obj = super(Version, self).save(*args, **kwargs) - for owner in self.project.users.all(): - assign('view_version', owner, self) self.project.sync_supported_versions() return obj diff --git a/readthedocs/projects/forms.py b/readthedocs/projects/forms.py --- a/readthedocs/projects/forms.py +++ b/readthedocs/projects/forms.py @@ -10,8 +10,6 @@ from django.utils.translation import ugettext_lazy as _ from django.utils.safestring import mark_safe -from guardian.shortcuts import assign - from readthedocs.builds.constants import TAG from readthedocs.core.utils import trigger_build from readthedocs.redirects.models import Redirect @@ -375,8 +373,6 @@ def clean_user(self): def save(self): self.project.users.add(self.user) - # Force update of permissions - assign('view_project', self.user, self.project) return self.user diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -10,10 +10,12 @@ from django.core.exceptions import MultipleObjectsReturned from django.core.urlresolvers import reverse from django.db import models +from django.db.models import signals from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ -from guardian.shortcuts import assign +from guardian.shortcuts import assign_perm +from guardian.shortcuts import remove_perm from readthedocs.builds.constants import LATEST from readthedocs.builds.constants import LATEST_VERBOSE_NAME @@ -67,6 +69,9 @@ class Project(models.Model): modified_date = models.DateTimeField(_('Modified date'), auto_now=True) # Generally from conf.py + + # Notice that adding/removing users is intercepted by set_user_permissions + # method. users = models.ManyToManyField(User, verbose_name=_('User'), related_name='projects') name = models.CharField(_('Name'), max_length=255) @@ -283,8 +288,6 @@ def save(self, *args, **kwargs): if self.slug == '': raise Exception(_("Model must have slug")) super(Project, self).save(*args, **kwargs) - for owner in self.users.all(): - assign('view_project', owner, self) try: if self.default_branch: latest = self.versions.get(slug=LATEST) @@ -887,6 +890,36 @@ def add_comment(self, version_slug, page, content_hash, commit, user, text): hash=content_hash, commit=commit) return node.comments.create(user=user, text=text) + @classmethod + def set_user_permissions(cls, sender, instance, action, reverse, pk_set, + **kwargs): + assert not reverse, ( + "You must add users to the project via the `users` field " + "on the project instance.") + + def perform_action(set_perm, users, project): + for user in users: + set_perm('view_project', user, project) + for version in project.versions.all(): + set_perm('view_version', user, version) + + if action == 'post_add': + users = User.objects.filter(pk__in=pk_set) + perform_action(assign_perm, users, instance) + + if action == 'pre_remove': + users = User.objects.filter(pk__in=pk_set) + perform_action(remove_perm, users, instance) + + if action == 'pre_clear': + users = instance.users.all() + perform_action(remove_perm, users, instance) + + +signals.m2m_changed.connect( + Project.set_user_permissions, + sender=Project._meta.get_field('users').rel.through) + class ImportedFile(models.Model):
diff --git a/readthedocs/rtd_tests/tests/test_project.py b/readthedocs/rtd_tests/tests/test_project.py --- a/readthedocs/rtd_tests/tests/test_project.py +++ b/readthedocs/rtd_tests/tests/test_project.py @@ -1,5 +1,7 @@ import json +from django.contrib.auth.models import User from django.test import TestCase +from guardian.shortcuts import get_objects_for_user from readthedocs.builds.constants import LATEST from readthedocs.projects.models import Project from rest_framework.reverse import reverse @@ -83,3 +85,28 @@ def test_has_epub_with_epub_build_disabled(self): self.pip.enable_epub_build = False with fake_paths_by_regex('\.epub$'): self.assertFalse(self.pip.has_epub(LATEST)) + + def test_users_relations_sets_permissions(self): + john = get(User) + maggy = get(User) + + project = get(Project) + + def get_projects(user): + return get_objects_for_user(user, 'projects.view_project') + + self.assertTrue(project not in get_projects(john)) + + project.users.add(john) + self.assertTrue(project in get_projects(john)) + + project.users.remove(john) + self.assertTrue(project not in get_projects(john)) + + project.users.add(maggy) + self.assertTrue(project not in get_projects(john)) + self.assertTrue(project in get_projects(maggy)) + + project.users = [john] + self.assertTrue(project in get_projects(john)) + self.assertTrue(project not in get_projects(maggy)) diff --git a/readthedocs/rtd_tests/tests/test_project_views.py b/readthedocs/rtd_tests/tests/test_project_views.py --- a/readthedocs/rtd_tests/tests/test_project_views.py +++ b/readthedocs/rtd_tests/tests/test_project_views.py @@ -2,6 +2,7 @@ from django.contrib.messages import constants as message_const from django_dynamic_fixture import get from django_dynamic_fixture import new +from guardian.shortcuts import get_objects_for_user from mock import patch from readthedocs.rtd_tests.base import WizardTestCase, MockBuildTestCase @@ -221,3 +222,57 @@ def test_delete_project(self): self.assertFalse(Project.objects.filter(slug='pip').exists()) remove_path_from_web.delay.assert_called_with( path=project.doc_path) + + def test_add_admin_user(self): + project = get(Project, slug='pip', users=[self.user]) + anthony = get(User, username='anthony') + + response = self.client.get('/dashboard/pip/users/') + self.assertEqual(response.status_code, 200) + + response = self.client.post('/dashboard/pip/users/', { + 'user': 'not-anthony', + }) + self.assertEqual(response.status_code, 200) + self.assertTrue(response.context['form'].errors) + + self.assertEqual(project.users.count(), 1) + + response = self.client.post('/dashboard/pip/users/', { + 'user': 'anthony', + }) + self.assertEqual(response.status_code, 302) + + self.assertEqual(project.users.count(), 2) + self.assertTrue(anthony in project.users.all()) + + # Permission was assigned correctly. + self.assertTrue(project in get_objects_for_user( + anthony, 'projects.view_project')) + + def test_remove_admin_user(self): + anthony = get(User, username='anthony') + project = get(Project, slug='pip', users=[self.user, anthony]) + + # Just to be sure that anthony has the correct permissions. + self.assertTrue(project in get_objects_for_user( + anthony, 'projects.view_project')) + + response = self.client.post('/dashboard/pip/users/delete/', {}) + self.assertEqual(response.status_code, 404) + + response = self.client.post('/dashboard/pip/users/delete/', { + 'username': 'not-anthony', + }) + self.assertEqual(response.status_code, 404) + + response = self.client.post('/dashboard/pip/users/delete/', { + 'username': 'anthony', + }) + self.assertEqual(response.status_code, 302) + + self.assertTrue(anthony not in project.users.all()) + + # Permission were removed correctly. + self.assertTrue(project not in get_objects_for_user( + anthony, 'projects.view_project')) diff --git a/readthedocs/rtd_tests/tests/test_version_model.py b/readthedocs/rtd_tests/tests/test_version_model.py new file mode 100644 --- /dev/null +++ b/readthedocs/rtd_tests/tests/test_version_model.py @@ -0,0 +1,42 @@ +from django.contrib.auth.models import User +from django.test import TestCase +from django_dynamic_fixture import get +from guardian.shortcuts import get_objects_for_user + +from readthedocs.builds.models import Version +from readthedocs.projects.models import Project + + +class VersionPermissionTests(TestCase): + def test_version_save_sets_permission(self): + user = get(User) + project = get(Project) + + versions = get_objects_for_user(user, 'builds.view_version') + self.assertEqual(len(versions), 0) + + version = get(Version, project=project) + versions = get_objects_for_user(user, 'builds.view_version') + self.assertTrue(version not in versions) + + # When user is added after version. + project.users.add(user) + versions = get_objects_for_user(user, 'builds.view_version') + self.assertTrue(version in versions) + + # When user is moved for existing version. + project.users.remove(user) + versions = get_objects_for_user(user, 'builds.view_version') + self.assertTrue(version not in versions) + + # When user is added before version. + project.users.add(user) + second = get(Version, project=project) + versions = get_objects_for_user(user, 'builds.view_version') + self.assertTrue(second in versions) + + # When project users are reset. + project.users = [] + second = get(Version, project=project) + versions = get_objects_for_user(user, 'builds.view_version') + self.assertTrue(second not in versions)
Privacy permissions never get unset We are setting the "projects.view_project" permission on a user when they are a project admin, but nothing ever removes this permission when they are removed.
2015-09-17T17:10:23
readthedocs/readthedocs.org
1,688
readthedocs__readthedocs.org-1688
[ "1641" ]
da702f964aef8b9011233384c5eafe957805ea2e
diff --git a/readthedocs/core/management/commands/reindex_elasticsearch.py b/readthedocs/core/management/commands/reindex_elasticsearch.py --- a/readthedocs/core/management/commands/reindex_elasticsearch.py +++ b/readthedocs/core/management/commands/reindex_elasticsearch.py @@ -2,12 +2,12 @@ from optparse import make_option from django.core.management.base import BaseCommand +from django.core.management.base import CommandError from django.conf import settings from readthedocs.builds.constants import LATEST from readthedocs.builds.models import Version -from readthedocs.search import parse_json -from readthedocs.restapi.utils import index_search_request +from readthedocs.projects.tasks import update_search log = logging.getLogger(__name__) @@ -27,13 +27,17 @@ def handle(self, *args, **options): ''' project = options['project'] + queryset = Version.objects.public() + if project: - queryset = Version.objects.public(project__slug=project) + queryset = queryset.filter(project__slug=project) + if not queryset.exists(): + raise CommandError( + 'No project with slug: {slug}'.format(slug=project)) log.info("Building all versions for %s" % project) elif getattr(settings, 'INDEX_ONLY_LATEST', True): - queryset = Version.objects.public().filter(slug=LATEST) - else: - queryset = Version.objects.public() + queryset = queryset.filter(slug=LATEST) + for version in queryset: log.info("Reindexing %s" % version) try: @@ -41,10 +45,9 @@ def handle(self, *args, **options): except: # This will happen on prod commit = None + try: - page_list = parse_json.process_all_json_files(version, build_dir=False) - index_search_request( - version=version, page_list=page_list, commit=commit, - project_scale=0, page_scale=0, section=False, delete=False) + update_search(version.pk, commit, + delete_non_commit_files=False) except Exception: - log.error('Build failed for %s' % version, exc_info=True) + log.error('Reindex failed for %s' % version, exc_info=True) diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -613,11 +613,12 @@ def move_files(version_pk, hostname, html=False, localmedia=False, search=False, @task(queue='web') -def update_search(version_pk, commit): +def update_search(version_pk, commit, delete_non_commit_files=True): """Task to update search indexes :param version_pk: Version id to update :param commit: Commit that updated index + :param delete_non_commit_files: Delete files not in commit from index """ version = Version.objects.get(pk=version_pk) @@ -642,6 +643,7 @@ def update_search(version_pk, commit): # Don't index sections to speed up indexing. # They aren't currently exposed anywhere. section=False, + delete=delete_non_commit_files, )
Fix or abandon reindex_elasticsearch Currently the managment command `reindex_elasticsearch` [located here](https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/core/management/commands/reindex_elasticsearch.py) is broken in at least two ways: 1. We give a [filter argument to the version's manager public method](https://github.com/rtfd/readthedocs.org/blob/adf227ae3810b0820d0ff548651dcd223f4f2388/readthedocs/core/management/commands/reindex_elasticsearch.py#L31). But that does not do any filtering. Therefore only selecting one project that should be updated will result in all projects to be reindexed. 2. We do not distinguish between mkdocs/sphinx projects. The used `parse_json.process_all_json_files` will only work correctly for Sphinx based projects. We should either remove the command completely as long as it no longer used/needed. Or fix the issues outlined above.
This is the only way we have to reindex our search cluster, so it's definitely something we need to keep around.
2015-09-24T09:33:56
readthedocs/readthedocs.org
1,804
readthedocs__readthedocs.org-1804
[ "1783" ]
e7bc900c5f968a81186a63a389a5b4a1f270f543
diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -412,6 +412,11 @@ def checkout_path(self, version=LATEST): def venv_path(self, version=LATEST): return os.path.join(self.doc_path, 'envs', version) + @property + def pip_cache_path(self): + """Path to pip cache""" + return os.path.join(self.doc_path, '.cache', 'pip') + # # Paths for symlinks in project doc_path. # diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -261,6 +261,8 @@ def setup_environment(self): 'install', '--use-wheel', '-U', + '--cache-dir', + self.project.pip_cache_path, ] if self.project.use_system_packages: # Other code expects sphinx-build to be installed inside the @@ -294,6 +296,8 @@ def setup_environment(self): self.project.venv_bin(version=self.version.slug, filename='pip'), 'install', '--exists-action=w', + '--cache-dir', + self.project.pip_cache_path, '-r{0}'.format(requirements_file_path), cwd=checkout_path, bin_path=self.project.venv_bin(version=self.version.slug) @@ -309,6 +313,8 @@ def setup_environment(self): self.project.venv_bin(version=self.version.slug, filename='pip'), 'install', '--ignore-installed', + '--cache-dir', + self.project.pip_cache_path, '.', cwd=checkout_path, bin_path=self.project.venv_bin(version=self.version.slug)
Establish pip cache for docker containers The containers aren't sharing the normal pip cache of `/home/docs/.cache/pip`, which also effects the wheel cache. We should explicitly specify a project-local pip cache dir to use, so that package install time can be reduced. Raised in #1767
2015-11-03T23:33:15
readthedocs/readthedocs.org
1,947
readthedocs__readthedocs.org-1947
[ "1901" ]
e1c4773cc1abc2a4f71cb34a1aadc4b92e2d0ed4
diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -100,7 +100,7 @@ def install_core_requirements(self): 'sphinx==1.3.1', 'Pygments==2.0.2', 'setuptools==18.6.1', - 'docutils==0.11', + 'docutils==0.12', 'mkdocs==0.14.0', 'mock==1.0.1', 'pillow==2.6.1', @@ -174,22 +174,22 @@ def setup_base(self): shutil.rmtree(version_path) self.build_env.run( 'conda', + 'env', 'create', - '--yes', '--name', self.version.slug, - 'python={python_version}'.format(python_version=self.config.python_version), + '--file', + self.config.conda_file, bin_path=None, # Don't use conda bin that doesn't exist yet ) def install_core_requirements(self): - conda_env_path = os.path.join(self.project.doc_path, 'conda') # Use conda for requirements it packages requirements = [ 'sphinx==1.3.1', 'Pygments==2.0.2', - 'docutils==0.11', + 'docutils==0.12', 'mock==1.0.1', 'pillow==3.0.0', 'sphinx_rtd_theme==0.1.7', @@ -231,7 +231,6 @@ def install_core_requirements(self): ) def install_user_requirements(self): - conda_env_path = os.path.join(self.project.doc_path, 'conda') self.build_env.run( 'conda', 'env',
conda env creation fails if Python 3 selected I put this in `readthedocs.yml`: ``` yaml conda: file: docs/conda-env.yml python: version: 3 setup_py_install: true ``` It creates a conda env with Python 3.5, and then tries to install the standard docs machinery. But docutils is pinned to 0.11, and there isn't a build of this for Python 3.5 (there is a package of docutils 0.12). So I see this failure: ``` conda install --yes --name docs-build-w-conda sphinx==1.3.1 Pygments==2.0.2 docutils==0.11 mock==1.0.1 pillow==3.0.0 sphinx_rtd_theme==0.1.7 alabaster>=0.7,<0.8,!=0.7.5 Fetching package metadata: /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:315: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning. SNIMissingWarning /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:120: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning .... Solving package specifications: .. Error: Unsatisfiable package specifications. Generating hint: [ ]| | 0% [2/8 ]|############ | 25% [3/8 ]|################## | 37% [5/8 ]|############################### | 62% [6/8 ]|##################################### | 75% [ COMPLETE ]|##################################################| 100% Hint: the following packages conflict with each other: - docutils ==0.11 - python 3.5* Use 'conda info docutils' etc. to see the dependencies for each package. ``` The obvious solution is not to pin docutils so it automatically picks the latest version available. If you prefer to keep it pinned, I think that installing dependencies at the same time as you create the environment should work; in this instance, it would fall back to Python 3.4 so it could satisfy the dependencies: ``` conda create --yes --name docs-build-w-conda python=3 sphinx==1.3.1 Pygments==2.0.2 docutils==0.11 ... ```
+1 ing. Same issue. Wouldn't it be easier to simply provide a RTD-specific environment.yml file, which should include all RTD requirements and possibly a RTD-channel that includes those packages for all (relevant) Python versions. Then creating the environment for RTD and the package can be done in one fell swoop and these issues would be prevented. You should be able to specify the proper python version in the `readthedocs.yml` file, eg. `version: 3.5` I'd like it to remain possible to specify `python: 3` and get the latest supported version automatically. With conda at least, it should be very easy to support both.
2016-01-20T18:20:54
readthedocs/readthedocs.org
1,969
readthedocs__readthedocs.org-1969
[ "1966" ]
af5de622cbc0650e3a688bc293b27a23f3b26ddb
diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -97,7 +97,7 @@ def setup_base(self): def install_core_requirements(self): requirements = [ - 'sphinx==1.3.4', + 'sphinx==1.3.5', 'Pygments==2.0.2', 'setuptools==18.6.1', 'docutils==0.12', @@ -187,7 +187,7 @@ def install_core_requirements(self): # Use conda for requirements it packages requirements = [ - 'sphinx==1.3.1', + 'sphinx==1.3.5', 'Pygments==2.0.2', 'docutils==0.12', 'mock',
move to sphinx 1.3.5 sphinx 1.3.4 introduced this bug: https://github.com/sphinx-doc/sphinx/issues/2247 , which breaks builds of projects using definition lists containing regular expression like strings. This was considered a high priority bug by the sphinx devs and was fixed with version 1.3.5. Please move to the new version so that I can again build my docs.
Is this as simple as a one-character fix to change the sphinx version in requirements/pip.txt? We are having the same problems on our project. You can specify a specific Sphinx version in your requirements file, and we'll install it over our default. Reopening this as we should test and change our dependencies for sphinx still. Anyone that requires the latest release should use an override though. Thanks for reopening this. While adding a working sphinx version to your requirements file is a workaround (thanks for pointing it out), I'd like to stress that this is a bug in just one specific version of sphinx so affected docs would build with any sphinx **except** 1.3.4. Just conceptually I find it the wrong approach to tell people to adjust their repos because you are building their docs with buggy software. The right solution, IMO, is still to move on to v1.3.5 or, alternatively, go back to 1.3.3. For the same reason I think this should not be classified as an enhancement, but as a bug fix. @wm75 we just can't flip a switch and deploy it -- vetting and all that. 1.3.5 is our next target and it will be pinned as soon as we can verify the new release. Sure, no problem waiting. The requirements file works for me for the time being.
2016-02-01T16:03:26
readthedocs/readthedocs.org
1,995
readthedocs__readthedocs.org-1995
[ "1978" ]
72fefa63ed7a4e59f1917bf88a47d9142269698c
diff --git a/readthedocs/doc_builder/constants.py b/readthedocs/doc_builder/constants.py --- a/readthedocs/doc_builder/constants.py +++ b/readthedocs/doc_builder/constants.py @@ -23,3 +23,5 @@ DOCKER_TIMEOUT_EXIT_CODE = 42 DOCKER_OOM_EXIT_CODE = 137 + +DOCKER_HOSTNAME_MAX_LEN = 64 diff --git a/readthedocs/doc_builder/environments.py b/readthedocs/doc_builder/environments.py --- a/readthedocs/doc_builder/environments.py +++ b/readthedocs/doc_builder/environments.py @@ -30,7 +30,7 @@ from .constants import (DOCKER_SOCKET, DOCKER_VERSION, DOCKER_IMAGE, DOCKER_LIMITS, DOCKER_TIMEOUT_EXIT_CODE, DOCKER_OOM_EXIT_CODE, SPHINX_TEMPLATE_DIR, - MKDOCS_TEMPLATE_DIR) + MKDOCS_TEMPLATE_DIR, DOCKER_HOSTNAME_MAX_LEN) log = logging.getLogger(__name__) @@ -250,23 +250,29 @@ def get_wrapped_command(self): class BuildEnvironment(object): - ''' - Base build environment + """Base build environment - Placeholder for reorganizing command execution. + Base class for wrapping command execution for build steps. This provides a + context for command execution and reporting, and eventually performs updates + on the build object itself, reporting success/failure, as well as top-level + failures. :param project: Project that is being built :param version: Project version that is being built :param build: Build instance :param record: Record status of build object - ''' + :param environment: shell environment variables + :param report_build_success: update build if successful + """ - def __init__(self, project=None, version=None, build=None, record=True, environment=None): + def __init__(self, project=None, version=None, build=None, record=True, + environment=None, report_build_success=True): self.project = project self.version = version self.build = build self.record = record self.environment = environment or {} + self.report_build_success = report_build_success self.commands = [] self.failure = None @@ -372,12 +378,14 @@ def done(self): self.build['state'] == BUILD_STATE_FINISHED) def update_build(self, state=None): - """ - Record a build by hitting the API. + """Record a build by hitting the API - Returns nothing + This step is skipped if we aren't recording the build, or if we don't + want to record successful builds yet (if we are running setup commands + for the build) """ - if not self.record: + if not self.record or (state == BUILD_STATE_FINISHED and + not self.report_build_success): return None self.build['project'] = self.project.pk @@ -448,9 +456,13 @@ def __init__(self, *args, **kwargs): super(DockerEnvironment, self).__init__(*args, **kwargs) self.client = None self.container = None - self.container_name = None - if self.version: - self.container_name = slugify(unicode(self.version)) + self.container_name = slugify( + 'build-{build}-project-{project_id}-{project_name}'.format( + build=self.build.get('id'), + project_id=self.project.pk, + project_name=self.project.slug, + )[:DOCKER_HOSTNAME_MAX_LEN] + ) if self.project.container_mem_limit: self.container_mem_limit = self.project.container_mem_limit if self.project.container_time_limit: diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -113,7 +113,8 @@ def run(self, pk, version_pk=None, build_pk=None, record=True, docker=False, env_cls = LocalEnvironment self.setup_env = env_cls(project=self.project, version=self.version, - build=self.build, record=record) + build=self.build, record=record, + report_build_success=False) # Environment used for code checkout & initial configuration reading with self.setup_env:
diff --git a/readthedocs/rtd_tests/tests/test_doc_building.py b/readthedocs/rtd_tests/tests/test_doc_building.py --- a/readthedocs/rtd_tests/tests/test_doc_building.py +++ b/readthedocs/rtd_tests/tests/test_doc_building.py @@ -116,9 +116,9 @@ def tearDown(self): def test_container_id(self): '''Test docker build command''' docker = DockerEnvironment(version=self.version, project=self.project, - build={}) + build={'id': 123}) self.assertEqual(docker.container_id, - 'version-foobar-of-pip-20') + 'build-123-project-6-pip') def test_connection_failure(self): '''Connection failure on to docker socket should raise exception''' @@ -163,12 +163,12 @@ def test_command_execution(self): }) build_env = DockerEnvironment(version=self.version, project=self.project, - build={}) + build={'id': 123}) with build_env: build_env.run('echo test', cwd='/tmp') self.mocks.docker_client.exec_create.assert_called_with( - container='version-foobar-of-pip-20', + container='build-123-project-6-pip', cmd="/bin/sh -c 'cd /tmp && echo\\ test'", stderr=True, stdout=True @@ -193,12 +193,12 @@ def test_command_execution_cleanup_exception(self): }) build_env = DockerEnvironment(version=self.version, project=self.project, - build={}) + build={'id': 123}) with build_env: build_env.run('echo', 'test', cwd='/tmp') self.mocks.docker_client.kill.assert_called_with( - 'version-foobar-of-pip-20') + 'build-123-project-6-pip') self.assertTrue(build_env.successful) def test_container_already_exists(self):
Double build environments cause premature marking of build complete With the two separate runs of the build environments on the build task, the build gets marked as complete by the `LocalEnvironment` pass. Environment creation should include a way to override reporting the build state.
2016-02-16T20:51:33
readthedocs/readthedocs.org
2,017
readthedocs__readthedocs.org-2017
[ "2015" ]
85a63c3c7868509cbaad4d07d078e25ad422524e
diff --git a/readthedocs/doc_builder/backends/mkdocs.py b/readthedocs/doc_builder/backends/mkdocs.py --- a/readthedocs/doc_builder/backends/mkdocs.py +++ b/readthedocs/doc_builder/backends/mkdocs.py @@ -98,7 +98,7 @@ def append_conf(self, **kwargs): # Will be available in the JavaScript as READTHEDOCS_DATA. readthedocs_data = { 'project': self.version.project.slug, - 'version': self.version.verbose_name, + 'version': self.version.slug, 'language': self.version.project.language, 'page': None, 'theme': "readthedocs",
Read The Docs TOC Footer Not Loading and Throwing Errors ## Details If this issue is for a specific project or build, include the following: - Project: http://gobblin.readthedocs.org/en/readthedocs/ - Build #: latest When loading the project page, the Chrome Inspect tool throws an error saying: `Failed to load resource: the server responded with a status of 404 (NOT FOUND) https://readthedocs.org//api/v2/footer_html/?callback=jQuery211025191313796…2Fcheckouts%2Freadthedocs%2Fgobblin-docs&source_suffix=.md&_=1456430887845` and `Error loading Read the Docs footer $.ajax.error @ readthedocs-doc-embed.js:1` I notice that the Read the Docs tab on the bottom left of the screen (at the bottom of the main TOC) is not loading. I'm guessing these are related, but any idea why this is happening? Is this a bug? Has anyone else seen this issue? <img width="319" alt="screen shot 2016-02-25 at 12 11 20 pm" src="https://cloud.githubusercontent.com/assets/1282583/13332876/eb7d73ca-dbb8-11e5-9c54-7851873c9871.png">
For reference my `mkdocs.yml` file is here: https://github.com/linkedin/gobblin/blob/readTheDocs/mkdocs.yml The docs are checked into the following branch of this GitHub Project: https://github.com/linkedin/gobblin/tree/readTheDocs and are under the folder `gobblin-docs` The ReadTheDocs Admin Page is here: https://readthedocs.org/projects/gobblin/ The ReadTheDocs Home Page is here: http://gobblin.readthedocs.org/en/readthedocs/ For some reason, the URL requested includes an incorrect version slug of: `&version=readTheDocs`. It should be the version slug, ie:`&version=readthedocs`. This seems like whatever Mkdocs is using here is incorrect. Seems this is where it is wrong: https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/doc_builder/backends/mkdocs.py#L101 Thanks a ton for the investigation @agjohnson Should I go ahead and open an Issue on the Mkdocs GitHub? If the change is as simple as `'version': self.version.verbose_name,` to `'version': self.version.slug,` I can create the PR too A PR would be :100: I believe that change should be enough. I don't use Mkdocs and haven't tested this however.
2016-02-26T23:33:11
readthedocs/readthedocs.org
2,027
readthedocs__readthedocs.org-2027
[ "2011" ]
c60d3eb08e053f5ee08b29160b1cf6e6722a0def
diff --git a/readthedocs/doc_builder/config.py b/readthedocs/doc_builder/config.py --- a/readthedocs/doc_builder/config.py +++ b/readthedocs/doc_builder/config.py @@ -23,8 +23,17 @@ def __init__(self, version, yaml_config): self._project = version.project self._yaml_config = yaml_config + @property + def pip_install(self): + if 'pip_install' in self._yaml_config.get('python', {}): + return self._yaml_config['python']['pip_install'] + else: + return False + @property def install_project(self): + if self.pip_install: + return True if 'setup_py_install' in self._yaml_config.get('python', {}): return self._yaml_config['python']['setup_py_install'] else: diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -43,7 +43,7 @@ def delete_existing_build_dir(self): def install_package(self): setup_path = os.path.join(self.checkout_path, 'setup.py') if os.path.isfile(setup_path) and self.config.install_project: - if getattr(settings, 'USE_PIP_INSTALL', False): + if self.config.pip_install or getattr(settings, 'USE_PIP_INSTALL', False): self.build_env.run( 'python', self.venv_bin(filename='pip'),
allow users to pick if package should be installed with pip ## Details There is a system-wide config for whether "install this package" should mean `pip install .` or `setup.py install`. It would be useful for packages to be able to specify, at least in the `setup.py install` case that's on the official deployment, that `pip install .` should be used for their package.
This might be worth exploring as part of our push to move configuration into a top-level `readthedoc.yaml` configuration file. Leaving this open here, it might move to the readthedocs-build repo however.
2016-02-29T10:38:57
readthedocs/readthedocs.org
2,050
readthedocs__readthedocs.org-2050
[ "1865" ]
da27e14ae85ba7940ae54053a9d6ad3b7fcf6900
diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -98,7 +98,7 @@ def setup_base(self): def install_core_requirements(self): requirements = [ 'sphinx==1.3.5', - 'Pygments==2.0.2', + 'Pygments==2.1.3', 'setuptools==20.1.1', 'docutils==0.12', 'mkdocs==0.15.0', @@ -189,7 +189,7 @@ def install_core_requirements(self): # Use conda for requirements it packages requirements = [ 'sphinx==1.3.5', - 'Pygments==2.0.2', + 'Pygments==2.1.3', 'docutils==0.12', 'mock', 'pillow==3.0.0',
Increment Pygements release to support Python 3.5 syntax Hello, Read the Docs offers the option to build docs with Python 2.x or 3.x, which is great. Python 3.5 introduced some new syntax, namely the `await` and `async` keywords. Since Read the Docs runs Python 3.4, code samples that use this syntax cannot be parsed and thus aren't syntax-highlighted. See the first block on [this page](http://aiohttp.readthedocs.org/en/v0.19.0/web.html) for example. Have you considered making it possible to pick a specific Python version, perhaps among 2.7, 3.4, 3.5? Alternatively, do you have a rough idea of when you'll upgrade the platform to 3.5? Thanks!
I appear to have incorrectly assumed that it was related to the version of Python running Sphinx. Apparently the next release of Pygments (for which there's no ETA) should solve the problem. https://bitbucket.org/birkenfeld/pygments-main/issues/1154/please-make-next-release Regarding the Python version selection: we haven't yet, though the ability to use arbitrary versions of Python might be a good future feature. The real issue seems to be a pending Pygments release, we'll pin the next release to come out. Pygments 2.1 was releaseed mid-January, unblocking this issue. Is it just a matter of bumping Pygments to 2.1.3 in `requirements/pip.txt`? You'll need to update the requirements in: https://github.com/rtfd/readthedocs.org/blob/42ab9d198494d5cf9fe320ac217d837bf480c73f/readthedocs/doc_builder/python_environments.py
2016-03-08T08:01:41
readthedocs/readthedocs.org
2,119
readthedocs__readthedocs.org-2119
[ "2090" ]
47a0b255ae89f68b1666e26e87864f219011a244
diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -727,13 +727,6 @@ def update_stable_version(self): identifier=new_stable.identifier) return new_stable - def version_from_branch_name(self, branch): - versions = self.versions_from_branch_name(branch) - try: - return versions[0] - except IndexError: - return None - def versions_from_branch_name(self, branch): return ( self.versions.filter(identifier=branch) |
diff --git a/readthedocs/rtd_tests/tests/test_post_commit_hooks.py b/readthedocs/rtd_tests/tests/test_post_commit_hooks.py --- a/readthedocs/rtd_tests/tests/test_post_commit_hooks.py +++ b/readthedocs/rtd_tests/tests/test_post_commit_hooks.py @@ -2,27 +2,44 @@ import json import logging +from django_dynamic_fixture import get + +from readthedocs.builds.models import Version from readthedocs.projects.models import Project from readthedocs.projects import tasks log = logging.getLogger(__name__) -class GitLabWebHookTest(TestCase): - fixtures = ["eric", "test_data"] - - def tearDown(self): - tasks.update_docs = self.old_bd +class BasePostCommitTest(TestCase): + def _setup(self): + self.rtfd = get( + Project, repo='https://github.com/rtfd/readthedocs.org', slug='read-the-docs') + self.rtfd_not_ok = get( + Version, project=self.rtfd, slug='not_ok', identifier='not_ok', active=False) + self.rtfd_awesome = get( + Version, project=self.rtfd, slug='awesome', identifier='awesome', active=True) - def setUp(self): - self.old_bd = tasks.update_docs + self.pip = get(Project, repo='https://bitbucket.org/pip/pip', repo_type='hg') + self.pip_not_ok = get( + Version, project=self.pip, slug='not_ok', identifier='not_ok', active=False) + self.sphinx = get(Project, repo='https://bitbucket.org/sphinx/sphinx', repo_type='git') def mock(*args, **kwargs): log.info("Mocking for great profit and speed.") + tasks.update_docs = mock tasks.update_docs.apply_async = mock self.client.login(username='eric', password='test') + + +class GitLabWebHookTest(BasePostCommitTest): + fixtures = ["eric"] + + def setUp(self): + self._setup() + self.payload = { "object_kind": "push", "before": "95790bf891e76fee5e1747ab589903a6a1f80f22", @@ -39,7 +56,7 @@ def mock(*args, **kwargs): "homepage": "http://github.com/rtfd/readthedocs.org", "git_http_url": "http://github.com/rtfd/readthedocs.org.git", "git_ssh_url": "[email protected]:rtfd/readthedocs.org.git", - "visibility_level":0 + "visibility_level": 0 }, "commits": [ { @@ -74,11 +91,13 @@ def test_gitlab_post_commit_hook_builds_branch_docs_if_it_should(self): """ r = self.client.post('/gitlab/', {'payload': json.dumps(self.payload)}) self.assertEqual(r.status_code, 200) - self.assertEqual(r.content, '(URL Build) Build Started: github.com/rtfd/readthedocs.org [awesome]') + self.assertEqual( + r.content, '(URL Build) Build Started: github.com/rtfd/readthedocs.org [awesome]') self.payload['ref'] = 'refs/heads/not_ok' r = self.client.post('/gitlab/', {'payload': json.dumps(self.payload)}) self.assertEqual(r.status_code, 200) - self.assertEqual(r.content, '(URL Build) Not Building: github.com/rtfd/readthedocs.org [not_ok]') + self.assertEqual( + r.content, '(URL Build) Not Building: github.com/rtfd/readthedocs.org [not_ok]') self.payload['ref'] = 'refs/heads/unknown' r = self.client.post('/gitlab/', {'payload': json.dumps(self.payload)}) self.assertEqual(r.status_code, 200) @@ -97,23 +116,19 @@ def test_gitlab_post_commit_knows_default_branches(self): r = self.client.post('/gitlab/', {'payload': json.dumps(self.payload)}) self.assertEqual(r.status_code, 200) - self.assertEqual(r.content, '(URL Build) Build Started: github.com/rtfd/readthedocs.org [latest]') + self.assertEqual( + r.content, '(URL Build) Build Started: github.com/rtfd/readthedocs.org [latest]') rtd.default_branch = old_default rtd.save() -class GitHubPostCommitTest(TestCase): - fixtures = ["eric", "test_data"] +class GitHubPostCommitTest(BasePostCommitTest): + fixtures = ["eric"] def setUp(self): - def mock(*args, **kwargs): - pass + self._setup() - tasks.UpdateDocsTask.run = mock - tasks.UpdateDocsTask.apply_async = mock - - self.client.login(username='eric', password='test') self.payload = { "after": "5ad757394b926e5637ffeafe340f952ef48bd270", "base_ref": "refs/heads/master", @@ -181,7 +196,10 @@ def test_github_upper_case_repo(self): payload['repository']['url'] = payload['repository']['url'].upper() r = self.client.post('/github/', {'payload': json.dumps(payload)}) self.assertEqual(r.status_code, 200) - self.assertEqual(r.content, '(URL Build) Build Started: HTTPS://GITHUB.COM/RTFD/READTHEDOCS.ORG [awesome]') + self.assertEqual( + r.content, + '(URL Build) Build Started: HTTPS://GITHUB.COM/RTFD/READTHEDOCS.ORG [awesome]' + ) self.payload['ref'] = 'refs/heads/not_ok' def test_400_on_no_ref(self): @@ -203,11 +221,13 @@ def test_github_post_commit_hook_builds_branch_docs_if_it_should(self): """ r = self.client.post('/github/', {'payload': json.dumps(self.payload)}) self.assertEqual(r.status_code, 200) - self.assertEqual(r.content, '(URL Build) Build Started: github.com/rtfd/readthedocs.org [awesome]') + self.assertEqual( + r.content, '(URL Build) Build Started: github.com/rtfd/readthedocs.org [awesome]') self.payload['ref'] = 'refs/heads/not_ok' r = self.client.post('/github/', {'payload': json.dumps(self.payload)}) self.assertEqual(r.status_code, 200) - self.assertEqual(r.content, '(URL Build) Not Building: github.com/rtfd/readthedocs.org [not_ok]') + self.assertEqual( + r.content, '(URL Build) Not Building: github.com/rtfd/readthedocs.org [not_ok]') self.payload['ref'] = 'refs/heads/unknown' r = self.client.post('/github/', {'payload': json.dumps(self.payload)}) self.assertEqual(r.status_code, 200) @@ -226,18 +246,27 @@ def test_github_post_commit_knows_default_branches(self): r = self.client.post('/github/', {'payload': json.dumps(self.payload)}) self.assertEqual(r.status_code, 200) - self.assertEqual(r.content, '(URL Build) Build Started: github.com/rtfd/readthedocs.org [latest]') + self.assertEqual( + r.content, '(URL Build) Build Started: github.com/rtfd/readthedocs.org [latest]') rtd.default_branch = old_default rtd.save() + +class CorePostCommitTest(BasePostCommitTest): + fixtures = ["eric"] + + def setUp(self): + self._setup() + def test_core_commit_hook(self): rtd = Project.objects.get(slug='read-the-docs') rtd.default_branch = 'master' rtd.save() r = self.client.post('/build/%s' % rtd.pk, {'version_slug': 'master'}) self.assertEqual(r.status_code, 302) - self.assertEqual(r._headers['location'][1], 'http://testserver/projects/read-the-docs/builds/') + self.assertEqual( + r._headers['location'][1], 'http://testserver/projects/read-the-docs/builds/') def test_hook_state_tracking(self): rtd = Project.objects.get(slug='read-the-docs') @@ -245,3 +274,142 @@ def test_hook_state_tracking(self): self.client.post('/build/%s' % rtd.pk, {'version_slug': 'latest'}) # Need to re-query to get updated DB entry self.assertEqual(Project.objects.get(slug='read-the-docs').has_valid_webhook, True) + + +class BitBucketHookTests(BasePostCommitTest): + + def setUp(self): + self._setup() + + self.hg_payload = { + "canon_url": "https://bitbucket.org", + "commits": [ + { + "author": "marcus", + "branch": "default", + "files": [ + { + "file": "somefile.py", + "type": "modified" + } + ], + "message": "Added some featureA things", + "node": "d14d26a93fd2", + "parents": [ + "1b458191f31a" + ], + "raw_author": "Marcus Bertrand <[email protected]>", + "raw_node": "d14d26a93fd28d3166fa81c0cd3b6f339bb95bfe", + "revision": 3, + "size": -1, + "timestamp": "2012-05-30 06:07:03", + "utctimestamp": "2012-05-30 04:07:03+00:00" + } + ], + "repository": { + "absolute_url": "/pip/pip/", + "fork": False, + "is_private": True, + "name": "Project X", + "owner": "marcus", + "scm": "hg", + "slug": "project-x", + "website": "" + }, + "user": "marcus" + } + + self.git_payload = { + "canon_url": "https://bitbucket.org", + "commits": [ + { + "author": "marcus", + "branch": "master", + "files": [ + { + "file": "somefile.py", + "type": "modified" + } + ], + "message": "Added some more things to somefile.py\n", + "node": "620ade18607a", + "parents": [ + "702c70160afc" + ], + "raw_author": "Marcus Bertrand <[email protected]>", + "raw_node": "620ade18607ac42d872b568bb92acaa9a28620e9", + "revision": None, + "size": -1, + "timestamp": "2012-05-30 05:58:56", + "utctimestamp": "2012-05-30 03:58:56+00:00" + } + ], + "repository": { + "absolute_url": "/sphinx/sphinx/", + "fork": False, + "is_private": True, + "name": "Project X", + "owner": "marcus", + "scm": "git", + "slug": "project-x", + "website": "https://atlassian.com/" + }, + "user": "marcus" + } + + def test_bitbucket_post_commit(self): + r = self.client.post('/bitbucket/', {'payload': json.dumps(self.hg_payload)}) + self.assertEqual(r.status_code, 200) + self.assertEqual( + r.content, '(URL Build) Build Started: bitbucket.org/pip/pip [latest]') + + r = self.client.post('/bitbucket/', {'payload': json.dumps(self.git_payload)}) + self.assertEqual(r.status_code, 200) + self.assertEqual( + r.content, '(URL Build) Build Started: bitbucket.org/sphinx/sphinx [latest]') + + def test_bitbucket_post_commit_hook_builds_branch_docs_if_it_should(self): + """ + Test the bitbucket post commit hook to see if it will only build + versions that are set to be built if the branch they refer to + is updated. Otherwise it is no op. + """ + r = self.client.post('/bitbucket/', {'payload': json.dumps(self.hg_payload)}) + self.assertEqual(r.status_code, 200) + self.assertEqual( + r.content, '(URL Build) Build Started: bitbucket.org/pip/pip [latest]') + + self.hg_payload['commits'] = [{ + "branch": "not_ok", + }] + r = self.client.post('/bitbucket/', {'payload': json.dumps(self.hg_payload)}) + self.assertEqual( + r.content, '(URL Build) Not Building: bitbucket.org/pip/pip [not_ok]') + + self.hg_payload['commits'] = [{ + "branch": "unknown", + }] + r = self.client.post('/bitbucket/', {'payload': json.dumps(self.hg_payload)}) + self.assertEqual(r.status_code, 200) + self.assertEqual( + r.content, '(URL Build) Not Building: bitbucket.org/pip/pip []') + + def test_bitbucket_default_branch(self): + self.test_project = get( + Project, repo='HTTPS://bitbucket.org/test/project', slug='test-project', + default_branch='integration', repo_type='git', + ) + + self.git_payload['commits'] = [{ + "branch": "integration", + }] + self.git_payload['repository'] = { + 'absolute_url': '/test/project/' + } + + r = self.client.post('/bitbucket/', {'payload': json.dumps(self.git_payload)}) + self.assertEqual(r.status_code, 200) + self.assertEqual( + r.content, '(URL Build) Build Started: bitbucket.org/test/project [latest]') + +
Add tests for BitBucket post-commit hooks We currently have tests for Gitlab and GitHub hooks, but not BitBucket. They should go here: https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/rtd_tests/tests/test_post_commit_hooks.py
2016-04-06T23:50:16
readthedocs/readthedocs.org
2,286
readthedocs__readthedocs.org-2286
[ "2229" ]
800f7b121b3037efc49ee9c510a2a65dcaee58b3
diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -297,11 +297,15 @@ def setup_environment(self): """ self.build_env.update_build(state=BUILD_STATE_INSTALLING) - self.python_env.delete_existing_build_dir() - self.python_env.setup_base() - self.python_env.install_core_requirements() - self.python_env.install_user_requirements() - self.python_env.install_package() + with self.project.repo_nonblockinglock( + version=self.version, + max_lock_age=getattr(settings, 'REPO_LOCK_SECONDS', 30)): + + self.python_env.delete_existing_build_dir() + self.python_env.setup_base() + self.python_env.install_core_requirements() + self.python_env.install_user_requirements() + self.python_env.install_package() def build_docs(self): """Wrapper to all build functions
"IOError: [Errno 26] Text file busy" during build. ## Details - Project URL: https://github.com/xmlrunner/unittest-xml-reporting - Build URL (if applicable): https://readthedocs.org/projects/unittest-xml-reporting/builds/4052270/ - Read the Docs username (if applicable): dnozay ## Excepted Result Build should have passed (e.g. https://readthedocs.org/projects/unittest-xml-reporting/builds/4052269/) ## Actual Result `IOError` raised during `python -mvirtualenv --no-site-packages /home/docs/checkouts/readthedocs.org/user_builds/unittest-xml-reporting/envs/latest`
2016-07-06T18:56:42
readthedocs/readthedocs.org
2,302
readthedocs__readthedocs.org-2302
[ "2262" ]
1e1e496f8971b2dd64822d09147aa63b8e318457
diff --git a/readthedocs/projects/views/private.py b/readthedocs/projects/views/private.py --- a/readthedocs/projects/views/private.py +++ b/readthedocs/projects/views/private.py @@ -251,13 +251,18 @@ def done(self, form_list, **kwargs): other side effects for now, by signalling a save without commit. Then, finish by added the members to the project and saving. """ + form_data = self.get_all_cleaned_data() + extra_fields = ProjectExtraForm.Meta.fields # expect the first form basics_form = form_list[0] # Save the basics form to create the project instance, then alter # attributes directly from other forms project = basics_form.save() - for form in form_list[1:]: - for (field, value) in form.cleaned_data.items(): + tags = form_data.pop('tags', []) + for tag in tags: + project.tags.add(tag) + for field, value in form_data.items(): + if field in extra_fields: setattr(project, field, value) basic_only = True project.save()
diff --git a/readthedocs/rtd_tests/tests/test_project_views.py b/readthedocs/rtd_tests/tests/test_project_views.py --- a/readthedocs/rtd_tests/tests/test_project_views.py +++ b/readthedocs/rtd_tests/tests/test_project_views.py @@ -116,6 +116,7 @@ def setUp(self): 'description': 'Describe foobar', 'language': 'en', 'documentation_type': 'sphinx', + 'tags': 'foo, bar, baz', } def test_form_pass(self): @@ -129,6 +130,11 @@ def test_form_pass(self): self.assertIsNotNone(proj) data = self.step_data['basics'] del data['advanced'] + del self.step_data['extra']['tags'] + self.assertItemsEqual( + [tag.name for tag in proj.tags.all()], + [u'bar', u'baz', u'foo'] + ) data.update(self.step_data['extra']) for (key, val) in data.items(): self.assertEqual(getattr(proj, key), val)
Tags are not saved when creating a new project ## Details - Project URL: N/A (affects all new projects) - Build URL (if applicable): N/A - Read the Docs username (if applicable): N/A ### Steps 1. Go to https://readthedocs.org/dashboard/import/manual 2. Select any project to import 3. Check the "Edit advanced project options" option 4. Enter the following in the `Tags` field: `foo, bar, foo bar` 5. Complete remaining required fields and submit the form ## Expected Result On https://readthedocs.org/projects/YOUR_PROJECT_NAME, three tags are listed: `foo`, `bar`, and `"foo bar"`. ## Actual Result No tags are listed. Tags appear after adding them again on: https://readthedocs.org/dashboard/YOUR_PROJECT_NAME/edit
2016-07-14T18:28:51
readthedocs/readthedocs.org
2,304
readthedocs__readthedocs.org-2304
[ "2210" ]
1e1e496f8971b2dd64822d09147aa63b8e318457
diff --git a/readthedocs/doc_builder/backends/mkdocs.py b/readthedocs/doc_builder/backends/mkdocs.py --- a/readthedocs/doc_builder/backends/mkdocs.py +++ b/readthedocs/doc_builder/backends/mkdocs.py @@ -58,7 +58,8 @@ def append_conf(self, **kwargs): # Mkdocs needs a full domain here because it tries to link to local media files if not media_url.startswith('http'): - media_url = 'http://localhost:8000' + media_url + domain = getattr(settings, 'PRODUCTION_DOMAIN') + media_url = 'http://{}/{}'.format(domain, media_url) if 'extra_javascript' in user_config: user_config['extra_javascript'].append('readthedocs-data.js')
MkDocs's media url shouldn't be hardcode with media_url = 'http://localhost:8000' + media_url In file `readthedocs.org/readthedocs/doc_builder/backends/mkdocs.py`: ``` python 55 # Set mkdocs config values 56 57 media_url = getattr(settings, 'MEDIA_URL', 'https://media.readthedocs.org') 58 59 # Mkdocs needs a full domain here because it tries to link to local media files 60 if not media_url.startswith('http'): 61 media_url = 'http://localhost:8000' + media_url ``` Can u please to replace it with `SITE_URL` as the follows: ``` python 59 # Mkdocs needs a full domain here because it tries to link to local media files 60 if not media_url.startswith('http'): 61 media_url = getattr(settings, 'SITE_URL', None) + media_url ```
The `MEDIA_URL` was defined in `readthedocs/settings/base.py` at line 169, ``` python 165 # Assets and media 166 STATIC_ROOT = os.path.join(SITE_ROOT, 'media/static/') 167 STATIC_URL = '/static/' 168 MEDIA_ROOT = os.path.join(SITE_ROOT, 'media/') 169 MEDIA_URL = '/media/' ``` However, in file `readthedocs/doc_builder/backends/mkdocs.py` at line 61, it appends `http://localhost:8000` as a prefix to the `media_url`, ``` python 55 # Set mkdocs config values 56 57 media_url = getattr(settings, 'MEDIA_URL', 'https://media.readthedocs.org') 58 59 # Mkdocs needs a full domain here because it tries to link to local media files 60 if not media_url.startswith('http'): 61 media_url = 'http://localhost:8000' + media_url ``` The hard coded domain should be replaced with `PRODUCTION_DOMAIN` setting, as a domain seems to be required here, as per the note above.
2016-07-14T18:48:49
readthedocs/readthedocs.org
2,308
readthedocs__readthedocs.org-2308
[ "1743" ]
1e1e496f8971b2dd64822d09147aa63b8e318457
diff --git a/readthedocs/projects/views/public.py b/readthedocs/projects/views/public.py --- a/readthedocs/projects/views/public.py +++ b/readthedocs/projects/views/public.py @@ -5,7 +5,6 @@ import json import logging import mimetypes -import md5 from django.core.urlresolvers import reverse from django.core.cache import cache @@ -106,20 +105,8 @@ def get_context_data(self, **kwargs): return context -def _badge_return(redirect, url): - if redirect: - return HttpResponseRedirect(url) - else: - response = requests.get(url) - http_response = HttpResponse(response.content, - content_type="image/svg+xml") - http_response['Cache-Control'] = 'no-cache' - http_response['Etag'] = md5.new(url) - return http_response - - @cache_control(no_cache=True) -def project_badge(request, project_slug, redirect=True): +def project_badge(request, project_slug): """Return a sweet badge for the project""" version_slug = request.GET.get('version', LATEST) style = request.GET.get('style', 'flat') @@ -130,13 +117,13 @@ def project_badge(request, project_slug, redirect=True): url = ( 'https://img.shields.io/badge/docs-unknown%20version-yellow.svg?style={style}' .format(style=style)) - return _badge_return(redirect, url) + return HttpResponseRedirect(url) version_builds = version.builds.filter(type='html', state='finished').order_by('-date') if not version_builds.exists(): url = ( 'https://img.shields.io/badge/docs-no%20builds-yellow.svg?style={style}' .format(style=style)) - return _badge_return(redirect, url) + return HttpResponseRedirect(url) last_build = version_builds[0] if last_build.success: color = 'brightgreen' @@ -144,7 +131,7 @@ def project_badge(request, project_slug, redirect=True): color = 'red' url = 'https://img.shields.io/badge/docs-%s-%s.svg?style=%s' % ( version.slug.replace('-', '--'), color, style) - return _badge_return(redirect, url) + return HttpResponseRedirect(url) def project_downloads(request, project_slug):
Etag + md5 question I'm playing with python3 conversion, and came across the following : I see that [here](https://github.com/rtfd/readthedocs.org/blob/f829ef0ebf93447318c93ff9ad45dfe7ed22ce98/readthedocs/projects/views/public.py#L117) the Etag is set to a `md5.new(url)` object. Shouldn't it be the `md5.new(url).hexdigest()` ? Or does django do some magic ? Thanks.
Perhaps -- It would be great to get a test for this showing it failing, and a patch that fixes it. Actually, it should use the `hashlib` module. `md5` has been deprecated since Python 2.5. However, it seems like the else branch in `_badge_return` is unused. `_badge_return` used by the `project_badge` view which passes `redirect=True` by default. I will open a pull request to simply it.
2016-07-14T21:19:17
readthedocs/readthedocs.org
2,319
readthedocs__readthedocs.org-2319
[ "2287" ]
db33973a4b5323d7ceda0b5fe2247c1b44221a64
diff --git a/readthedocs/core/resolver.py b/readthedocs/core/resolver.py --- a/readthedocs/core/resolver.py +++ b/readthedocs/core/resolver.py @@ -195,6 +195,9 @@ def _fix_filename(self, project, filename): path = "index.html#document-" + filename elif project.documentation_type in ["sphinx_htmldir", "mkdocs"]: path = filename + "/" + elif '#' in filename: + # do nothing if the filename contains URL fragments + path = filename else: path = filename + ".html" else:
diff --git a/readthedocs/rtd_tests/tests/test_redirects.py b/readthedocs/rtd_tests/tests/test_redirects.py --- a/readthedocs/rtd_tests/tests/test_redirects.py +++ b/readthedocs/rtd_tests/tests/test_redirects.py @@ -215,6 +215,36 @@ def test_redirect_htmldir(self): r['Location'], 'http://pip.readthedocs.org/en/latest/faq/') +class CustomRedirectTests(TestCase): + + @classmethod + def setUpTestData(cls): + cls.pip = Project.objects.create(**{ + 'repo_type': 'git', + 'name': 'Pip', + 'default_branch': '', + 'project_url': 'http://pip.rtfd.org', + 'repo': 'https://github.com/fail/sauce', + 'default_version': LATEST, + 'privacy_level': 'public', + 'version_privacy_level': 'public', + 'description': 'wat', + 'documentation_type': 'sphinx', + }) + Redirect.objects.create( + project=cls.pip, + redirect_type='page', + from_url='/install.html', + to_url='/install.html#custom-fragment', + ) + + def test_redirect_fragment(self): + redirect = Redirect.objects.get(project=self.pip) + path = redirect.get_redirect_path('/install.html') + expected_path = '/docs/pip/en/latest/install.html#custom-fragment' + self.assertEqual(path, expected_path) + + @override_settings(PUBLIC_DOMAIN='readthedocs.org', USE_SUBDOMAIN=False) class RedirectBuildTests(TestCase): fixtures = ["eric", "test_data"]
Page redirects incorrectly append .html to redirected URLs containing fragments ## Details - Project URL: urllib3.readthedocs.io - Build URL (if applicable): Any - Read the Docs username (if applicable): Lukasa ## Action Taken In settings, I configured a page redirect: `Page Redirect: /security.html -> /advanced-usage.html#ssl-warnings`. ## Expected Result When visiting https://urllib3.readthedocs.io/en/latest/security.html, I expect to be redirected to https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings. ## Actual Result When visiting https://urllib3.readthedocs.io/en/latest/security.html, I am redirected to https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings.html (note the extra HTML). I suspect this is just a misbehaving convenience feature: RTD is spotting that the URL doesn't end in `.html` and is helpfully adding it for me, even though it's syntactically not in the right place. I think this change requires URL parsing the target URL and confirming that the _path_ ends in `.html`, and then restoring the fragment (if present).
2016-07-18T13:35:52
readthedocs/readthedocs.org
2,332
readthedocs__readthedocs.org-2332
[ "2299" ]
b31c8952d6c0665e3330b39f434a3ce5372e19ac
diff --git a/readthedocs/core/utils/__init__.py b/readthedocs/core/utils/__init__.py --- a/readthedocs/core/utils/__init__.py +++ b/readthedocs/core/utils/__init__.py @@ -7,6 +7,7 @@ from django.conf import settings from readthedocs.builds.constants import LATEST +from readthedocs.doc_builder.constants import DOCKER_LIMITS from ..tasks import send_email_task @@ -102,6 +103,18 @@ def trigger_build(project, version=None, record=True, force=False, basic=False): if project.build_queue: options['queue'] = project.build_queue + # Set per-task time limit + time_limit = DOCKER_LIMITS['time'] + try: + if project.container_time_limit: + time_limit = int(project.container_time_limit) + except ValueError: + pass + # Add 20% overhead to task, to ensure the build can timeout and the task + # will cleanly finish. + options['soft_time_limit'] = time_limit + options['time_limit'] = int(time_limit * 1.2) + update_docs.apply_async(kwargs=kwargs, **options) return build
diff --git a/readthedocs/rtd_tests/tests/test_core_utils.py b/readthedocs/rtd_tests/tests/test_core_utils.py new file mode 100644 --- /dev/null +++ b/readthedocs/rtd_tests/tests/test_core_utils.py @@ -0,0 +1,80 @@ +"""Test core util functions""" + +import mock + +from django_dynamic_fixture import get +from django.test import TestCase +from django.test.utils import override_settings + +from readthedocs.projects.models import Project +from readthedocs.builds.models import Version +from readthedocs.core.utils import trigger_build + + +class CoreUtilTests(TestCase): + + def setUp(self): + self.project = get(Project, container_time_limit=None) + self.version = get(Version, project=self.project) + + @mock.patch('readthedocs.projects.tasks.update_docs') + def test_trigger_build_time_limit(self, update_docs): + """Pass of time limit""" + trigger_build(project=self.project, version=self.version) + update_docs.assert_has_calls([ + mock.call.apply_async( + time_limit=720, + soft_time_limit=600, + queue=mock.ANY, + kwargs={ + 'pk': self.project.id, + 'force': False, + 'basic': False, + 'record': True, + 'build_pk': mock.ANY, + 'version_pk': self.version.id + } + ) + ]) + + @mock.patch('readthedocs.projects.tasks.update_docs') + def test_trigger_build_invalid_time_limit(self, update_docs): + """Time limit as string""" + self.project.container_time_limit = '200s' + trigger_build(project=self.project, version=self.version) + update_docs.assert_has_calls([ + mock.call.apply_async( + time_limit=720, + soft_time_limit=600, + queue=mock.ANY, + kwargs={ + 'pk': self.project.id, + 'force': False, + 'basic': False, + 'record': True, + 'build_pk': mock.ANY, + 'version_pk': self.version.id + } + ) + ]) + + @mock.patch('readthedocs.projects.tasks.update_docs') + def test_trigger_build_rounded_time_limit(self, update_docs): + """Time limit should round down""" + self.project.container_time_limit = 3 + trigger_build(project=self.project, version=self.version) + update_docs.assert_has_calls([ + mock.call.apply_async( + time_limit=3, + soft_time_limit=3, + queue=mock.ANY, + kwargs={ + 'pk': self.project.id, + 'force': False, + 'basic': False, + 'record': True, + 'build_pk': mock.ANY, + 'version_pk': self.version.id + } + ) + ])
Task for update_docs can timeout apparently Stack trace: ``` Jul 13 18:43:51 build02 readthedocs/celery.worker.job[11229]: ERROR Task update_docs[12609cdb-ee39-45f2-b3a6-616a1a920c3c] raised unexpected: TimeLimitExceeded(3600,) [celery.worker.job:282] Traceback (most recent call last): File "/home/docs/local/lib/python2.7/site-packages/billiard/pool.py", line 641, in on_hard_timeout raise TimeLimitExceeded(job._timeout) TimeLimitExceeded: TimeLimitExceeded(3600,) Jul 13 18:43:51 build02 readthedocs/celery.worker.job[11229]: ERROR Hard time limit (3600s) exceeded for update_docs[12609cdb-ee39-45f2-b3a6-616a1a920c3c] [celery.worker.job:368] ``` This should instead report a failure on the build, not just die. When the celery process is killed, the lock stays around, user is not notified of failure, and the build stays in "Building" state.
This is a celery setting that we have set. We can remove it or raise it if we don't think this is an issue now that we have the Docker time-limiting in place. Yeah, the reason for termination is clear. We'll want to do this as an argument to calling the task, as the value of Docker time limit changes with projects.
2016-07-23T00:21:30
readthedocs/readthedocs.org
2,368
readthedocs__readthedocs.org-2368
[ "173", "173" ]
ef40e223a7f68e3b81176dc9bf4acc56bba855e8
diff --git a/readthedocs/doc_builder/config.py b/readthedocs/doc_builder/config.py --- a/readthedocs/doc_builder/config.py +++ b/readthedocs/doc_builder/config.py @@ -39,6 +39,14 @@ def install_project(self): else: return self._project.install_project + @property + def extra_requirements(self): + if self.pip_install and 'extra_requirements' in self._yaml_config.get( + 'python', {}): + return self._yaml_config['python']['extra_requirements'] + else: + return [] + @property def python_interpreter(self): if 'version' in self._yaml_config.get('python', {}): diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -44,6 +44,10 @@ def install_package(self): setup_path = os.path.join(self.checkout_path, 'setup.py') if os.path.isfile(setup_path) and self.config.install_project: if self.config.pip_install or getattr(settings, 'USE_PIP_INSTALL', False): + extra_req_param = '' + if self.config.extra_requirements: + extra_req_param = '[{0}]'.format( + ','.join(self.config.extra_requirements)) self.build_env.run( 'python', self.venv_bin(filename='pip'), @@ -51,7 +55,7 @@ def install_package(self): '--ignore-installed', '--cache-dir', self.project.pip_cache_path, - '.', + '.{0}'.format(extra_req_param), cwd=self.checkout_path, bin_path=self.venv_bin() )
diff --git a/readthedocs/rtd_tests/tests/test_config_wrapper.py b/readthedocs/rtd_tests/tests/test_config_wrapper.py --- a/readthedocs/rtd_tests/tests/test_config_wrapper.py +++ b/readthedocs/rtd_tests/tests/test_config_wrapper.py @@ -55,6 +55,28 @@ def test_install_project(self): config = ConfigWrapper(version=self.version, yaml_config=yaml_config) self.assertEqual(config.install_project, False) + def test_extra_requirements(self): + yaml_config = get_build_config({'python': { + 'pip_install': True, + 'extra_requirements': ['tests', 'docs']}}) + config = ConfigWrapper(version=self.version, yaml_config=yaml_config) + self.assertEqual(config.extra_requirements, ['tests', 'docs']) + + yaml_config = get_build_config({'python': { + 'extra_requirements': ['tests', 'docs']}}) + config = ConfigWrapper(version=self.version, yaml_config=yaml_config) + self.assertEqual(config.extra_requirements, []) + + yaml_config = get_build_config({}) + config = ConfigWrapper(version=self.version, yaml_config=yaml_config) + self.assertEqual(config.extra_requirements, []) + + yaml_config = get_build_config({'python': { + 'setup_py_install': True, + 'extra_requirements': ['tests', 'docs']}}) + config = ConfigWrapper(version=self.version, yaml_config=yaml_config) + self.assertEqual(config.extra_requirements, []) + def test_conda(self): to_find = 'urls.py' yaml_config = get_build_config({'conda': {'file': to_find}})
Support setuptools/distribute extras dependencies For example, I have in one of my projects: ``` extras_require={ 'test': ['webtest', 'nose', 'coverage'], 'develop': ['bpython', 'z3c.checkversions [buildout]'], }, ``` For API documentation, 'test' packages need to be installed, would be nice if rtd supported this feature :) Support setuptools/distribute extras dependencies For example, I have in one of my projects: ``` extras_require={ 'test': ['webtest', 'nose', 'coverage'], 'develop': ['bpython', 'z3c.checkversions [buildout]'], }, ``` For API documentation, 'test' packages need to be installed, would be nice if rtd supported this feature :)
Is there a concept of documentation as a key here? I don't think it makes sense to install necessarily the test dependencies, but if there is one for creating the documentation, I would get behind that. Extras can be anything. Some people do like to put 'docs' extras, where they enumerate all dependencies needed to be installed for documentation generation. Closing this for now. I don't really see how it makes sense for RTD to support. If there was some kind of standard for "things I need to install to build docs", we could support that. Something in distribute, or a documentation_requirements.txt in the top-level or requirements/documentation.txt for pip. RTD might be able to take the lead in adding that, but this ticket doesn't really mean that. So feel free to re-open with a proposal for something awesome like that :) I would like to reopen this issue for discussion. Using setuptools and specifying `extras_require` has become pretty standard. Pip supports installing these extras using ``` sh pip install project\[docs,other,extra\] ``` Using `extras_require` instead of requirements prevent cluttering the root directory of a project. Since a requirements file can already be specified for RTD, I think 'extras' can be specified just as easy. Hello from the future! I agree with @remcohaszing, `extras_require` is the standard approach, can someone from rtfd reopen this issue? What do you want to be able to do that you can't do now? Can't you just specify the extras_require in your requirements file? hi @ericholscher! Instead of `requirements.txt`, I'd like to use my `setup.py` to specify dependencies to build the docs. Right now in our project we have duplication between [`setup.py`](https://github.com/bigchaindb/bigchaindb/blob/develop/setup.py#L25) and [`requirements.txt`](https://github.com/bigchaindb/bigchaindb/blob/develop/docs/requirements.txt). Yes, it's not duplicated anymore if we remove the dependencies from `setup.py`, but I really like the idea to keep everything in a single place. In the advanced settings I can only set the path to the `requirements.txt`, but it'd be a nice idea to support also dependencies specified in `extras_require`. ![image](https://cloud.githubusercontent.com/assets/134680/13524404/4628f608-e1fb-11e5-87b7-3e50ca108bca.png) I'm going to reopen this. I think stronger integration with `setup.py` would be a good thing for module maintainers, and other folks that have no other need for requirements files. This functionality likely won't make it into project options, but would be a good addition to our `readthedocs.yaml` and https://github.com/rtfd/readthedocs-build Leaving it open here for now, though it will likely require work in multiple repos. If anyone wants to tackle this, there is some previous work adding similar options to the yaml spec here and in readthedocs-build. I'm not a fan of the setuptools extensions of setup.py but it would be nice to see `pip install -e .` being used as this will pickup any dependencies required where `python setup.py install` will not. :-( Is there a concept of documentation as a key here? I don't think it makes sense to install necessarily the test dependencies, but if there is one for creating the documentation, I would get behind that. Extras can be anything. Some people do like to put 'docs' extras, where they enumerate all dependencies needed to be installed for documentation generation. Closing this for now. I don't really see how it makes sense for RTD to support. If there was some kind of standard for "things I need to install to build docs", we could support that. Something in distribute, or a documentation_requirements.txt in the top-level or requirements/documentation.txt for pip. RTD might be able to take the lead in adding that, but this ticket doesn't really mean that. So feel free to re-open with a proposal for something awesome like that :) I would like to reopen this issue for discussion. Using setuptools and specifying `extras_require` has become pretty standard. Pip supports installing these extras using ``` sh pip install project\[docs,other,extra\] ``` Using `extras_require` instead of requirements prevent cluttering the root directory of a project. Since a requirements file can already be specified for RTD, I think 'extras' can be specified just as easy. Hello from the future! I agree with @remcohaszing, `extras_require` is the standard approach, can someone from rtfd reopen this issue? What do you want to be able to do that you can't do now? Can't you just specify the extras_require in your requirements file? hi @ericholscher! Instead of `requirements.txt`, I'd like to use my `setup.py` to specify dependencies to build the docs. Right now in our project we have duplication between [`setup.py`](https://github.com/bigchaindb/bigchaindb/blob/develop/setup.py#L25) and [`requirements.txt`](https://github.com/bigchaindb/bigchaindb/blob/develop/docs/requirements.txt). Yes, it's not duplicated anymore if we remove the dependencies from `setup.py`, but I really like the idea to keep everything in a single place. In the advanced settings I can only set the path to the `requirements.txt`, but it'd be a nice idea to support also dependencies specified in `extras_require`. ![image](https://cloud.githubusercontent.com/assets/134680/13524404/4628f608-e1fb-11e5-87b7-3e50ca108bca.png) I'm going to reopen this. I think stronger integration with `setup.py` would be a good thing for module maintainers, and other folks that have no other need for requirements files. This functionality likely won't make it into project options, but would be a good addition to our `readthedocs.yaml` and https://github.com/rtfd/readthedocs-build Leaving it open here for now, though it will likely require work in multiple repos. If anyone wants to tackle this, there is some previous work adding similar options to the yaml spec here and in readthedocs-build. I'm not a fan of the setuptools extensions of setup.py but it would be nice to see `pip install -e .` being used as this will pickup any dependencies required where `python setup.py install` will not. :-(
2016-08-16T21:22:40
readthedocs/readthedocs.org
2,455
readthedocs__readthedocs.org-2455
[ "2442" ]
322140fa2e8aba581b9baf005893f8f4e9ad61cf
diff --git a/readthedocs/core/adapters.py b/readthedocs/core/adapters.py --- a/readthedocs/core/adapters.py +++ b/readthedocs/core/adapters.py @@ -1,5 +1,8 @@ """Allauth overrides""" +import pickle +import logging + from allauth.account.adapter import DefaultAccountAdapter from django.template.loader import render_to_string @@ -10,6 +13,8 @@ except ImportError: from django.utils.encoding import force_unicode as force_text +log = logging.getLogger(__name__) + class AccountAdapter(DefaultAccountAdapter): @@ -25,6 +30,19 @@ def send_mail(self, template_prefix, email, context): subject = " ".join(subject.splitlines()).strip() subject = self.format_email_subject(subject) + # Allauth sends some additional data in the context, remove it if the + # pieces can't be pickled + removed_keys = [] + for key in context.keys(): + try: + _ = pickle.dumps(context[key]) + except pickle.PickleError: + removed_keys.append(key) + del context[key] + if removed_keys: + log.debug('Removed context we were unable to serialize: %s', + removed_keys) + send_email( recipient=email, subject=subject,
Document support of .readthedocs.yml see rtfd/readthedocs-build#17
2016-10-12T17:52:00
readthedocs/readthedocs.org
2,501
readthedocs__readthedocs.org-2501
[ "2498", "2499" ]
64cd0d9c2eb22d4a4ed1566c2b88ef8eeb001673
diff --git a/readthedocs/builds/filters.py b/readthedocs/builds/filters.py --- a/readthedocs/builds/filters.py +++ b/readthedocs/builds/filters.py @@ -27,9 +27,9 @@ class VersionFilter(django_filters.FilterSet): project = django_filters.CharFilter(name='project__slug') # Allow filtering on slug= or version= slug = django_filters.CharFilter(label=_("Name"), name='slug', - lookup_type='exact') + lookup_expr='exact') version = django_filters.CharFilter(label=_("Version"), name='slug', - lookup_type='exact') + lookup_expr='exact') class Meta: model = Version @@ -37,7 +37,7 @@ class Meta: class BuildFilter(django_filters.FilterSet): - date = django_filters.DateRangeFilter(label=_("Build Date"), name="date", lookup_type='range') + date = django_filters.DateRangeFilter(label=_("Build Date"), name="date", lookup_expr='range') type = django_filters.ChoiceFilter(label=_("Build Type"), choices=BUILD_TYPES) diff --git a/readthedocs/projects/filters.py b/readthedocs/projects/filters.py --- a/readthedocs/projects/filters.py +++ b/readthedocs/projects/filters.py @@ -44,17 +44,17 @@ class ProjectFilter(django_filters.FilterSet): """Project filter for filter views""" name = django_filters.CharFilter(label=_("Name"), name='name', - lookup_type='icontains') + lookup_expr='icontains') slug = django_filters.CharFilter(label=_("Slug"), name='slug', - lookup_type='icontains') + lookup_expr='icontains') pub_date = django_filters.DateRangeFilter(label=_("Created Date"), name="pub_date") repo = django_filters.CharFilter(label=_("Repository URL"), name='repo', - lookup_type='icontains') + lookup_expr='icontains') repo_type = django_filters.ChoiceFilter( label=_("Repository Type"), name='repo', - lookup_type='icontains', + lookup_expr='icontains', choices=REPO_CHOICES, ) @@ -65,7 +65,7 @@ class Meta: class DomainFilter(django_filters.FilterSet): project = django_filters.CharFilter(label=_("Project"), name='project__slug', - lookup_type='exact') + lookup_expr='exact') class Meta: model = Domain
Update django-filter to 1.0 ## Details Sorry for deleting the issue template: This is about technical debt :) It may not be immediately critical, but the advice from the author of django-filter is that it's worth it. django-filter 1.0 has changes that are backwards incompatible. The release notes are here: http://django-filter.readthedocs.io/en/latest/migration.html It means, amongst other this, that all where `Filter` object instances are iterated on, we have to [add the `.qs` method](http://django-filter.readthedocs.io/en/latest/migration.html#queryset-methods-are-no-longer-proxied). Pin django-filter The new 1.0 series is incompatible, and I've opened #2498 for this purpose. Meanwhile, as the current master is broken because of this, the version should be pinned - I guess it's sort of bad practice to use the `master` branch anyways, am thinking it's possibly also an outdated decision now. This fixes #2495 and #2490
Hi @benjaoming - I'm partly to blame for the API breakage 😅. Feel free to ping me if you have any questions about the changes. @rpkilby - thanks! it's a major version bump and with a nice migration guide so it's all in good order I guess :) I've opened the issue, hoping that someone who knows the codebase well is going to do the refactor.. I'm shying away here.
2016-11-14T15:29:35
readthedocs/readthedocs.org
2,712
readthedocs__readthedocs.org-2712
[ "2583" ]
cf4f8ff1e9c034d12bc7b2ccdbd545b711abc409
diff --git a/docs/conf.py b/docs/conf.py --- a/docs/conf.py +++ b/docs/conf.py @@ -32,7 +32,7 @@ master_doc = 'index' project = u'Read The Docs' -copyright = u'2010, Eric Holscher, Charlie Leifer, Bobby Grace' +copyright = u'2010-2017, Read the Docs, Inc & contributors' version = '1.0' release = '1.0' exclude_patterns = ['_build']
Document that RTD uses `rel` branch for production Hi, i'd like to add a new builder for doxygen documentation (but native, not with breath). Since there are a lot of branches like real/relcorp which a far ahead of master, i'd like to know, which branch to choose for development. Thanks in advance! Oli
Thanks for your interest. We likely wouldn't include a doxygen builder in code, but we'd be happy to make it easy to implement as a third party builder, with a good API in RTD. We'd also be happy to list the extension in our docs! :) The main site is deployed from `rel`, which shouldn't be ahead of `master`. Note that there are a few sphinx extensions for integrating doxygen content, notably https://github.com/michaeljones/breathe, you might want to check that out before starting from scratch. Should I close this issue? The original question was answered (regarding to the branch) :grin: Do you want to continue the discussion about how to do/implement it here? If so, we should change the title of the issue since it will be confusing. We should probably document how we do deployments and that the `rel` branch is in production.
2017-03-09T22:50:25
readthedocs/readthedocs.org
2,721
readthedocs__readthedocs.org-2721
[ "2720" ]
bb36f34d4cab7b9f37869b30c01912c4af45a1e3
diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -103,7 +103,7 @@ def setup_base(self): def install_core_requirements(self): requirements = [ 'sphinx==1.5.3', - 'Pygments==2.1.3', + 'Pygments==2.2.0', 'setuptools==28.8.0', 'docutils==0.13.1', 'mkdocs==0.15.0', @@ -194,7 +194,7 @@ def install_core_requirements(self): # Use conda for requirements it packages requirements = [ 'sphinx==1.3.5', - 'Pygments==2.1.1', + 'Pygments==2.2.0', 'docutils==0.12', 'mock', 'pillow==3.0.0',
Support latest Pygments (for improved Haskell syntax, and more) ### Change Requested The use of `Pygments==2.2.0` (or newer, potentially) to highlight code. ### Background As part of a [syntax highlighting problem noted on Haskell-Servant](https://github.com/haskell-servant/servant/issues/359), @teh pushed a [PR for Pygments](https://bitbucket.org/birkenfeld/pygments-main/pull-requests/685/two-haskell-fixes/diff) that was merged a while ago. I've submitted [a Pygments dependency bump in the Servant codebase](https://github.com/haskell-servant/servant/compare/master...declension:359-upgrade-pygments) which works locally, but as we use https://readthedocs.org for actually hosting, it won't help solve the real problem unless Pygments is upgraded here too...
2017-03-12T11:56:18
readthedocs/readthedocs.org
2,779
readthedocs__readthedocs.org-2779
[ "2778" ]
1bb7e07b733aa0898b6b03e2feebc6175bf58eaa
diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -197,7 +197,7 @@ def install_core_requirements(self): 'Pygments==2.2.0', 'docutils==0.12', 'mock', - 'pillow==3.0.0', + 'pillow>=3.0.0', 'sphinx_rtd_theme==0.1.7', 'alabaster>=0.7,<0.8,!=0.7.5', ]
Update conda requirements for Pillow ## Details * Project URL: https://readthedocs.org/projects/jupyterhub/ * Build URL (if applicable): https://readthedocs.org/projects/jupyterhub/builds/5242702/ * Read the Docs username (if applicable): willingc ## Expected Result I didn't expect the stable/0.7.2 docs to build. If they did run, I expected the docs to build without failing. ## Actual Result Build is failing since Pillow 3.0.0 is not compatible with Python 3.6. I'm not sure what triggered the build for JupyterHub stable/0.7.2 docs. I triggered the last failure but the other two just appeared :bat: 👻 My recommendation would be allow Pillow to float >=3.0.0 for conda builds to prevent mismatches when there is a newer Python release like 3.6. Happy to submit the PR if needed.
2017-04-03T22:12:21
readthedocs/readthedocs.org
2,787
readthedocs__readthedocs.org-2787
[ "2731" ]
1af444173481df9a7b16e015fc6b12abe8155e7e
diff --git a/readthedocs/core/views/serve.py b/readthedocs/core/views/serve.py --- a/readthedocs/core/views/serve.py +++ b/readthedocs/core/views/serve.py @@ -34,7 +34,8 @@ from functools import wraps from django.conf import settings -from django.http import Http404, HttpResponse, HttpResponseRedirect +from django.http import HttpResponse, HttpResponseRedirect, Http404 +from django.shortcuts import get_object_or_404 from django.shortcuts import render from django.views.static import serve @@ -60,18 +61,17 @@ def map_subproject_slug(view_func): def inner_view( request, subproject=None, subproject_slug=None, *args, **kwargs): if subproject is None and subproject_slug: + # Try to fetch by subproject alias first, otherwise we might end up + # redirected to an unrelated project. try: - subproject = Project.objects.get(slug=subproject_slug) - except Project.DoesNotExist: - try: - # Depends on a project passed into kwargs - rel = ProjectRelationship.objects.get( - parent=kwargs['project'], - alias=subproject_slug, - ) - subproject = rel.child - except (ProjectRelationship.DoesNotExist, KeyError): - raise Http404 + # Depends on a project passed into kwargs + rel = ProjectRelationship.objects.get( + parent=kwargs['project'], + alias=subproject_slug, + ) + subproject = rel.child + except (ProjectRelationship.DoesNotExist, KeyError): + get_object_or_404(Project, slug=subproject_slug) return view_func(request, subproject=subproject, *args, **kwargs) return inner_view
diff --git a/readthedocs/rtd_tests/tests/test_resolver.py b/readthedocs/rtd_tests/tests/test_resolver.py --- a/readthedocs/rtd_tests/tests/test_resolver.py +++ b/readthedocs/rtd_tests/tests/test_resolver.py @@ -385,3 +385,32 @@ def test_resolver_public_domain_overrides(self): self.assertEqual(url, 'http://docs.foobar.com/en/latest/') url = resolve(project=self.pip, private=False) self.assertEqual(url, 'http://docs.foobar.com/en/latest/') + + +class ResolverAltSetUp(object): + + def setUp(self): + with mock.patch('readthedocs.projects.models.broadcast'): + self.owner = create_user(username='owner', password='test') + self.tester = create_user(username='tester', password='test') + self.pip = get(Project, slug='pip', users=[self.owner], main_language_project=None) + self.seed = get(Project, slug='sub', users=[self.owner], main_language_project=None) + self.subproject = get(Project, slug='subproject', language='ja', users=[self.owner], main_language_project=None) + self.translation = get(Project, slug='trans', language='ja', users=[self.owner], main_language_project=None) + self.pip.add_subproject(self.subproject, alias='sub') + self.pip.translations.add(self.translation) + + +@override_settings(PUBLIC_DOMAIN='readthedocs.org') +class ResolverDomainTestsAlt(ResolverAltSetUp, ResolverDomainTests): + pass + + +@override_settings(PUBLIC_DOMAIN='readthedocs.org') +class SmartResolverPathTestsAlt(ResolverAltSetUp, SmartResolverPathTests): + pass + + +@override_settings(PUBLIC_DOMAIN='readthedocs.org') +class ResolverTestsAlt(ResolverAltSetUp, ResolverTests): + pass diff --git a/readthedocs/rtd_tests/tests/test_subprojects.py b/readthedocs/rtd_tests/tests/test_subprojects.py --- a/readthedocs/rtd_tests/tests/test_subprojects.py +++ b/readthedocs/rtd_tests/tests/test_subprojects.py @@ -161,15 +161,29 @@ def setUp(self): self.pip.add_subproject(self.subproject) self.pip.translations.add(self.translation) - @override_settings(PRODUCTION_DOMAIN='readthedocs.org') - def test_resolver_subproject_alias(self): relation = self.pip.subprojects.first() relation.alias = 'sub_alias' relation.save() - with override_settings(USE_SUBDOMAIN=False): - resp = self.client.get('/docs/pip/projects/sub_alias/') - self.assertEqual(resp.status_code, 302) - self.assertEqual( - resp._headers['location'][1], - 'http://readthedocs.org/docs/pip/projects/sub_alias/ja/latest/' + fixture.get(Project, slug='sub_alias', language='ya') + + + @override_settings( + PRODUCTION_DOMAIN='readthedocs.org', + USE_SUBDOMAIN=False, ) + def test_resolver_subproject_alias(self): + resp = self.client.get('/docs/pip/projects/sub_alias/') + self.assertEqual(resp.status_code, 302) + self.assertEqual( + resp._headers['location'][1], + 'http://readthedocs.org/docs/pip/projects/sub_alias/ja/latest/' + ) + + @override_settings(USE_SUBDOMAIN=True) + def test_resolver_subproject_subdomain_alias(self): + resp = self.client.get('/projects/sub_alias/', HTTP_HOST='pip.readthedocs.org') + self.assertEqual(resp.status_code, 302) + self.assertEqual( + resp._headers['location'][1], + 'http://pip.readthedocs.org/projects/sub_alias/ja/latest/' + )
subproject alias 302 redirect to top-level project sharing alias' name ## Details I have set up a subproject, Subproject: cloudify-openstack-plugin-fh Alias: openstack * Project URL: http://cfy-rtd-demo.readthedocs.io/ * Build URL (if applicable): https://readthedocs.org/projects/cfy-rtd-demo/builds/5162299/ * Read the Docs username (if applicable): funkyhat ## Expected Result When navigating to http://cfy-rtd-demo.readthedocs.io/projects/openstack I expect to see (presumably via a redirect to http://cfy-rtd-demo.readthedocs.io/projects/openstack/en/sphinxify-rtd-demo/) my subproject's docs (`sphinxify-rtd-demo` is the current "active branch" for the subproject). ## Actual Result I am redirected to http://openstack.readthedocs.io/en/latest/ which is unrelated to my project: ``` < HTTP/1.1 302 Found * Server nginx/1.10.0 (Ubuntu) is not blacklisted < Server: nginx/1.10.0 (Ubuntu) < Date: Fri, 17 Mar 2017 13:00:04 GMT < Content-Type: text/html; charset=utf-8 < Transfer-Encoding: chunked < Connection: keep-alive < Vary: Accept-Language, Cookie < Location: http://openstack.readthedocs.io/en/latest/ < Content-Language: en < X-Fallback: True < X-Served: Django < X-Deity: web03 ``` I have tried rebuilding the main project, which produced no change. This seems potentially related to #1602
2017-04-10T14:04:51
readthedocs/readthedocs.org
2,859
readthedocs__readthedocs.org-2859
[ "2851" ]
8996546410a6569b468c47096d92eeb491dba1fd
diff --git a/readthedocs/settings/base.py b/readthedocs/settings/base.py --- a/readthedocs/settings/base.py +++ b/readthedocs/settings/base.py @@ -333,132 +333,39 @@ def INSTALLED_APPS(self): # noqa SILENCED_SYSTEM_CHECKS = ['fields.W342'] # Logging - LOG_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s" + LOG_FORMAT = '%(name)s:%(lineno)s[%(process)d]: %(levelname)s %(message)s' LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { - 'standard': { + 'default': { 'format': LOG_FORMAT, - 'datefmt': "%d/%b/%Y %H:%M:%S" + 'datefmt': '%d/%b/%Y %H:%M:%S', }, }, - 'filters': { - 'require_debug_false': { - '()': 'django.utils.log.RequireDebugFalse' - } - }, 'handlers': { - 'null': { - 'level': 'DEBUG', - 'class': 'logging.NullHandler', - }, - 'exceptionlog': { - 'level': 'DEBUG', - 'class': 'logging.handlers.RotatingFileHandler', - 'filename': os.path.join(LOGS_ROOT, "exceptions.log"), - 'formatter': 'standard', - }, - 'errorlog': { + 'console': { 'level': 'INFO', - 'class': 'logging.handlers.RotatingFileHandler', - 'filename': os.path.join(LOGS_ROOT, "rtd.log"), - 'formatter': 'standard', - }, - 'postcommit': { - 'level': 'DEBUG', - 'class': 'logging.handlers.RotatingFileHandler', - 'filename': os.path.join(LOGS_ROOT, "postcommit.log"), - 'formatter': 'standard', - }, - 'middleware': { - 'level': 'DEBUG', - 'class': 'logging.handlers.RotatingFileHandler', - 'filename': os.path.join(LOGS_ROOT, "middleware.log"), - 'formatter': 'standard', + 'class': 'logging.StreamHandler', + 'formatter': 'default' }, - 'restapi': { + 'debug': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', - 'filename': os.path.join(LOGS_ROOT, "api.log"), - 'formatter': 'standard', - }, - 'db': { - 'level': 'INFO', - 'class': 'logging.handlers.RotatingFileHandler', - 'filename': os.path.join(LOGS_ROOT, "db.log"), - 'formatter': 'standard', - }, - 'search': { - 'level': 'INFO', - 'class': 'logging.handlers.RotatingFileHandler', - 'filename': os.path.join(LOGS_ROOT, "search.log"), - 'formatter': 'standard', - }, - 'mail_admins': { - 'level': 'ERROR', - 'filters': ['require_debug_false'], - 'class': 'django.utils.log.AdminEmailHandler', - }, - 'console': { - 'level': ('INFO', 'DEBUG')[DEBUG], - 'class': 'logging.StreamHandler', - 'formatter': 'standard' + 'filename': 'debug.log', + 'formatter': 'default', }, }, 'loggers': { - 'django': { - 'handlers': ['console', 'errorlog'], - 'propagate': True, - 'level': 'WARN', - }, - 'django.db.backends': { - 'handlers': ['db'], - 'level': 'DEBUG', - 'propagate': False, - }, - 'readthedocs.core.views.post_commit': { - 'handlers': ['postcommit'], - 'level': 'DEBUG', - 'propagate': False, - }, - 'core.middleware': { - 'handlers': ['middleware'], - 'level': 'DEBUG', - 'propagate': False, - }, - 'restapi': { - 'handlers': ['restapi'], + 'readthedocs': { + 'handlers': ['debug', 'console'], 'level': 'DEBUG', - 'propagate': False, - }, - 'django.request': { - 'handlers': ['exceptionlog'], - 'level': 'ERROR', - 'propagate': False, - }, - 'readthedocs.projects.views.public.search': { - 'handlers': ['search'], - 'level': 'DEBUG', - 'propagate': False, - }, - 'search': { - 'handlers': ['search'], - 'level': 'DEBUG', - 'propagate': False, + 'propagate': True, }, - # Uncomment if you want to see Elasticsearch queries in the console. - # 'elasticsearch.trace': { - # 'level': 'DEBUG', - # 'handlers': ['console'], - # }, - - # Default handler for everything that we're doing. Hopefully this - # doesn't double-print the Django things as well. Not 100% sure how - # logging works :) '': { - 'handlers': ['console', 'errorlog'], - 'level': 'INFO', + 'handlers': ['debug', 'console'], + 'level': 'DEBUG', + 'propagate': True, }, - } + }, } diff --git a/readthedocs/settings/dev.py b/readthedocs/settings/dev.py --- a/readthedocs/settings/dev.py +++ b/readthedocs/settings/dev.py @@ -51,6 +51,12 @@ def DATABASES(self): # noqa 'test:8000', ) + @property + def LOGGING(self): # noqa - avoid pep8 N802 + logging = super(CommunityDevSettings, self).LOGGING + logging['formatters']['default']['format'] = '[%(asctime)s] ' + self.LOG_FORMAT + return logging + CommunityDevSettings.load_settings(__name__)
Add datetime to LOG_FORMAT With the new branch (https://github.com/rtfd/readthedocs.org/blob/fix-logging/readthedocs/settings/base.py#L336) we have a very good logging shine and working, but it's missing the datetime. ``` readthedocs.doc_builder.environments[31528]: INFO (Build) [tornado:latest] Build finished [readthedocs.doc_builder.environments:540] readthedocs.core.views.hooks[31528]: INFO (Version build) Building tornado:latest [readthedocs.core.views.hooks:55] readthedocs.core.views.hooks[31528]: INFO (Version build) Building tornado:latest [readthedocs.core.views.hooks:55] readthedocs.api.client[32396]: DEBUG Using slumber with user test, pointed at http://localhost:8000 [readthedocs.api.client:24] readthedocs.api.client[32396]: DEBUG Using slumber with user test, pointed at http://localhost:8000 [readthedocs.api.client:24] readthedocs.restapi.client[32396]: DEBUG Using slumber v2 with user test, pointed at http://localhost:8000 [readthedocs.restapi.client:46] readthedocs.restapi.client[32396]: DEBUG Using slumber v2 with user test, pointed at http://localhost:8000 [readthedocs.restapi.client:46] ``` So, I suggest to change it to something like this to include the datetime and remove the duplcated `(name)s`: %(asctime)s - [%(name)s:%(lineno)s][%(process)d]: %(levelname)s %(message)s @agjohnson we should probably add this to your branch.
2017-05-21T22:32:56
readthedocs/readthedocs.org
2,880
readthedocs__readthedocs.org-2880
[ "2618", "2618" ]
e2124b46847f7311edc7ba239c5738bad3936e0f
diff --git a/readthedocs/oauth/services/__init__.py b/readthedocs/oauth/services/__init__.py --- a/readthedocs/oauth/services/__init__.py +++ b/readthedocs/oauth/services/__init__.py @@ -1,13 +1,17 @@ """Conditional classes for OAuth services""" -from django.utils.module_loading import import_string -from django.conf import settings - -GitHubService = import_string( - getattr(settings, 'OAUTH_GITHUB_SERVICE', - 'readthedocs.oauth.services.github.GitHubService')) -BitbucketService = import_string( - getattr(settings, 'OAUTH_BITBUCKET_SERVICE', - 'readthedocs.oauth.services.bitbucket.BitbucketService')) +from readthedocs.core.utils.extend import SettingsOverrideObject +from readthedocs.oauth.services import github, bitbucket + + +class GitHubService(SettingsOverrideObject): + _default_class = github.GitHubService + _override_setting = 'OAUTH_GITHUB_SERVICE' + + +class BitbucketService(SettingsOverrideObject): + _default_class = bitbucket.BitbucketService + _override_setting = 'OAUTH_BITBUCKET_SERVICE' + registry = [GitHubService, BitbucketService] diff --git a/readthedocs/privacy/loader.py b/readthedocs/privacy/loader.py --- a/readthedocs/privacy/loader.py +++ b/readthedocs/privacy/loader.py @@ -1,36 +1,54 @@ -from django.utils.module_loading import import_string -from django.conf import settings +from readthedocs.core.utils.extend import SettingsOverrideObject +from readthedocs.privacy import backend + # Managers -ProjectManager = import_string( - getattr(settings, 'PROJECT_MANAGER', - 'readthedocs.privacy.backend.ProjectManager')) +from readthedocs.privacy.backends import syncers + + +class ProjectManager(SettingsOverrideObject): + _default_class = backend.ProjectManager + _override_setting = 'PROJECT_MANAGER' + + # VersionQuerySet was replaced by SettingsOverrideObject -VersionManager = import_string( - getattr(settings, 'VERSION_MANAGER', - 'readthedocs.privacy.backend.VersionManager')) -BuildManager = import_string( - getattr(settings, 'BUILD_MANAGER', - 'readthedocs.privacy.backend.BuildManager')) -RelatedProjectManager = import_string( - getattr(settings, 'RELATED_PROJECT_MANAGER', - 'readthedocs.privacy.backend.RelatedProjectManager')) -RelatedBuildManager = import_string( - getattr(settings, 'RELATED_BUILD_MANAGER', - 'readthedocs.privacy.backend.RelatedBuildManager')) -RelatedUserManager = import_string( - getattr(settings, 'RELATED_USER_MANAGER', - 'readthedocs.privacy.backend.RelatedUserManager')) -ChildRelatedProjectManager = import_string( - getattr(settings, 'CHILD_RELATED_PROJECT_MANAGER', - 'readthedocs.privacy.backend.ChildRelatedProjectManager')) +class VersionManager(SettingsOverrideObject): + _default_class = backend.VersionManager + _override_setting = 'VERSION_MANAGER' + + +class BuildManager(SettingsOverrideObject): + _default_class = backend.BuildManager + _override_setting = 'BUILD_MANAGER' + + +class RelatedProjectManager(SettingsOverrideObject): + _default_class = backend.RelatedProjectManager + _override_setting = 'RELATED_PROJECT_MANAGER' + + +class RelatedBuildManager(SettingsOverrideObject): + _default_class = backend.RelatedBuildManager + _override_setting = 'RELATED_BUILD_MANAGER' + + +class RelatedUserManager(SettingsOverrideObject): + _default_class = backend.RelatedUserManager + _override_setting = 'RELATED_USER_MANAGER' + + +class ChildRelatedProjectManager(SettingsOverrideObject): + _default_class = backend.ChildRelatedProjectManager + _override_setting = 'CHILD_RELATED_PROJECT_MANAGER' + # Permissions -AdminPermission = import_string( - getattr(settings, 'ADMIN_PERMISSION', - 'readthedocs.privacy.backend.AdminPermission')) +class AdminPermission(SettingsOverrideObject): + _default_class = backend.AdminPermission + _override_setting = 'ADMIN_PERMISSION' + # Syncers -Syncer = import_string( - getattr(settings, 'FILE_SYNCER', - 'readthedocs.privacy.backends.syncers.LocalSyncer')) +class Syncer(SettingsOverrideObject): + _default_class = syncers.LocalSyncer + _override_setting = 'FILE_SYNCER' diff --git a/readthedocs/projects/backends/views.py b/readthedocs/projects/backends/views.py --- a/readthedocs/projects/backends/views.py +++ b/readthedocs/projects/backends/views.py @@ -5,20 +5,17 @@ settings override of the view class. """ -from django.utils.module_loading import import_string -from django.conf import settings +from readthedocs.core.utils.extend import SettingsOverrideObject +from readthedocs.projects.views import private # Project Import Wizard -ImportWizardView = import_string(getattr( - settings, - 'PROJECT_IMPORT_VIEW', - 'readthedocs.projects.views.private.ImportWizardView' -)) +class ImportWizardView(SettingsOverrideObject): + _default_class = private.ImportWizardView + _override_setting = 'PROJECT_IMPORT_VIEW' + # Project demo import -ImportDemoView = import_string(getattr( - settings, - 'PROJECT_IMPORT_DEMO_VIEW', - 'readthedocs.projects.views.private.ImportDemoView' -)) +class ImportDemoView(SettingsOverrideObject): + _default_class = private.ImportDemoView + _override_setting = 'PROJECT_IMPORT_DEMO_VIEW'
Replace extension pattern with updated version We have two extension patterns utilized currently. These extension points are required so that we can add additional functionality or altered querysets on readthedocs.com. The modern version is in `readthedocs.core.utils.extend`, and an example of this extension is `readthedocs.core.symlink.PublicSymlink`. There are a number of classes using arbitrary settings to allow for override in `readthedocs.privacy.backend`. Unifying these two implementations would clean things up and consolidate our settings. Ref #2611 Replace extension pattern with updated version We have two extension patterns utilized currently. These extension points are required so that we can add additional functionality or altered querysets on readthedocs.com. The modern version is in `readthedocs.core.utils.extend`, and an example of this extension is `readthedocs.core.symlink.PublicSymlink`. There are a number of classes using arbitrary settings to allow for override in `readthedocs.privacy.backend`. Unifying these two implementations would clean things up and consolidate our settings. Ref #2611
`readthedocs.privacy.backend` already uses `SettingsOverrideObject` with `VersionManager`/`VersionQuerySet` - what else do you see as requiring changes? The old pattern is used in these spots: * https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/privacy/loader.py * https://github.com/rtfd/readthedocs.org/blob/c84cd7362a5c43eb95c2316fef9b6df4c592b3b4/readthedocs/oauth/services/__init__.py * https://github.com/rtfd/readthedocs.org/blob/c84cd7362a5c43eb95c2316fef9b6df4c592b3b4/readthedocs/projects/backends/views.py `readthedocs.privacy.backend` already uses `SettingsOverrideObject` with `VersionManager`/`VersionQuerySet` - what else do you see as requiring changes? The old pattern is used in these spots: * https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/privacy/loader.py * https://github.com/rtfd/readthedocs.org/blob/c84cd7362a5c43eb95c2316fef9b6df4c592b3b4/readthedocs/oauth/services/__init__.py * https://github.com/rtfd/readthedocs.org/blob/c84cd7362a5c43eb95c2316fef9b6df4c592b3b4/readthedocs/projects/backends/views.py
2017-05-22T21:50:46
readthedocs/readthedocs.org
2,916
readthedocs__readthedocs.org-2916
[ "1893" ]
1db9bbd27117402b891b0954e6fa3b8471b9cc1f
diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -339,11 +339,11 @@ def save(self, *args, **kwargs): # pylint: disable=arguments-differ 'Re-symlinking superprojects: project=%s', self.slug, ) - for superproject in self.superprojects.all(): + for relationship in self.superprojects.all(): broadcast( type='app', task=tasks.symlink_project, - args=[superproject.pk], + args=[relationship.parent.pk], ) except Exception:
diff --git a/readthedocs/rtd_tests/tests/test_api.py b/readthedocs/rtd_tests/tests/test_api.py --- a/readthedocs/rtd_tests/tests/test_api.py +++ b/readthedocs/rtd_tests/tests/test_api.py @@ -466,6 +466,7 @@ def test_bitbucket_webhook(self, trigger_build): trigger_build.assert_has_calls( [mock.call(force=True, version=mock.ANY, project=self.project)]) + trigger_build_call_count = trigger_build.call_count client.post( '/api/v2/webhook/bitbucket/{0}/'.format(self.project.slug), { @@ -479,8 +480,7 @@ def test_bitbucket_webhook(self, trigger_build): }, format='json', ) - trigger_build.assert_not_called( - [mock.call(force=True, version=mock.ANY, project=self.project)]) + self.assertEqual(trigger_build_call_count, trigger_build.call_count) def test_bitbucket_invalid_webhook(self, trigger_build): """Bitbucket webhook unhandled event.""" diff --git a/readthedocs/rtd_tests/tests/test_project_symlinks.py b/readthedocs/rtd_tests/tests/test_project_symlinks.py --- a/readthedocs/rtd_tests/tests/test_project_symlinks.py +++ b/readthedocs/rtd_tests/tests/test_project_symlinks.py @@ -926,7 +926,7 @@ def test_symlink_broadcast_calls_on_project_save(self): project.description = 'New description' project.save() # called once for this project itself - broadcast.assert_any_calls( + broadcast.assert_any_call( type='app', task=symlink_project, args=[project.pk], @@ -944,13 +944,13 @@ def test_symlink_broadcast_calls_on_project_save(self): subproject.description = 'New subproject description' subproject.save() # subproject symlinks - broadcast.assert_any_calls( + broadcast.assert_any_call( type='app', task=symlink_project, args=[subproject.pk], ) # superproject symlinks - broadcast.assert_any_calls( + broadcast.assert_any_call( type='app', task=symlink_project, args=[project.pk],
Bump allauth to next release When the next version of allauth is released, be sure to bump allauth in requirements.
2017-05-28T20:29:35
readthedocs/readthedocs.org
3,005
readthedocs__readthedocs.org-3005
[ "3000" ]
96f6da57d89a37bdfa6b99de93e8ae6d09e2a586
diff --git a/readthedocs/projects/views/public.py b/readthedocs/projects/views/public.py --- a/readthedocs/projects/views/public.py +++ b/readthedocs/projects/views/public.py @@ -107,27 +107,34 @@ def project_badge(request, project_slug): """Return a sweet badge for the project""" version_slug = request.GET.get('version', LATEST) style = request.GET.get('style', 'flat') + # Default to 24 hour cache lifetime + max_age = request.GET.get('maxAge', 86400) try: version = Version.objects.public(request.user).get( project__slug=project_slug, slug=version_slug) except Version.DoesNotExist: url = ( - 'https://img.shields.io/badge/docs-unknown%20version-yellow.svg?style={style}' - .format(style=style)) + 'https://img.shields.io/badge/docs-unknown%20version-yellow.svg' + '?style={style}&maxAge={max_age}' + .format(style=style, max_age=max_age)) return HttpResponseRedirect(url) version_builds = version.builds.filter(type='html', state='finished').order_by('-date') if not version_builds.exists(): url = ( - 'https://img.shields.io/badge/docs-no%20builds-yellow.svg?style={style}' - .format(style=style)) + 'https://img.shields.io/badge/docs-no%20builds-yellow.svg' + '?style={style}&maxAge={max_age}' + .format(style=style, max_age=max_age)) return HttpResponseRedirect(url) last_build = version_builds[0] if last_build.success: color = 'brightgreen' else: color = 'red' - url = 'https://img.shields.io/badge/docs-%s-%s.svg?style=%s' % ( - version.slug.replace('-', '--'), color, style) + url = ( + 'https://img.shields.io/badge/docs-{version}-{color}.svg' + '?style={style}&maxAge={max_age}' + .format(version=version.slug.replace('-', '--'), color=color, + style=style, max_age=max_age)) return HttpResponseRedirect(url)
Support `maxAge` query parameter to Shields.io in badge redirect ## Details Shields.io allows passing a `maxAge` query parameter that should address #1612, but this is not supported by the RTD redirect. ## Expected Result The `Location` header from `curl -v https://readthedocs.org/projects/pyphi/badge/?version=latest&style=flat-square&maxAge=600` should be: ``` Location: https://img.shields.io/badge/docs-latest-brightgreen.svg?style=flat-square&maxAge=600 ``` ## Actual Result `maxAge` is ignored, though `style` is respected. The `Location` header from `curl -v https://readthedocs.org/projects/pyphi/badge/?version=latest&style=flat-square&maxAge=600` is: ``` Location: https://img.shields.io/badge/docs-latest-brightgreen.svg?style=flat-square ```
This would be a great contribution! The code is here: https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/projects/views/public.py#L119
2017-07-17T20:30:02
readthedocs/readthedocs.org
3,009
readthedocs__readthedocs.org-3009
[ "3008" ]
01c044b583263f9f9ba851c51d39eaac2cd6f100
diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -226,7 +226,7 @@ def install_core_requirements(self): pip_requirements.append('mkdocs') else: pip_requirements.append('readthedocs-sphinx-ext') - requirements.extend(['sphinx', 'sphinx-rtd-theme']) + requirements.extend(['sphinx', 'sphinx_rtd_theme']) cmd = [ 'conda',
Build failing since sphinx-rtd-theme can't be found I believe a recent PR introduced an error which is preventing the theme from being loaded. https://readthedocs.org/projects/jupyterhub/builds/5713289/ I think that perhaps [this line](https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/doc_builder/python_environments.py#L229) should be `sphinx_rtd_theme`. cc/ @ericholscher
2017-07-20T00:53:04
readthedocs/readthedocs.org
3,111
readthedocs__readthedocs.org-3111
[ "2799" ]
ec23bc9c9d0eef0821a165d11a3ce75f1f39d59c
diff --git a/readthedocs/donate/views.py b/readthedocs/donate/views.py --- a/readthedocs/donate/views.py +++ b/readthedocs/donate/views.py @@ -135,7 +135,6 @@ def click_proxy(request, promo_id, hash): ) ) cache.incr(promo.cache_key(type=CLICKS, hash=hash)) - raise Http404('Invalid click. This has been logged.') return redirect(promo.link) @@ -165,7 +164,6 @@ def view_proxy(request, promo_id, hash): ) ) cache.incr(promo.cache_key(type=VIEWS, hash=hash)) - raise Http404('Invalid click. This has been logged.') return redirect(promo.image)
Click twice in the 404 sustainability link doesn't work ## Steps to reproduce it 1. Go to https://readthedocs.org/humitos 2. You will see a 404 page with a sustainability link (https://readthedocs.org/sustainability/click/90/EdfO7Jed1YQr/) 3. Click on it 4. It goes to Sentry home page 5. Go back and click it again ## Expected Result Go to Sentry again. ## Actual Result You get **a new** 404 page with a new link :)
2017-09-19T04:10:38
readthedocs/readthedocs.org
3,131
readthedocs__readthedocs.org-3131
[ "2762" ]
cb22c21bd4993a03937e40d738cb97b4490232a3
diff --git a/readthedocs/core/admin.py b/readthedocs/core/admin.py --- a/readthedocs/core/admin.py +++ b/readthedocs/core/admin.py @@ -67,6 +67,7 @@ def is_banned(self, obj): return hasattr(obj, 'profile') and obj.profile.banned is_banned.short_description = 'Banned' + is_banned.boolean = True def ban_user(self, request, queryset): users = [] diff --git a/readthedocs/projects/admin.py b/readthedocs/projects/admin.py --- a/readthedocs/projects/admin.py +++ b/readthedocs/projects/admin.py @@ -2,8 +2,13 @@ from __future__ import absolute_import from django.contrib import admin +from django.contrib import messages +from django.contrib.admin.actions import delete_selected +from django.utils.translation import ugettext_lazy as _ from guardian.admin import GuardedModelAdmin +from readthedocs.core.models import UserProfile +from readthedocs.core.utils import broadcast from readthedocs.builds.models import Version from readthedocs.redirects.models import Redirect from readthedocs.notifications.views import SendNotificationView @@ -11,6 +16,7 @@ from .notifications import ResourceUsageNotification from .models import (Project, ImportedFile, ProjectRelationship, EmailHook, WebHook, Domain) +from .tasks import remove_dir class ProjectSendNotificationView(SendNotificationView): @@ -65,6 +71,30 @@ class DomainInline(admin.TabularInline): # return instance.click_ratio * 100 +class ProjectOwnerBannedFilter(admin.SimpleListFilter): + + """Filter for projects with banned owners + + There are problems adding `users__profile__banned` to the `list_filter` + attribute, so we'll create a basic filter to capture banned owners. + """ + + title = 'project owner banned' + parameter_name = 'project_owner_banned' + + OWNER_BANNED = 'true' + + def lookups(self, request, model_admin): + return ( + (self.OWNER_BANNED, _('Yes')), + ) + + def queryset(self, request, queryset): + if self.value() == self.OWNER_BANNED: + return queryset.filter(users__profile__banned=True) + return queryset + + class ProjectAdmin(GuardedModelAdmin): """Project model admin view""" @@ -72,13 +102,14 @@ class ProjectAdmin(GuardedModelAdmin): prepopulated_fields = {'slug': ('name',)} list_display = ('name', 'repo', 'repo_type', 'allow_comments', 'featured', 'theme') list_filter = ('repo_type', 'allow_comments', 'featured', 'privacy_level', - 'documentation_type', 'programming_language') + 'documentation_type', 'programming_language', + ProjectOwnerBannedFilter) list_editable = ('featured',) search_fields = ('slug', 'repo') inlines = [ProjectRelationshipInline, RedirectInline, VersionInline, DomainInline] raw_id_fields = ('users', 'main_language_project') - actions = ['send_owner_email'] + actions = ['send_owner_email', 'ban_owner'] def send_owner_email(self, request, queryset): view = ProjectSendNotificationView.as_view( @@ -88,6 +119,51 @@ def send_owner_email(self, request, queryset): send_owner_email.short_description = 'Notify project owners' + def ban_owner(self, request, queryset): + """Ban project owner + + This will only ban single owners, because a malicious user could add a + user as a co-owner of the project. We don't want to induce and + collatoral damage when flagging users. + """ + total = 0 + for project in queryset: + if project.users.count() == 1: + count = (UserProfile.objects + .filter(user__projects=project) + .update(banned=True)) + total += count + else: + messages.add_message(request, messages.ERROR, + 'Project has multiple owners: {0}'.format(project)) + if total == 0: + messages.add_message(request, messages.ERROR, 'No users banned') + else: + messages.add_message(request, messages.INFO, + 'Banned {0} user(s)'.format(total)) + + ban_owner.short_description = 'Ban project owner' + + def delete_selected_and_artifacts(self, request, queryset): + """Remove HTML/etc artifacts from application instances + + Prior to the query delete, broadcast tasks to delete HTML artifacts from + application instances. + """ + if request.POST.get('post'): + for project in queryset: + broadcast(type='app', task=remove_dir, args=[project.doc_path]) + return delete_selected(self, request, queryset) + + def get_actions(self, request): + actions = super(ProjectAdmin, self).get_actions(request) + actions['delete_selected'] = ( + self.__class__.delete_selected_and_artifacts, + 'delete_selected', + delete_selected.short_description + ) + return actions + class ImportedFileAdmin(admin.ModelAdmin):
diff --git a/readthedocs/rtd_tests/tests/projects/__init__.py b/readthedocs/rtd_tests/tests/projects/__init__.py new file mode 100644 diff --git a/readthedocs/rtd_tests/tests/projects/test_admin_actions.py b/readthedocs/rtd_tests/tests/projects/test_admin_actions.py new file mode 100644 --- /dev/null +++ b/readthedocs/rtd_tests/tests/projects/test_admin_actions.py @@ -0,0 +1,80 @@ +import mock +import django_dynamic_fixture as fixture +from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME +from django.contrib.auth.models import User +from django.core import urlresolvers +from django.test import TestCase + +from readthedocs.core.models import UserProfile +from readthedocs.projects.models import Project + + +class ProjectAdminActionsTest(TestCase): + + @classmethod + def setUpTestData(cls): + cls.owner = fixture.get(User) + cls.profile = fixture.get(UserProfile, user=cls.owner, banned=False) + cls.admin = fixture.get(User, is_staff=True, is_superuser=True) + cls.project = fixture.get( + Project, + main_language_project=None, + users=[cls.owner], + ) + + def setUp(self): + self.client.force_login(self.admin) + + def test_project_ban_owner(self): + self.assertFalse(self.owner.profile.banned) + action_data = { + ACTION_CHECKBOX_NAME: [self.project.pk], + 'action': 'ban_owner', + 'index': 0, + } + resp = self.client.post( + urlresolvers.reverse('admin:projects_project_changelist'), + action_data + ) + self.assertTrue(self.project.users.filter(profile__banned=True).exists()) + self.assertFalse(self.project.users.filter(profile__banned=False).exists()) + + def test_project_ban_multiple_owners(self): + owner_b = fixture.get(User) + profile_b = fixture.get(UserProfile, user=owner_b, banned=False) + self.project.users.add(owner_b) + self.assertFalse(self.owner.profile.banned) + self.assertFalse(owner_b.profile.banned) + action_data = { + ACTION_CHECKBOX_NAME: [self.project.pk], + 'action': 'ban_owner', + 'index': 0, + } + resp = self.client.post( + urlresolvers.reverse('admin:projects_project_changelist'), + action_data + ) + self.assertFalse(self.project.users.filter(profile__banned=True).exists()) + self.assertEqual(self.project.users.filter(profile__banned=False).count(), 2) + + @mock.patch('readthedocs.projects.admin.remove_dir') + def test_project_delete(self, remove_dir): + """Test project and artifacts are removed""" + action_data = { + ACTION_CHECKBOX_NAME: [self.project.pk], + 'action': 'delete_selected', + 'index': 0, + 'post': 'yes', + } + resp = self.client.post( + urlresolvers.reverse('admin:projects_project_changelist'), + action_data + ) + self.assertFalse(Project.objects.filter(pk=self.project.pk).exists()) + remove_dir.apply_async.assert_has_calls([ + mock.call( + kwargs={}, + queue='celery', + args=[self.project.doc_path] + ), + ])
Add an admin function to remove spam We could use an admin function that performs a series of operations on a project: * Update the `UserProfile` to set the `banned` flag * Delete the `Project` being flagged Perhaps also a separate admin function: delete any project owner by a user that is flagged as banned.
So it will remove projects from database?
2017-09-28T18:28:14
readthedocs/readthedocs.org
3,175
readthedocs__readthedocs.org-3175
[ "3120" ]
0cb36c6d1d89edaf550bf378c8bc4447b30dd103
diff --git a/readthedocs/core/forms.py b/readthedocs/core/forms.py --- a/readthedocs/core/forms.py +++ b/readthedocs/core/forms.py @@ -4,6 +4,7 @@ from builtins import object import logging +from django.contrib.auth.models import User from haystack.forms import SearchForm from haystack.query import SearchQuerySet from django import forms @@ -44,6 +45,22 @@ def save(self, commit=True): return profile +class UserDeleteForm(forms.ModelForm): + username = CharField(label=_('Username'), help_text=_('Please type your username to confirm.')) + + class Meta(object): + model = User + fields = ['username'] + + def clean_username(self): + data = self.cleaned_data['username'] + + if self.instance.username != data: + raise forms.ValidationError(_("Username does not match!")) + + return data + + class FacetField(forms.MultipleChoiceField): """ diff --git a/readthedocs/profiles/urls/private.py b/readthedocs/profiles/urls/private.py --- a/readthedocs/profiles/urls/private.py +++ b/readthedocs/profiles/urls/private.py @@ -18,4 +18,5 @@ 'template_name': 'profiles/private/edit_profile.html', }, name='profiles_profile_edit'), + url(r'^delete/', views.delete_account, name='delete_account') ] diff --git a/readthedocs/profiles/views.py b/readthedocs/profiles/views.py --- a/readthedocs/profiles/views.py +++ b/readthedocs/profiles/views.py @@ -1,16 +1,21 @@ """Views for creating, editing and viewing site-specific user profiles.""" from __future__ import absolute_import + +from django.contrib import messages +from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse from django.http import Http404 from django.http import HttpResponseRedirect -from django.shortcuts import get_object_or_404 +from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render_to_response from django.template import RequestContext +from readthedocs.core.forms import UserDeleteForm + def create_profile(request, form_class, success_url=None, template_name='profiles/private/create_profile.html', @@ -183,6 +188,27 @@ def edit_profile(request, form_class, success_url=None, edit_profile = login_required(edit_profile) +@login_required() +def delete_account(request): + form = UserDeleteForm() + template_name = 'profiles/private/delete_account.html' + + if request.method == 'POST': + form = UserDeleteForm(instance=request.user, data=request.POST) + if form.is_valid(): + + # Do not delete the account permanently because it may create disaster + # Inactive the user instead. + request.user.is_active = False + request.user.save() + logout(request) + messages.info(request, 'You have successfully deleted your account') + + return redirect('homepage') + + return render(request, template_name, {'form': form}) + + def profile_detail(request, username, public_profile_field=None, template_name='profiles/public/profile_detail.html', extra_context=None):
Enable users to delete their own account Currently, people are posting issues if they need their account deleted. This leads to extra noise in the issues, and to some privacy concerns. I propose we add an email account and notice to the README, letting users know where they can email to request account deletion. This will allow better triaging and chunking of deletions. @ericholscher What do you think?
Is adding a "Delete Account" button somewhere out of the question? That would also work. This is a proposed stop-gap measure which would be easier to set up, I believe. There's a bunch of background here: https://github.com/rtfd/readthedocs.org/issues/1408 -- tl;dr, we need to decide how to handle a number of cases when deleting folks, and it isn't as simple as running user.delete(). I lied, #1408 is about deleting projects, which is a follow on effect on deleting users. Yep. What we can do now, though, is to set up a clearer, more private way for users to contact you (or someone else who can do this task), which doesn't require them spamming all of the watchers. What do you think? Hmm, I guess. Though having the requests just come to my email isn't a great solution either. We should really implement a proper delete function; but I guess the people who want to delete their accounts are the least likely to contribute :/ I feel you. How about we rename this "Enable users to delete their own account", tag it as Help Wanted, and see if anyone wants to bite? :) Works for me. I'd like to get to it, but as above, users who are leaving the platform are hard to prioritize, so it hasn't gotten done. > users who are leaving the platform are hard to prioritize, Ah. I'm sorry, I wasn't clear! I agree, I'm not prioritizing them. What I'm prioritizing is the notifications of watchers to this repo - people we want to keep! - and ensuring that we don't flood their streams with issues from people saying 'Delete my account please'. Some of the noise can be removed with a better process, leading to higher signal. I'll change the name of the issue now! Anyone who wants to take this on, feel free to comment here! @RichardLitt So the fix would be adding a button for the user to delete their account? @safwanrahman Yep. Want to take a crack at it? @RichardLitt I will go through the code and check if I can make it work. Hope that will work
2017-10-20T17:31:38
readthedocs/readthedocs.org
3,200
readthedocs__readthedocs.org-3200
[ "3171" ]
b65e2f35e772dca1f5b15469a4aa0408f1fe9774
diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -117,7 +117,13 @@ def install_core_requirements(self): """Install basic Read the Docs requirements into the virtualenv.""" requirements = [ 'Pygments==2.2.0', - 'setuptools==28.8.0', + # Assume semver for setuptools version, support up to next backwards + # incompatible release + self.project.get_feature_value( + Feature.USE_SETUPTOOLS_LATEST, + positive='setuptools<37', + negative='setuptools==28.8.0', + ), 'docutils==0.13.1', 'mock==1.0.1', 'pillow==2.6.1', @@ -129,13 +135,14 @@ def install_core_requirements(self): if self.project.documentation_type == 'mkdocs': requirements.append('mkdocs==0.15.0') else: - if self.project.has_feature(Feature.USE_SPHINX_LATEST): - # We will assume semver here and only automate up to the next - # backward incompatible release: 2.x - requirements.append('sphinx<2') - else: - requirements.append('sphinx==1.5.6') + # We will assume semver here and only automate up to the next + # backward incompatible release: 2.x requirements.extend([ + self.project.get_feature_value( + Feature.USE_SPHINX_LATEST, + positive='sphinx<2', + negative='sphinx==1.5.6', + ), 'sphinx-rtd-theme<0.3', 'readthedocs-sphinx-ext<0.6' ]) diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -835,6 +835,14 @@ def has_feature(self, feature_id): """ return self.features.filter(feature_id=feature_id).exists() + def get_feature_value(self, feature, positive, negative): + """Look up project feature, return corresponding value + + If a project has a feature, return ``positive``, otherwise return + ``negative`` + """ + return positive if self.has_feature(feature) else negative + class APIProject(Project): @@ -994,9 +1002,11 @@ def add_features(sender, **kwargs): # Feature constants - this is not a exhaustive list of features, features # may be added by other packages USE_SPHINX_LATEST = 'use_sphinx_latest' + USE_SETUPTOOLS_LATEST = 'use_setuptools_latest' FEATURES = ( (USE_SPHINX_LATEST, _('Use latest version of Sphinx')), + (USE_SETUPTOOLS_LATEST, _('Use latest version of setuptools')), ) projects = models.ManyToManyField(
Bump setuptools version. Similar to #2547, setuptools is out of date again, and is causing builds such as https://readthedocs.org/projects/mozilla-balrog/builds/6136328/ to fail.
2017-10-27T06:20:19
readthedocs/readthedocs.org
3,201
readthedocs__readthedocs.org-3201
[ "3077" ]
a6ec23ce85e9ce98bebdd2ad950de25350a73396
diff --git a/readthedocs/doc_builder/python_environments.py b/readthedocs/doc_builder/python_environments.py --- a/readthedocs/doc_builder/python_environments.py +++ b/readthedocs/doc_builder/python_environments.py @@ -152,7 +152,7 @@ def install_core_requirements(self): self.venv_bin(filename='pip'), 'install', '--use-wheel', - '-U', + '--upgrade', '--cache-dir', self.project.pip_cache_path, ] @@ -182,14 +182,21 @@ def install_user_requirements(self): break if requirements_file_path: - self.build_env.run( + args = [ 'python', self.venv_bin(filename='pip'), 'install', + ] + if self.project.has_feature(Feature.PIP_ALWAYS_UPGRADE): + args += ['--upgrade'] + args += [ '--exists-action=w', '--cache-dir', self.project.pip_cache_path, '-r{0}'.format(requirements_file_path), + ] + self.build_env.run( + *args, cwd=self.checkout_path, bin_path=self.venv_bin() ) diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -1003,10 +1003,12 @@ def add_features(sender, **kwargs): # may be added by other packages USE_SPHINX_LATEST = 'use_sphinx_latest' USE_SETUPTOOLS_LATEST = 'use_setuptools_latest' + PIP_ALWAYS_UPGRADE = 'pip_always_upgrade' FEATURES = ( (USE_SPHINX_LATEST, _('Use latest version of Sphinx')), (USE_SETUPTOOLS_LATEST, _('Use latest version of setuptools')), + (PIP_ALWAYS_UPGRADE, _('Always run pip install --upgrade')), ) projects = models.ManyToManyField(
Use `--upgrade` flag for user environment `pip install` Addresses #3027. I'm not sure if this will cause undesirable side-effects, so more discussion is needed—but I figured I'd make the PR in any case.
@ericholscher, by the way, I'd be happy to help out triaging tickets—would you grant me the necessary permissions? Sure thing. I added you. I know there is a reason we removed the call to `-U` on pip, but I can't remember what it was. I'll do a bit of research and see if I can remember what issue it was causing. Sounds good. Thanks for the permissions! I vaguely recall a problem with pip package caching while forcing upgrades. I'm going to bump up plans to test out feature flagging on projects this week. This is yet another case where we could push out a change on a sample and see if it blows up. @agjohnson, sounds good! Let me know if I can help.
2017-10-27T06:39:33
readthedocs/readthedocs.org
3,205
readthedocs__readthedocs.org-3205
[ "3130" ]
44173225b37576be2131c3e535e135bdbd310864
diff --git a/readthedocs/core/views/hooks.py b/readthedocs/core/views/hooks.py --- a/readthedocs/core/views/hooks.py +++ b/readthedocs/core/views/hooks.py @@ -11,7 +11,7 @@ from readthedocs.core.utils import trigger_build from readthedocs.builds.constants import LATEST from readthedocs.projects import constants -from readthedocs.projects.models import Project +from readthedocs.projects.models import Project, Feature from readthedocs.projects.tasks import update_imported_docs import logging @@ -23,6 +23,10 @@ class NoProjectException(Exception): pass +def _allow_deprecated_webhook(project): + return project.has_feature(Feature.ALLOW_DEPRECATED_WEBHOOKS) + + def _build_version(project, slug, already_built=()): """ Where we actually trigger builds for a project and slug. @@ -108,6 +112,13 @@ def _build_url(url, projects, branches): ret = "" all_built = {} all_not_building = {} + + # This endpoint doesn't require authorization, we shouldn't allow builds to + # be triggered from this any longer. Deprecation plan is to selectively + # allow access to this endpoint for now. + if not any(_allow_deprecated_webhook(project) for project in projects): + return HttpResponse('This API endpoint is deprecated', status=403) + for project in projects: (built, not_building) = build_branches(project, branches) if not built: @@ -314,6 +325,11 @@ def generic_build(request, project_id_or_slug=None): project_id_or_slug) return HttpResponseNotFound( 'Repo not found: %s' % project_id_or_slug) + # This endpoint doesn't require authorization, we shouldn't allow builds to + # be triggered from this any longer. Deprecation plan is to selectively + # allow access to this endpoint for now. + if not _allow_deprecated_webhook(project): + return HttpResponse('This API endpoint is deprecated', status=403) if request.method == 'POST': slug = request.POST.get('version_slug', project.default_version) log.info( diff --git a/readthedocs/projects/migrations/0021_add-webhook-deprecation-feature.py b/readthedocs/projects/migrations/0021_add-webhook-deprecation-feature.py new file mode 100644 --- /dev/null +++ b/readthedocs/projects/migrations/0021_add-webhook-deprecation-feature.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- + +"""Add feature for allowing access to deprecated webhook endpoints""" + +from __future__ import unicode_literals + +from django.db import migrations + + +FEATURE_ID = 'allow_deprecated_webhooks' + + +def forward_add_feature(apps, schema_editor): + Feature = apps.get_model('projects', 'Feature') + Feature.objects.create( + feature_id=FEATURE_ID, + default_true=True, + ) + + +def reverse_add_feature(apps, schema_editor): + Feature = apps.get_model('projects', 'Feature') + Feature.objects.filter(feature_id=FEATURE_ID).delete() + + +class Migration(migrations.Migration): + + dependencies = [ + ('projects', '0020_add-api-project-proxy'), + ] + + operations = [ + migrations.RunPython(forward_add_feature, reverse_add_feature) + ] diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -1003,11 +1003,13 @@ def add_features(sender, **kwargs): # may be added by other packages USE_SPHINX_LATEST = 'use_sphinx_latest' USE_SETUPTOOLS_LATEST = 'use_setuptools_latest' + ALLOW_DEPRECATED_WEBHOOKS = 'allow_deprecated_webhooks' PIP_ALWAYS_UPGRADE = 'pip_always_upgrade' FEATURES = ( (USE_SPHINX_LATEST, _('Use latest version of Sphinx')), (USE_SETUPTOOLS_LATEST, _('Use latest version of setuptools')), + (ALLOW_DEPRECATED_WEBHOOKS, _('Allow deprecated webhook views')), (PIP_ALWAYS_UPGRADE, _('Always run pip install --upgrade')), )
diff --git a/readthedocs/rtd_tests/tests/test_post_commit_hooks.py b/readthedocs/rtd_tests/tests/test_post_commit_hooks.py --- a/readthedocs/rtd_tests/tests/test_post_commit_hooks.py +++ b/readthedocs/rtd_tests/tests/test_post_commit_hooks.py @@ -9,7 +9,7 @@ from future.backports.urllib.parse import urlencode from readthedocs.builds.models import Version -from readthedocs.projects.models import Project +from readthedocs.projects.models import Project, Feature log = logging.getLogger(__name__) @@ -32,6 +32,11 @@ def _setup(self): self.mocks = [mock.patch('readthedocs.core.views.hooks.trigger_build')] self.patches = [m.start() for m in self.mocks] + self.feature = Feature.objects.get(feature_id=Feature.ALLOW_DEPRECATED_WEBHOOKS) + self.feature.projects.add(self.pip) + self.feature.projects.add(self.rtfd) + self.feature.projects.add(self.sphinx) + self.client.login(username='eric', password='test') @@ -141,6 +146,23 @@ def test_gitlab_post_commit_knows_default_branches(self): rtd.default_branch = old_default rtd.save() + def test_gitlab_webhook_is_deprecated(self): + # Project is created after feature, not included in historical allowance + url = 'https://github.com/rtfd/readthedocs-build' + payload = self.payload.copy() + payload['project']['http_url'] = url + project = get( + Project, + main_language_project=None, + repo=url, + ) + r = self.client.post( + '/gitlab/', + data=json.dumps(payload), + content_type='application/json' + ) + self.assertEqual(r.status_code, 403) + class GitHubPostCommitTest(BasePostCommitTest): fixtures = ["eric"] @@ -297,6 +319,23 @@ def test_github_post_commit_knows_default_branches(self): rtd.default_branch = old_default rtd.save() + def test_github_webhook_is_deprecated(self): + # Project is created after feature, not included in historical allowance + url = 'https://github.com/rtfd/readthedocs-build' + payload = self.payload.copy() + payload['repository']['url'] = url + project = get( + Project, + main_language_project=None, + repo=url, + ) + r = self.client.post( + '/github/', + data=json.dumps(payload), + content_type='application/json' + ) + self.assertEqual(r.status_code, 403) + class CorePostCommitTest(BasePostCommitTest): fixtures = ["eric"] @@ -320,6 +359,12 @@ def test_hook_state_tracking(self): # Need to re-query to get updated DB entry self.assertEqual(Project.objects.get(slug='read-the-docs').has_valid_webhook, True) + def test_generic_webhook_is_deprecated(self): + # Project is created after feature, not included in historical allowance + project = get(Project, main_language_project=None) + r = self.client.post('/build/%s' % project.pk, {'version_slug': 'master'}) + self.assertEqual(r.status_code, 403) + class BitBucketHookTests(BasePostCommitTest): @@ -476,6 +521,7 @@ def test_bitbucket_default_branch(self): Project, repo='HTTPS://bitbucket.org/test/project', slug='test-project', default_branch='integration', repo_type='git', ) + self.feature.projects.add(self.test_project) self.git_payload['commits'] = [{ "branch": "integration", @@ -487,3 +533,20 @@ def test_bitbucket_default_branch(self): r = self.client.post('/bitbucket/', data=json.dumps(self.git_payload), content_type='application/json') self.assertContains(r, '(URL Build) Build Started: bitbucket.org/test/project [latest]') + + def test_bitbucket_webhook_is_deprecated(self): + # Project is created after feature, not included in historical allowance + url = 'https://bitbucket.org/rtfd/readthedocs-build' + payload = self.git_payload.copy() + payload['repository']['absolute_url'] = '/rtfd/readthedocs-build' + project = get( + Project, + main_language_project=None, + repo=url, + ) + r = self.client.post( + '/bitbucket/', + data=json.dumps(payload), + content_type='application/json' + ) + self.assertEqual(r.status_code, 403)
Close up /build endpoint The `/build` endpoint should be deprecated. Anyone can abuse this endpoint and trigger builds across any number of projects. We now have authenticated build endpoints that users should be using. ## Steps to deprecation - [ ] Find users legitimately using the endpoint (Add a build_source on builds, so we can track it) - [ ] Feature flag these users as allowed - [ ] Remove feature for all other projects and all newly imported projects
2017-10-28T00:15:27
readthedocs/readthedocs.org
3,214
readthedocs__readthedocs.org-3214
[ "3182" ]
e85e1fc6fa40bc063ff7111310ee7396f5ad35f1
diff --git a/readthedocs/core/signals.py b/readthedocs/core/signals.py --- a/readthedocs/core/signals.py +++ b/readthedocs/core/signals.py @@ -5,13 +5,15 @@ import logging from corsheaders import signals +from django.conf import settings +from django.db.models.signals import pre_delete from django.dispatch import Signal -from django.db.models import Q +from django.db.models import Q, Count +from django.dispatch import receiver from future.backports.urllib.parse import urlparse from readthedocs.projects.models import Project, Domain - log = logging.getLogger(__name__) WHITELIST_URLS = ['/api/v2/footer_html', '/api/v2/search', '/api/v2/docsearch'] @@ -62,4 +64,20 @@ def decide_if_cors(sender, request, **kwargs): # pylint: disable=unused-argumen return False + +@receiver(pre_delete, sender=settings.AUTH_USER_MODEL) +def delete_projects_and_organizations(sender, instance, *args, **kwargs): + # Here we count the owner list from the projects that the user own + # Then exclude the projects where there are more than one owner + projects = instance.projects.all().annotate(num_users=Count('users')).exclude(num_users__gt=1) + + # Here we count the users list from the organization that the user belong + # Then exclude the organizations where there are more than one user + oauth_organizations = (instance.oauth_organizations.annotate(num_users=Count('users')) + .exclude(num_users__gt=1)) + + projects.delete() + oauth_organizations.delete() + + signals.check_request_enabled.connect(decide_if_cors) diff --git a/readthedocs/profiles/views.py b/readthedocs/profiles/views.py --- a/readthedocs/profiles/views.py +++ b/readthedocs/profiles/views.py @@ -196,11 +196,9 @@ def delete_account(request): if request.method == 'POST': form = UserDeleteForm(instance=request.user, data=request.POST) if form.is_valid(): - - # Do not delete the account permanently because it may create disaster - # Inactive the user instead. - request.user.is_active = False - request.user.save() + # Delete the user permanently + # It will also delete some projects where he is the only owner + request.user.delete() logout(request) messages.info(request, 'You have successfully deleted your account')
Better User deletion With #3175 we now have a way for users to mark themselves as wanting to be deleted, now we need to actually delete them. This could be done inline during delete, or as a batch job that runs after the web view returns. We want to actually **delete** the User instance, but we need to confirm a couple things: * Projects that the user _only_ owns are deleted. This is a [M2m](https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/projects/models.py#L83), so we need to either *remove* them if there are multiple users, or *delete* the project if they are the only owner, so we don't end up with orphaned projects.
@agjohnson Anything else you can think of that attach to users? Looking at the code I see: * FK: Comments - will be deleted * FK: Bookmarks - will be deleted * M2M: [Oauth connections](https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/oauth/models.py#L38) - Believe these might need to be manually deleted (same logic, if only person in Org, delete, otherwise remove user) We should also add a guide entry or something that is Googleable, that shows how to do this (http://docs.readthedocs.io/en/latest/guides/index.html) Projects is the big one. There probably isn't a good reason why oauth models shouldn't be cascading if they aren't already -- those are all single user relations, but might have to be m2m for some other reason. Hey there, The currently implemented "delete" feature is misleading. I wanted to change my username, but I saw that it's impossible, so i went on and deleted (my empty) account thinking that I'd be able to create a new one with a new username. Nowhere does it say that the account is only "disabled". Now I can't re-register because my email is in use (because the account wasn't actually deleted), nor can I reactivate the account. Something needs to be done here 😄 And on a personal note, If someone could hack the DB a bit and reactivate my account in the meantime, it would be delightful 🙏 Is there a support email anywhere? Couldn't find it. Thanks, Shachar. Hey @shacharoo, Apologies for the problem you are facing. Can you open a new issue about your problem so that we can ask out Operation teams to change the email or do other necessary things for you? In the meantime, I am hoping to create a patch ASAP that will cover your use case. Will do @safwanrahman, thanks! Opened #3189 .
2017-10-31T19:03:30
readthedocs/readthedocs.org
3,260
readthedocs__readthedocs.org-3260
[ "3253" ]
1b6860a308a63bec306232d1c156d7b63a64cbd4
diff --git a/readthedocs/builds/views.py b/readthedocs/builds/views.py --- a/readthedocs/builds/views.py +++ b/readthedocs/builds/views.py @@ -6,11 +6,14 @@ from django.shortcuts import get_object_or_404 from django.views.generic import ListView, DetailView -from django.http import HttpResponsePermanentRedirect +from django.http import HttpResponsePermanentRedirect, HttpResponseRedirect from django.conf import settings +from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse +from django.utils.decorators import method_decorator from readthedocs.builds.models import Build, Version +from readthedocs.core.utils import trigger_build from readthedocs.projects.models import Project from redis import Redis, ConnectionError @@ -33,7 +36,26 @@ def get_queryset(self): return queryset -class BuildList(BuildBase, ListView): +class BuildTriggerMixin(object): + + @method_decorator(login_required) + def post(self, request, project_slug): + project = get_object_or_404( + Project.objects.for_admin_user(self.request.user), + slug=project_slug + ) + version_slug = request.POST.get('version_slug') + version = get_object_or_404( + Version, + project=project, + slug=version_slug, + ) + + trigger_build(project=project, version=version) + return HttpResponseRedirect(reverse('builds_project_list', args=[project.slug])) + + +class BuildList(BuildBase, BuildTriggerMixin, ListView): def get_context_data(self, **kwargs): context = super(BuildList, self).get_context_data(**kwargs) diff --git a/readthedocs/projects/views/public.py b/readthedocs/projects/views/public.py --- a/readthedocs/projects/views/public.py +++ b/readthedocs/projects/views/public.py @@ -26,6 +26,7 @@ from .base import ProjectOnboardMixin from readthedocs.builds.constants import LATEST from readthedocs.builds.models import Version +from readthedocs.builds.views import BuildTriggerMixin from readthedocs.projects.models import Project, ImportedFile from readthedocs.search.indexes import PageIndex from readthedocs.search.views import LOG_TEMPLATE @@ -67,7 +68,7 @@ def get_context_data(self, **kwargs): project_index = ProjectIndex.as_view() -class ProjectDetailView(ProjectOnboardMixin, DetailView): +class ProjectDetailView(BuildTriggerMixin, ProjectOnboardMixin, DetailView): """Display project onboard steps"""
Build version forms hit deprecated /build endpoint The `/build` endpoint was deprecated recently, as it was a security problem allowing builds without authorization. We are still posting to this endpoint on the project dashboard and the build listing page "build version" forms. We should replace this with an endpoint that uses CSRF token and stop posting to `/build/`. Right now, posting to this endpoint on a project that does not have the `Feature.ALLOW_DEPRECATED_WEBHOOKS` feature will result in "This endpoint is deprecated" error.
2017-11-14T17:26:33
readthedocs/readthedocs.org
3,273
readthedocs__readthedocs.org-3273
[ "2992" ]
7cbda6a9b318dc182cd304332a3045a1c53a4aef
diff --git a/readthedocs/oauth/services/base.py b/readthedocs/oauth/services/base.py --- a/readthedocs/oauth/services/base.py +++ b/readthedocs/oauth/services/base.py @@ -1,13 +1,14 @@ -"""OAuth utility functions""" +"""OAuth utility functions.""" from __future__ import absolute_import -from builtins import str from builtins import object import logging from datetime import datetime from django.conf import settings from requests_oauthlib import OAuth2Session +from requests.exceptions import RequestException +from oauthlib.oauth2.rfc6749.errors import InvalidClientIdError from allauth.socialaccount.models import SocialAccount @@ -69,13 +70,13 @@ def create_session(self): return None token_config = { - 'access_token': str(token.token), + 'access_token': token.token, 'token_type': 'bearer', } if token.expires_at is not None: token_expires = (token.expires_at - datetime.now()).total_seconds() token_config.update({ - 'refresh_token': str(token.token_secret), + 'refresh_token': token.token_secret, 'expires_in': token_expires, }) @@ -114,6 +115,34 @@ def _updater(data): return _updater + def paginate(self, url): + """Recursively combine results from service's pagination. + + :param url: start url to get the data from. + :type url: unicode + """ + try: + resp = self.get_session().get(url) + next_url = self.get_next_url_to_paginate(resp) + results = self.get_paginated_results(resp) + if next_url: + results.extend(self.paginate(next_url)) + return results + # Catch specific exception related to OAuth + except InvalidClientIdError: + log.error('access_token or refresh_token failed: %s', url) + raise Exception('You should reconnect your account') + # Catch exceptions with request or deserializing JSON + except (RequestException, ValueError): + # Response data should always be JSON, still try to log if not though + try: + debug_data = resp.json() + except ValueError: + debug_data = resp.content + log.debug('paginate failed at %s with response: %s', url, debug_data) + finally: + return [] + def sync(self): raise NotImplementedError @@ -124,6 +153,22 @@ def create_repository(self, fields, privacy=DEFAULT_PRIVACY_LEVEL, def create_organization(self, fields): raise NotImplementedError + def get_next_url_to_paginate(self, response): + """Return the next url to feed the `paginate` method. + + :param response: response from where to get the `next_url` attribute + :type response: requests.Response + """ + raise NotImplementedError + + def get_paginated_results(self, response): + """Return the results for the current response/page. + + :param response: response from where to get the results. + :type response: requests.Response + """ + raise NotImplementedError + def setup_webhook(self, project): raise NotImplementedError diff --git a/readthedocs/oauth/services/bitbucket.py b/readthedocs/oauth/services/bitbucket.py --- a/readthedocs/oauth/services/bitbucket.py +++ b/readthedocs/oauth/services/bitbucket.py @@ -164,18 +164,11 @@ def create_organization(self, fields): organization.save() return organization - def paginate(self, url): - """Recursively combine results from Bitbucket pagination + def get_next_url_to_paginate(self, response): + return response.json().get('next') - :param url: start url to get the data from. - """ - resp = self.get_session().get(url) - data = resp.json() - results = data.get('values', []) - next_url = data.get('next') - if next_url: - results.extend(self.paginate(next_url)) - return results + def get_paginated_results(self, response): + return response.json().get('values', []) def get_webhook_data(self, project, integration): """Get webhook JSON data to post to the API""" diff --git a/readthedocs/oauth/services/github.py b/readthedocs/oauth/services/github.py --- a/readthedocs/oauth/services/github.py +++ b/readthedocs/oauth/services/github.py @@ -148,19 +148,11 @@ def create_organization(self, fields): organization.save() return organization - def paginate(self, url): - """Combines return from GitHub pagination + def get_next_url_to_paginate(self, response): + return response.links.get('next', {}).get('url') - :param url: start url to get the data from. - - See https://developer.github.com/v3/#pagination - """ - resp = self.get_session().get(url) - result = resp.json() - next_url = resp.links.get('next', {}).get('url') - if next_url: - result.extend(self.paginate(next_url)) - return result + def get_paginated_results(self, response): + return response.json() def get_webhook_data(self, project, integration): """Get webhook JSON data to post to the API"""
Can't sync outdated Bitbucket repositories For some reason, the refresh token for Bitbucket is failing. Is this a Bitbucket problem? Problem with our detection of expired tokens? I get this locally as well as on the community site. Removing and adding the Bitbucket connection solves the problem at least temporarily. Traceback: ``` [05/Jul/2017 14:44:13] celery.worker.job:282[33151]: ERROR Task readthedocs.oauth.tasks.SyncRemoteRepositories[86bd1cbd-0c99-44a6-b5d7-9beadb917a7b] raised unexpected: InvalidClientIdError(u'(invalid_request) (invalid_request) Invalid refresh_token',) Traceback (most recent call last): File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/Users/anthony/dev/readthedocs.org/readthedocs/core/utils/tasks/public.py", line 71, in run result = self.run_public(*args, **kwargs) File "/Users/anthony/dev/readthedocs.org/readthedocs/oauth/tasks.py", line 22, in run_public service.sync() File "/Users/anthony/dev/readthedocs.org/readthedocs/oauth/services/bitbucket.py", line 38, in sync self.sync_repositories() File "/Users/anthony/dev/readthedocs.org/readthedocs/oauth/services/bitbucket.py", line 46, in sync_repositories 'https://bitbucket.org/api/2.0/repositories/?role=member') File "/Users/anthony/dev/readthedocs.org/readthedocs/oauth/services/bitbucket.py", line 172, in paginate resp = self.get_session().get(url) File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/requests/sessions.py", line 468, in get return self.request('GET', url, **kwargs) File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/requests_oauthlib/oauth2_session.py", line 343, in request self.auto_refresh_url, auth=auth, **kwargs File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/requests_oauthlib/oauth2_session.py", line 309, in refresh_token self.token = self._client.parse_request_body_response(r.text, scope=self.scope) File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 409, in parse_request_body_response self.token = parse_token_response(body, scope=scope) File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 376, in parse_token_response validate_token_parameters(params) File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 383, in validate_token_parameters raise_from_error(params.get('error'), params) File "/Users/anthony/.pyenv/versions/rtd-2.7.8/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/errors.py", line 325, in raise_from_error raise cls(**kwargs) InvalidClientIdError: (invalid_request) (invalid_request) Invalid refresh_token ```
2017-11-15T22:58:00
readthedocs/readthedocs.org
3,292
readthedocs__readthedocs.org-3292
[ "3285" ]
02cc08f245efed845df12d702d969d56a3645b83
diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -196,6 +196,7 @@ def run_setup(self, record=True): if not isinstance(self.setup_env.failure, vcs_support_utils.LockTimeout): self.send_notifications() + self.setup_env.update_build(state=BUILD_STATE_FINISHED) return False if self.setup_env.successful and not self.project.has_valid_clone: @@ -257,6 +258,8 @@ def run_build(self, docker=False, record=True): if self.build_env.failed: self.send_notifications() + + self.build_env.update_build(state=BUILD_STATE_FINISHED) build_complete.send(sender=Build, build=self.build_env.build) @staticmethod
Build passed but there is an error on the build page ## Details * Project URL: https://readthedocs.org/projects/mujoco/ * Build URL (if applicable): https://readthedocs.org/projects/mujoco/builds/6291303/ * Read the Docs username (if applicable): ethanabrooks ## Expected Result Matching the build status with the message ## Actual Result It says the build Passed but it has Failed ![captura de pantalla_2017-11-19_16-43-48](https://user-images.githubusercontent.com/244656/32995885-007a55b2-cd49-11e7-8dca-8381fdb1d90a.png) Related: #3284
This might be related to #3280
2017-11-21T18:24:17
readthedocs/readthedocs.org
3,302
readthedocs__readthedocs.org-3302
[ "1637" ]
86f705fe6a42b841e742225060b87649cf18cf6a
diff --git a/readthedocs/vcs_support/backends/git.py b/readthedocs/vcs_support/backends/git.py --- a/readthedocs/vcs_support/backends/git.py +++ b/readthedocs/vcs_support/backends/git.py @@ -92,7 +92,15 @@ def clone(self): @property def tags(self): - retcode, stdout, _ = self.run('git', 'show-ref', '--tags') + # Hash for non-annotated tag is its commit hash, but for annotated tag it + # points to tag itself, so we need to dereference annotated tags. + # The output format is the same as `git show-ref --tags`, but with hashes + # of annotated tags pointing to tagged commits. + retcode, stdout, _ = self.run( + 'git', 'for-each-ref', + '--format="%(if)%(*objectname)%(then)%(*objectname)' + '%(else)%(objectname)%(end) %(refname)"', + 'refs/tags') # error (or no tags found) if retcode != 0: return [] @@ -100,7 +108,7 @@ def tags(self): def parse_tags(self, data): """ - Parses output of show-ref --tags, eg: + Parses output of `git show-ref --tags`, eg: 3b32886c8d3cb815df3793b3937b2e91d0fb00f1 refs/tags/2.0.0 bd533a768ff661991a689d3758fcfe72f455435d refs/tags/2.0.1
Broken edit links Two issues which may or may not be related: - Module sources: the "Edit on github" links for pages like http://www.tornadoweb.org/en/stable/_modules/tornado/stack_context.html are broken; they point to a non-existent .rst file. Is it possible to suppress the edit link for these pages (or ideally point it to the real source)? (migrated from https://github.com/snide/sphinx_rtd_theme/issues/237) - Non-latest branches: on a page like http://www.tornadoweb.org/en/stable/, the "edit on github" link in the upper right is broken because it points to https://github.com/tornadoweb/tornado/blob/origin/stable/docs/index.rst (the 'origin' directory needs to be removed from the path). On the lower left, clicking "v: stable" for the menu and then "Edit" works (linking to https://github.com/tornadoweb/tornado/edit/stable/docs/index.rst). The "latest" branch works fine (linking to "master"); this is only a problem for pages based on other branches (migrated from https://github.com/snide/sphinx_rtd_theme/issues/236)
Thanks for the report! Indeed these are two distinct issues. The first will be addressed with #1643. I also had a look at the second, but it's a little tricky. The reason is that `stable` usually is a special version name on our end. We alias the branch or tag of a project that is a valid version number (like v1.3.4) and the highest version number of all tags/branches as being the `stable` version. So that's why this name gets an extra treatment. The Tornado project seems to suffer from this a little as you have a branch called `stable`. Now the reason why the link in the footer-popup (clicking `v: stable`) works is that this part of the page does not check for the special `stable` name (so actually it's broken for all projects that are not having a `stable` branch in the project) and the link at the top of the page "Edit on GitHub" is broken for your case as it checks for the special name. I will try to come up with a fix but currently I think for really making the "stable" special casing work, we might need to refactor how we store the branch/commit identifier information. I'll keep you posted. Ah, I didn't realize that about `stable`. I'm using the `stable` branch to do essentially the same thing by hand, so maybe I can just get rid of my branch. How would I replace my `stable` branch with an alias for `branch4.2` or tag `v4.2.1`? We are trying to figure out the stable branch ourself by parsing all available branch and tag names. The highest valid version number that is compliant to [PEP-440](https://www.python.org/dev/peps/pep-0440/) we be set as the stable branch. So if I just delete my `stable` branch from github, readthedocs will see that it's gone and replace it with one of my branches or tags? The second point of your issue will be addressed with #1650 @bdarnell Should work this way, yes. Maybe you need to push one commit (should be irrelevant which branch) since I don't know if the deletion of a branch triggers a post commit hook. The second point (bad links from the top right "Edit on GitHub" page) will be fixed with the next deploy as we have merged #1650 So is it fixed? The issue with the "Edit on Github" for auto-generated pages is still present. I just tried it in my local instance of RTD and I can see the link for auto-generated pages. Also, the last issue linked here from another repo is from November 2016. Regarding the second one and the branches, I'm not really sure to understand it or how to make a good test.
2017-11-23T07:54:25
readthedocs/readthedocs.org
3,306
readthedocs__readthedocs.org-3306
[ "3524" ]
90ac70d56ee741d8b7caeeda97ca63345b2ba239
diff --git a/readthedocs/doc_builder/config.py b/readthedocs/doc_builder/config.py --- a/readthedocs/doc_builder/config.py +++ b/readthedocs/doc_builder/config.py @@ -1,11 +1,14 @@ +# -*- coding: utf-8 -*- """An API to load config from a readthedocs.yml file.""" -from __future__ import absolute_import -from builtins import (filter, object) +from __future__ import ( + absolute_import, division, print_function, unicode_literals) -from readthedocs_build.config import (ConfigError, BuildConfig, InvalidConfig, - load as load_config) -from .constants import BUILD_IMAGES, DOCKER_IMAGE +from builtins import filter, object +from readthedocs_build.config import load as load_config +from readthedocs_build.config import BuildConfig, ConfigError, InvalidConfig + +from .constants import DOCKER_BUILD_IMAGES, DOCKER_IMAGE class ConfigWrapper(object): @@ -18,7 +21,6 @@ class ConfigWrapper(object): We only currently implement a subset of the existing YAML config. This should be the canonical source for our usage of the YAML files, never accessing the config object directly. - """ def __init__(self, version, yaml_config): @@ -53,10 +55,12 @@ def python_interpreter(self): if ver in [2, 3]: # Get the highest version of the major series version if user only # gave us a version of '2', or '3' - ver = max(list(filter( - lambda x: x < ver + 1, - self._yaml_config.get_valid_python_versions(), - ))) + ver = max( + list( + filter( + lambda x: x < ver + 1, + self._yaml_config.get_valid_python_versions(), + ))) return 'python{0}'.format(ver) @property @@ -118,8 +122,8 @@ def load_yaml_config(version): """ Load a configuration from `readthedocs.yml` file. - This uses the configuration logic from `readthedocs-build`, - which will keep parsing consistent between projects. + This uses the configuration logic from `readthedocs-build`, which will keep + parsing consistent between projects. """ checkout_path = version.project.checkout_path(version.slug) env_config = {} @@ -127,9 +131,9 @@ def load_yaml_config(version): # Get build image to set up the python version validation. Pass in the # build image python limitations to the loaded config so that the versions # can be rejected at validation - build_image = BUILD_IMAGES.get( + build_image = DOCKER_BUILD_IMAGES.get( version.project.container_image, - BUILD_IMAGES.get(DOCKER_IMAGE, None), + DOCKER_BUILD_IMAGES.get(DOCKER_IMAGE, None), ) if build_image: env_config = { @@ -147,7 +151,8 @@ def load_yaml_config(version): path=checkout_path, env_config=sphinx_env_config, )[0] - except InvalidConfig: # This is a subclass of ConfigError, so has to come first + except InvalidConfig: + # This is a subclass of ConfigError, so has to come first raise except ConfigError: config = BuildConfig( diff --git a/readthedocs/doc_builder/constants.py b/readthedocs/doc_builder/constants.py --- a/readthedocs/doc_builder/constants.py +++ b/readthedocs/doc_builder/constants.py @@ -1,22 +1,36 @@ -"""Doc build constants""" +# -*- coding: utf-8 -*- +"""Doc build constants.""" + +from __future__ import ( + absolute_import, division, print_function, unicode_literals) -from __future__ import absolute_import import os import re from django.conf import settings - -SPHINX_TEMPLATE_DIR = os.path.join(settings.SITE_ROOT, 'readthedocs', - 'templates', 'sphinx') -MKDOCS_TEMPLATE_DIR = os.path.join(settings.SITE_ROOT, 'readthedocs', - 'templates', 'mkdocs') +SPHINX_TEMPLATE_DIR = os.path.join( + settings.SITE_ROOT, + 'readthedocs', + 'templates', + 'sphinx', +) +MKDOCS_TEMPLATE_DIR = os.path.join( + settings.SITE_ROOT, + 'readthedocs', + 'templates', + 'mkdocs', +) SPHINX_STATIC_DIR = os.path.join(SPHINX_TEMPLATE_DIR, '_static') PDF_RE = re.compile('Output written on (.*?)') # Docker -DOCKER_SOCKET = getattr(settings, 'DOCKER_SOCKET', 'unix:///var/run/docker.sock') +DOCKER_SOCKET = getattr( + settings, + 'DOCKER_SOCKET', + 'unix:///var/run/docker.sock', +) DOCKER_VERSION = getattr(settings, 'DOCKER_VERSION', 'auto') DOCKER_IMAGE = getattr(settings, 'DOCKER_IMAGE', 'readthedocs/build:2.0') DOCKER_LIMITS = {'memory': '200m', 'time': 600} @@ -28,7 +42,7 @@ DOCKER_HOSTNAME_MAX_LEN = 64 # Build images -BUILD_IMAGES = { +DOCKER_BUILD_IMAGES = { 'readthedocs/build:1.0': { 'python': {'supported_versions': [2, 2.7, 3, 3.4]}, }, @@ -39,3 +53,4 @@ 'python': {'supported_versions': [2, 2.7, 3, 3.3, 3.4, 3.5, 3.6]}, }, } +DOCKER_BUILD_IMAGES.update(getattr(settings, 'DOCKER_BUILD_IMAGES', {}))
The changelog contains not merged PRs ## Details Chagelog http://docs.readthedocs.io/en/latest/changelog.html#version-2-1-4 Not merged PRs: - #3444 - #3463 - #3377 - #2699 How is the changelog generated?
2017-11-23T14:47:55
readthedocs/readthedocs.org
3,312
readthedocs__readthedocs.org-3312
[ "3308" ]
6a18b75ced695f695ffe363458eb6f02253fb907
diff --git a/readthedocs/projects/tasks.py b/readthedocs/projects/tasks.py --- a/readthedocs/projects/tasks.py +++ b/readthedocs/projects/tasks.py @@ -6,6 +6,7 @@ from __future__ import absolute_import +import datetime import hashlib import json import logging @@ -20,6 +21,7 @@ from celery.exceptions import SoftTimeLimitExceeded from django.conf import settings from django.core.urlresolvers import reverse +from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from readthedocs_build.config import ConfigError from slumber.exceptions import HttpClientError @@ -41,6 +43,7 @@ from readthedocs.core.symlink import PublicSymlink, PrivateSymlink from readthedocs.core.utils import send_email, broadcast from readthedocs.doc_builder.config import load_yaml_config +from readthedocs.doc_builder.constants import DOCKER_LIMITS from readthedocs.doc_builder.environments import (LocalEnvironment, DockerEnvironment) from readthedocs.doc_builder.exceptions import BuildEnvironmentError @@ -1005,3 +1008,48 @@ def sync_callback(_, version_pk, commit, *args, **kwargs): """ fileify(version_pk, commit=commit) update_search(version_pk, commit=commit) + + [email protected]() +def finish_inactive_builds(): + """ + Finish inactive builds. + + A build is consider inactive if it's not in ``FINISHED`` state and it has been + "running" for more time that the allowed one (``Project.container_time_limit`` + or ``DOCKER_LIMITS['time']`` plus a 20% of it). + + These inactive builds will be marked as ``success`` and ``FINISHED`` with an + ``error`` to be communicated to the user. + """ + time_limit = int(DOCKER_LIMITS['time'] * 1.2) + delta = datetime.timedelta(seconds=time_limit) + query = (~Q(state=BUILD_STATE_FINISHED) & + Q(date__lte=datetime.datetime.now() - delta)) + + builds_finished = 0 + builds = Build.objects.filter(query)[:50] + for build in builds: + + if build.project.container_time_limit: + custom_delta = datetime.timedelta( + seconds=int(build.project.container_time_limit)) + if build.date + custom_delta > datetime.datetime.now(): + # Do not mark as FINISHED builds with a custom time limit that wasn't + # expired yet (they are still building the project version) + continue + + build.success = False + build.state = BUILD_STATE_FINISHED + build.error = _( + 'This build was terminated due to inactivity. If you ' + 'continue to encounter this error, file a support ' + 'request with and reference this build id ({0}).'.format(build.pk) + ) + build.save() + builds_finished += 1 + + log.info( + 'Builds marked as "Terminated due inactivity": %s', + builds_finished, + ) diff --git a/readthedocs/restapi/views/footer_views.py b/readthedocs/restapi/views/footer_views.py --- a/readthedocs/restapi/views/footer_views.py +++ b/readthedocs/restapi/views/footer_views.py @@ -43,7 +43,7 @@ def get_version_compare_data(project, base_version=None): } if highest_version_obj: ret_val['url'] = highest_version_obj.get_absolute_url() - ret_val['slug'] = highest_version_obj.slug, + ret_val['slug'] = (highest_version_obj.slug,) if base_version and base_version.slug != LATEST: try: base_version_comparable = parse_version_failsafe(
diff --git a/readthedocs/rtd_tests/tests/test_project.py b/readthedocs/rtd_tests/tests/test_project.py --- a/readthedocs/rtd_tests/tests/test_project.py +++ b/readthedocs/rtd_tests/tests/test_project.py @@ -1,16 +1,24 @@ -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import ( + absolute_import, division, print_function, unicode_literals) + +import datetime import json + from django.test import TestCase -from readthedocs.builds.constants import LATEST -from readthedocs.projects.models import Project -from rest_framework.reverse import reverse from django_dynamic_fixture import get -from readthedocs.restapi.serializers import ProjectSerializer +from rest_framework.reverse import reverse + +from readthedocs.builds.constants import ( + BUILD_STATE_CLONING, BUILD_STATE_FINISHED, BUILD_STATE_TRIGGERED, LATEST) +from readthedocs.builds.models import Build +from readthedocs.projects.models import Project +from readthedocs.projects.tasks import finish_inactive_builds from readthedocs.rtd_tests.mocks.paths import fake_paths_by_regex class TestProject(TestCase): - fixtures = ["eric", "test_data"] + fixtures = ['eric', 'test_data'] def setUp(self): self.client.login(username='eric', password='test') @@ -40,17 +48,19 @@ def test_translations(self): self.assertEqual(response.status_code, 200) translation_ids_from_api = [ - t['id'] for t in response.data['translations']] + t['id'] for t in response.data['translations'] + ] translation_ids_from_orm = [ - t[0] for t in main_project.translations.values_list('id')] + t[0] for t in main_project.translations.values_list('id') + ] self.assertEqual( set(translation_ids_from_api), - set(translation_ids_from_orm) + set(translation_ids_from_orm), ) def test_translation_delete(self): - """Ensure translation deletion doesn't cascade up to main project""" + """Ensure translation deletion doesn't cascade up to main project.""" # In this scenario, a user has created a project and set the translation # to another project. If the user deletes this new project, the delete # operation shouldn't cascade up to the main project, and should instead @@ -62,12 +72,13 @@ def test_translation_delete(self): self.assertTrue(Project.objects.filter(pk=project_delete.pk).exists()) self.assertEqual( Project.objects.get(pk=project_keep.pk).main_language_project, - project_delete + project_delete, ) project_delete.delete() self.assertFalse(Project.objects.filter(pk=project_delete.pk).exists()) self.assertTrue(Project.objects.filter(pk=project_keep.pk).exists()) - self.assertIsNone(Project.objects.get(pk=project_keep.pk).main_language_project) + self.assertIsNone( + Project.objects.get(pk=project_keep.pk).main_language_project) def test_token(self): r = self.client.get('/api/v2/project/6/token/', {}) @@ -104,3 +115,63 @@ def test_has_epub_with_epub_build_disabled(self): self.pip.enable_epub_build = False with fake_paths_by_regex('\.epub$'): self.assertFalse(self.pip.has_epub(LATEST)) + + +class TestFinishInactiveBuildsTask(TestCase): + fixtures = ['eric', 'test_data'] + + def setUp(self): + self.client.login(username='eric', password='test') + self.pip = Project.objects.get(slug='pip') + + self.taggit = Project.objects.get(slug='taggit') + self.taggit.container_time_limit = 7200 # 2 hours + self.taggit.save() + + # Build just started with the default time + self.build_1 = Build.objects.create( + project=self.pip, + version=self.pip.get_stable_version(), + state=BUILD_STATE_CLONING, + ) + + # Build started an hour ago with default time + self.build_2 = Build.objects.create( + project=self.pip, + version=self.pip.get_stable_version(), + state=BUILD_STATE_TRIGGERED, + ) + self.build_2.date = ( + datetime.datetime.now() - datetime.timedelta(hours=1)) + self.build_2.save() + + # Build started an hour ago with custom time (2 hours) + self.build_3 = Build.objects.create( + project=self.taggit, + version=self.taggit.get_stable_version(), + state=BUILD_STATE_TRIGGERED, + ) + self.build_3.date = ( + datetime.datetime.now() - datetime.timedelta(hours=1)) + self.build_3.save() + + def test_finish_inactive_builds_task(self): + finish_inactive_builds() + + # Legitimate build (just started) not finished + self.build_1.refresh_from_db() + self.assertTrue(self.build_1.success) + self.assertEqual(self.build_1.error, '') + self.assertEqual(self.build_1.state, BUILD_STATE_CLONING) + + # Build with default time finished + self.build_2.refresh_from_db() + self.assertFalse(self.build_2.success) + self.assertNotEqual(self.build_2.error, '') + self.assertEqual(self.build_2.state, BUILD_STATE_FINISHED) + + # Build with custom time not finished + self.build_3.refresh_from_db() + self.assertTrue(self.build_3.success) + self.assertEqual(self.build_3.error, '') + self.assertEqual(self.build_3.state, BUILD_STATE_TRIGGERED)
Several recent consecutive builds are stuck in "Building" state ## Details * Project URL: http://esp-idf.readthedocs.io/en/latest/ * Build URL (if applicable): * https://readthedocs.org/projects/esp-idf/builds/6311619/ * https://readthedocs.org/projects/esp-idf/builds/6311059/ * https://readthedocs.org/projects/esp-idf/builds/6308949/ * https://readthedocs.org/projects/esp-idf/builds/6308480/ * https://readthedocs.org/projects/esp-idf/builds/6308479/ Initial enquiry done in https://github.com/rtfd/readthedocs.org/issues/3296#issuecomment-346633621 ## Expected Result Build should timeout instead of "Building" forever. ## Actual Result Builds are stuck in "Building" state. ![image](https://user-images.githubusercontent.com/12953787/33186130-78bde458-d087-11e7-899d-58d2a2e63082.png)
2017-11-23T22:46:05
readthedocs/readthedocs.org
3,326
readthedocs__readthedocs.org-3326
[ "2963" ]
6fd828216fede4a64259c5d5f199f8e4fd5163e1
diff --git a/readthedocs/projects/exceptions.py b/readthedocs/projects/exceptions.py --- a/readthedocs/projects/exceptions.py +++ b/readthedocs/projects/exceptions.py @@ -1,5 +1,8 @@ +# -*- coding: utf-8 -*- """Project exceptions.""" +from __future__ import division, print_function, unicode_literals + from django.conf import settings from django.utils.translation import ugettext_noop as _ @@ -15,6 +18,12 @@ class ProjectConfigurationError(BuildEnvironmentError): 'Make sure you have a conf.py file in your repository.' ) + MULTIPLE_CONF_FILES = _( + 'We found more than one conf.py and are not sure which one to use. ' + 'Please, specify the correct file under the Advanced settings tab ' + "in the project's Admin." + ) + class RepositoryError(BuildEnvironmentError): diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -1,15 +1,17 @@ +# -*- coding: utf-8 -*- """Project models.""" -from __future__ import absolute_import +from __future__ import ( + absolute_import, division, print_function, unicode_literals) import fnmatch import logging import os - from builtins import object # pylint: disable=redefined-builtin + from django.conf import settings from django.contrib.auth.models import User -from django.core.urlresolvers import reverse, NoReverseMatch +from django.core.urlresolvers import NoReverseMatch, reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @@ -24,19 +26,16 @@ from readthedocs.projects import constants from readthedocs.projects.exceptions import ProjectConfigurationError from readthedocs.projects.querysets import ( - ProjectQuerySet, - RelatedProjectQuerySet, - ChildRelatedProjectQuerySet, - FeatureQuerySet, -) + ChildRelatedProjectQuerySet, FeatureQuerySet, ProjectQuerySet, + RelatedProjectQuerySet) from readthedocs.projects.templatetags.projects_tags import sort_version_aware -from readthedocs.projects.version_handling import determine_stable_version, version_windows +from readthedocs.projects.version_handling import ( + determine_stable_version, version_windows) from readthedocs.restapi.client import api from readthedocs.vcs_support.backends import backend_cls from readthedocs.vcs_support.base import VCSProject from readthedocs.vcs_support.utils import Lock, NonBlockingLock - log = logging.getLogger(__name__) @@ -58,7 +57,7 @@ class ProjectRelationship(models.Model): objects = ChildRelatedProjectQuerySet.as_manager() def __str__(self): - return "%s -> %s" % (self.parent, self.child) + return '%s -> %s' % (self.parent, self.child) def save(self, *args, **kwargs): # pylint: disable=arguments-differ if not self.alias: @@ -139,26 +138,27 @@ class Project(models.Model): # Project features allow_comments = models.BooleanField(_('Allow Comments'), default=False) - comment_moderation = models.BooleanField(_('Comment Moderation'), default=False) + comment_moderation = models.BooleanField( + _('Comment Moderation'), default=False,) cdn_enabled = models.BooleanField(_('CDN Enabled'), default=False) analytics_code = models.CharField( _('Analytics code'), max_length=50, null=True, blank=True, - help_text=_("Google Analytics Tracking ID " - "(ex. <code>UA-22345342-1</code>). " - "This may slow down your page loads.")) + help_text=_('Google Analytics Tracking ID ' + '(ex. <code>UA-22345342-1</code>). ' + 'This may slow down your page loads.')) container_image = models.CharField( _('Alternative container image'), max_length=64, null=True, blank=True) container_mem_limit = models.CharField( _('Container memory limit'), max_length=10, null=True, blank=True, - help_text=_("Memory limit in Docker format " - "-- example: <code>512m</code> or <code>1g</code>")) + help_text=_('Memory limit in Docker format ' + '-- example: <code>512m</code> or <code>1g</code>')) container_time_limit = models.CharField( _('Container time limit'), max_length=10, null=True, blank=True) build_queue = models.CharField( _('Alternate build queue id'), max_length=32, null=True, blank=True) allow_promos = models.BooleanField( _('Allow paid advertising'), default=True, help_text=_( - "If unchecked, users will still see community ads.")) + 'If unchecked, users will still see community ads.')) # Sphinx specific build options. enable_epub_build = models.BooleanField( @@ -172,8 +172,8 @@ class Project(models.Model): # Other model data. path = models.CharField(_('Path'), max_length=255, editable=False, - help_text=_("The directory where " - "<code>conf.py</code> lives")) + help_text=_('The directory where ' + '<code>conf.py</code> lives')) conf_py_file = models.CharField( _('Python configuration file'), max_length=255, default='', blank=True, help_text=_('Path from project root to <code>conf.py</code> file ' @@ -185,8 +185,8 @@ class Project(models.Model): mirror = models.BooleanField(_('Mirror'), default=False) install_project = models.BooleanField( _('Install Project'), - help_text=_("Install your project inside a virtualenv using <code>setup.py " - "install</code>"), + help_text=_('Install your project inside a virtualenv using <code>setup.py ' + 'install</code>'), default=False ) @@ -197,13 +197,13 @@ class Project(models.Model): max_length=20, choices=constants.PYTHON_CHOICES, default='python', - help_text=_("(Beta) The Python interpreter used to create the virtual " - "environment.")) + help_text=_('(Beta) The Python interpreter used to create the virtual ' + 'environment.')) use_system_packages = models.BooleanField( _('Use system packages'), - help_text=_("Give the virtual environment access to the global " - "site-packages dir."), + help_text=_('Give the virtual environment access to the global ' + 'site-packages dir.'), default=False ) django_packages_url = models.CharField(_('Django Packages URL'), @@ -211,14 +211,14 @@ class Project(models.Model): privacy_level = models.CharField( _('Privacy Level'), max_length=20, choices=constants.PRIVACY_CHOICES, default=getattr(settings, 'DEFAULT_PRIVACY_LEVEL', 'public'), - help_text=_("(Beta) Level of privacy that you want on the repository. " - "Protected means public but not in listings.")) + help_text=_('(Beta) Level of privacy that you want on the repository. ' + 'Protected means public but not in listings.')) version_privacy_level = models.CharField( _('Version Privacy Level'), max_length=20, choices=constants.PRIVACY_CHOICES, default=getattr( settings, 'DEFAULT_PRIVACY_LEVEL', 'public'), - help_text=_("(Beta) Default level of privacy you want on built " - "versions of documentation.")) + help_text=_('(Beta) Default level of privacy you want on built ' + 'versions of documentation.')) # Subprojects related_projects = models.ManyToManyField( @@ -227,8 +227,8 @@ class Project(models.Model): # Language bits language = models.CharField(_('Language'), max_length=20, default='en', - help_text=_("The language the project " - "documentation is rendered in. " + help_text=_('The language the project ' + 'documentation is rendered in. ' "Note: this affects your project's URL."), choices=constants.LANGUAGES) @@ -236,7 +236,8 @@ class Project(models.Model): _('Programming Language'), max_length=20, default='words', - help_text=_("The primary programming language the project is written in."), + help_text=_( + 'The primary programming language the project is written in.'), choices=constants.PROGRAMMING_LANGUAGES, blank=True) # A subproject pointed at its main language, so it can be tracked main_language_project = models.ForeignKey('self', @@ -250,21 +251,21 @@ class Project(models.Model): default=2, null=True, blank=True, - help_text=_("2 means supporting 3.X.X and 2.X.X, but not 1.X.X") + help_text=_('2 means supporting 3.X.X and 2.X.X, but not 1.X.X') ) num_minor = models.IntegerField( _('Number of Minor versions'), default=2, null=True, blank=True, - help_text=_("2 means supporting 2.2.X and 2.1.X, but not 2.0.X") + help_text=_('2 means supporting 2.2.X and 2.1.X, but not 2.0.X') ) num_point = models.IntegerField( _('Number of Point versions'), default=2, null=True, blank=True, - help_text=_("2 means supporting 2.2.2 and 2.2.1, but not 2.2.0") + help_text=_('2 means supporting 2.2.2 and 2.2.1, but not 2.2.0') ) has_valid_webhook = models.BooleanField( @@ -296,7 +297,8 @@ def sync_supported_versions(self): verbose_name__in=supported).update(supported=True) self.versions.exclude( verbose_name__in=supported).update(supported=False) - self.versions.filter(verbose_name=LATEST_VERBOSE_NAME).update(supported=True) + self.versions.filter( + verbose_name=LATEST_VERBOSE_NAME).update(supported=True) def save(self, *args, **kwargs): # pylint: disable=arguments-differ from readthedocs.projects import tasks @@ -305,7 +307,7 @@ def save(self, *args, **kwargs): # pylint: disable=arguments-differ # Subdomains can't have underscores in them. self.slug = slugify(self.name) if self.slug == '': - raise Exception(_("Model must have slug")) + raise Exception(_('Model must have slug')) super(Project, self).save(*args, **kwargs) for owner in self.users.all(): assign('view_project', owner, self) @@ -325,12 +327,14 @@ def save(self, *args, **kwargs): # pylint: disable=arguments-differ log.exception('failed to sync supported versions') try: if not first_save: - broadcast(type='app', task=tasks.symlink_project, args=[self.pk]) + broadcast(type='app', task=tasks.symlink_project, + args=[self.pk],) except Exception: log.exception('failed to symlink project') try: if not first_save: - broadcast(type='app', task=tasks.update_static_metadata, args=[self.pk]) + broadcast( + type='app', task=tasks.update_static_metadata, args=[self.pk],) except Exception: log.exception('failed to update static metadata') try: @@ -473,19 +477,19 @@ def full_doc_path(self, version=LATEST): def artifact_path(self, type_, version=LATEST): """The path to the build html docs in the project.""" - return os.path.join(self.doc_path, "artifacts", version, type_) + return os.path.join(self.doc_path, 'artifacts', version, type_) def full_build_path(self, version=LATEST): """The path to the build html docs in the project.""" - return os.path.join(self.conf_dir(version), "_build", "html") + return os.path.join(self.conf_dir(version), '_build', 'html') def full_latex_path(self, version=LATEST): """The path to the build LaTeX docs in the project.""" - return os.path.join(self.conf_dir(version), "_build", "latex") + return os.path.join(self.conf_dir(version), '_build', 'latex') def full_epub_path(self, version=LATEST): """The path to the build epub docs in the project.""" - return os.path.join(self.conf_dir(version), "_build", "epub") + return os.path.join(self.conf_dir(version), '_build', 'epub') # There is currently no support for building man/dash formats, but we keep # the support there for existing projects. They might have already existing @@ -493,22 +497,22 @@ def full_epub_path(self, version=LATEST): def full_man_path(self, version=LATEST): """The path to the build man docs in the project.""" - return os.path.join(self.conf_dir(version), "_build", "man") + return os.path.join(self.conf_dir(version), '_build', 'man') def full_dash_path(self, version=LATEST): """The path to the build dash docs in the project.""" - return os.path.join(self.conf_dir(version), "_build", "dash") + return os.path.join(self.conf_dir(version), '_build', 'dash') def full_json_path(self, version=LATEST): """The path to the build json docs in the project.""" if 'sphinx' in self.documentation_type: - return os.path.join(self.conf_dir(version), "_build", "json") + return os.path.join(self.conf_dir(version), '_build', 'json') elif 'mkdocs' in self.documentation_type: - return os.path.join(self.checkout_path(version), "_build", "json") + return os.path.join(self.checkout_path(version), '_build', 'json') def full_singlehtml_path(self, version=LATEST): """The path to the build singlehtml docs in the project.""" - return os.path.join(self.conf_dir(version), "_build", "singlehtml") + return os.path.join(self.conf_dir(version), '_build', 'singlehtml') def rtd_build_path(self, version=LATEST): """The destination path where the built docs are copied.""" @@ -521,7 +525,8 @@ def static_metadata_path(self): def conf_file(self, version=LATEST): """Find a ``conf.py`` file in the project checkout.""" if self.conf_py_file: - conf_path = os.path.join(self.checkout_path(version), self.conf_py_file) + conf_path = os.path.join( + self.checkout_path(version), self.conf_py_file,) if os.path.exists(conf_path): log.info('Inserting conf.py file path from model') return conf_path @@ -533,8 +538,18 @@ def conf_file(self, version=LATEST): if len(files) == 1: return files[0] for filename in files: + # When multiples conf.py files, we look up the first one that + # contains the `doc` word in its path and return this one if filename.find('doc', 70) != -1: return filename + + # If the project has more than one conf.py file but none of them have + # the `doc` word in the path, we raise an error informing this to the user + if len(files) > 1: + raise ProjectConfigurationError( + ProjectConfigurationError.MULTIPLE_CONF_FILES + ) + raise ProjectConfigurationError( ProjectConfigurationError.NOT_FOUND ) @@ -636,7 +651,7 @@ def get_latest_build(self, finished=True): """ Get latest build for project. - finished -- Return only builds that are in a finished state + :param finished: Return only builds that are in a finished state """ kwargs = {'type': 'html'} if finished: @@ -688,7 +703,8 @@ def supported_versions(self): """ if not self.num_major or not self.num_minor or not self.num_point: return [] - version_identifiers = self.versions.values_list('verbose_name', flat=True) + version_identifiers = self.versions.values_list( + 'verbose_name', flat=True,) return version_windows( version_identifiers, major=self.num_major, @@ -715,7 +731,7 @@ def update_stable_version(self): new_stable.identifier != current_stable.identifier) if identifier_updated and current_stable.active and current_stable.machine: log.info( - "Update stable version: {project}:{version}".format( + 'Update stable version: {project}:{version}'.format( project=self.slug, version=new_stable.identifier)) current_stable.identifier = new_stable.identifier @@ -723,7 +739,7 @@ def update_stable_version(self): return new_stable else: log.info( - "Creating new stable version: {project}:{version}".format( + 'Creating new stable version: {project}:{version}'.format( project=self.slug, version=new_stable.identifier)) current_stable = self.versions.create_stable( @@ -964,14 +980,17 @@ class Domain(models.Model): ) canonical = models.BooleanField( default=False, - help_text=_('This Domain is the primary one where the documentation is served from') + help_text=_( + 'This Domain is the primary one where the documentation is ' + 'served from') ) https = models.BooleanField( _('Use HTTPS'), default=False, help_text=_('SSL is enabled for this domain') ) - count = models.IntegerField(default=0, help_text=_('Number of times this domain has been hit')) + count = models.IntegerField(default=0, help_text=_( + 'Number of times this domain has been hit'),) objects = RelatedProjectQuerySet.as_manager() @@ -979,7 +998,7 @@ class Meta(object): ordering = ('-canonical', '-machine', 'domain') def __str__(self): - return "{domain} pointed at {project}".format(domain=self.domain, project=self.project.name) + return '{domain} pointed at {project}'.format(domain=self.domain, project=self.project.name) def save(self, *args, **kwargs): # pylint: disable=arguments-differ from readthedocs.projects import tasks @@ -989,11 +1008,13 @@ def save(self, *args, **kwargs): # pylint: disable=arguments-differ else: self.domain = parsed.path super(Domain, self).save(*args, **kwargs) - broadcast(type='app', task=tasks.symlink_domain, args=[self.project.pk, self.pk]) + broadcast(type='app', task=tasks.symlink_domain, + args=[self.project.pk, self.pk],) def delete(self, *args, **kwargs): # pylint: disable=arguments-differ from readthedocs.projects import tasks - broadcast(type='app', task=tasks.symlink_domain, args=[self.project.pk, self.pk, True]) + broadcast(type='app', task=tasks.symlink_domain, + args=[self.project.pk, self.pk, True],) super(Domain, self).delete(*args, **kwargs) @@ -1051,7 +1072,7 @@ def add_features(sender, **kwargs): objects = FeatureQuerySet.as_manager() def __str__(self): - return "{0} feature".format( + return '{0} feature'.format( self.get_feature_display(), )
diff --git a/readthedocs/rtd_tests/tests/test_project.py b/readthedocs/rtd_tests/tests/test_project.py --- a/readthedocs/rtd_tests/tests/test_project.py +++ b/readthedocs/rtd_tests/tests/test_project.py @@ -7,11 +7,13 @@ from django.test import TestCase from django_dynamic_fixture import get +from mock import patch from rest_framework.reverse import reverse from readthedocs.builds.constants import ( BUILD_STATE_CLONING, BUILD_STATE_FINISHED, BUILD_STATE_TRIGGERED, LATEST) from readthedocs.builds.models import Build +from readthedocs.projects.exceptions import ProjectConfigurationError from readthedocs.projects.models import Project from readthedocs.projects.tasks import finish_inactive_builds from readthedocs.rtd_tests.mocks.paths import fake_paths_by_regex @@ -116,6 +118,45 @@ def test_has_epub_with_epub_build_disabled(self): with fake_paths_by_regex('\.epub$'): self.assertFalse(self.pip.has_epub(LATEST)) + @patch('readthedocs.projects.models.Project.find') + def test_conf_file_found(self, find_method): + find_method.return_value = [ + '/home/docs/rtfd/code/readthedocs.org/user_builds/pip/checkouts/latest/src/conf.py', + ] + self.assertEqual( + self.pip.conf_file(), + '/home/docs/rtfd/code/readthedocs.org/user_builds/pip/checkouts/latest/src/conf.py', + ) + + @patch('readthedocs.projects.models.Project.find') + def test_multiple_conf_file_one_doc_in_path(self, find_method): + find_method.return_value = [ + '/home/docs/rtfd/code/readthedocs.org/user_builds/pip/checkouts/latest/src/conf.py', + '/home/docs/rtfd/code/readthedocs.org/user_builds/pip/checkouts/latest/docs/conf.py', + ] + self.assertEqual( + self.pip.conf_file(), + '/home/docs/rtfd/code/readthedocs.org/user_builds/pip/checkouts/latest/docs/conf.py', + ) + + def test_conf_file_not_found(self): + with self.assertRaisesMessage( + ProjectConfigurationError, + ProjectConfigurationError.NOT_FOUND) as cm: + self.pip.conf_file() + + @patch('readthedocs.projects.models.Project.find') + def test_multiple_conf_files(self, find_method): + find_method.return_value = [ + '/home/docs/rtfd/code/readthedocs.org/user_builds/pip/checkouts/multi-conf.py/src/conf.py', + '/home/docs/rtfd/code/readthedocs.org/user_builds/pip/checkouts/multi-conf.py/src/sub/conf.py', + '/home/docs/rtfd/code/readthedocs.org/user_builds/pip/checkouts/multi-conf.py/src/sub/src/conf.py', + ] + with self.assertRaisesMessage( + ProjectConfigurationError, + ProjectConfigurationError.MULTIPLE_CONF_FILES) as cm: + self.pip.conf_file() + class TestFinishInactiveBuildsTask(TestCase): fixtures = ['eric', 'test_data']
Regressions with conf.py and error reporting Our search should be finding `conf.py` files in non-standard paths, but this is not happening automatically. We should be able to find and use a `conf.py` at least in any first level path. Additionally, when we aren't finding a conf.py, we were reporting this to the user. This is not happening either now, instead the user receives a message that an unknown error occured. Ref #2962
@agjohnson I would like to contribute, can you please give me a little guidance? @monvilafer hey! I was about to start working on this issue, are you still interested on contributing? Summarizing the steps that you will need: 1. Setup your dev env as: http://docs.readthedocs.io/en/latest/install.html 1. Import a project manually in your local RTD to test everything is working 1. Start here debugging, `conf_file` method that tries to get the real path: https://github.com/rtfd/readthedocs.org/blob/5a4fbc93d53a876de8f19a043c64a68a9a411ecc/readthedocs/projects/models.py#L515-L537 also, the `find` and `full_find` method are interesting for this: https://github.com/rtfd/readthedocs.org/blob/5a4fbc93d53a876de8f19a043c64a68a9a411ecc/readthedocs/projects/models.py#L605-L627 Yes!, I am working on it! I think to fix this issue we will need: - [ ] a repository with multiples `conf.py` (which one would be selected?) - [ ] a repo without a `conf.py` that produce an exception and clear error description for the user - [ ] a repo with a `conf.py` file in a non-standar path (`documentation/src/conf.py`, for example) Tip: I'm creating local repositories with `git init` and serving them with: git daemon --verbose --export-all --base-path=.git --reuseaddr --strict-paths .git/ then, I import the repository manually and use `git://localhost/` as URL. I think this could help you to clarify what it's needed here, @monvilafer. BTW, were you able to setup the development environment? I was able to reproduce this issue, but only in the commit mentioned in the other ticket (https://github.com/italia/anpr/commit/2196e3d). `latest` version builds properly in my local instance but that commit raises: ``` [27/Nov/2017 08:44:40] readthedocs.doc_builder.environments:319[32093]: ERROR (Build) [anprlocal:multi-conf.py] Conf file not found Traceback (most recent call last): File "/home/humitos/rtfd/code/readthedocs.org/readthedocs/projects/tasks.py", line 235, in run_build outcomes = self.build_docs() File "/home/humitos/rtfd/code/readthedocs.org/readthedocs/projects/tasks.py", line 430, in build_docs outcomes['html'] = self.build_docs_html() File "/home/humitos/rtfd/code/readthedocs.org/readthedocs/projects/tasks.py", line 447, in build_docs_html html_builder.append_conf() File "/home/humitos/rtfd/code/readthedocs.org/readthedocs/doc_builder/backends/sphinx.py", line 133, in append_conf six.reraise(ProjectImportError('Conf file not found'), None, trace) File "/home/humitos/rtfd/code/readthedocs.org/readthedocs/doc_builder/backends/sphinx.py", line 129, in append_conf outfile_path = self.project.conf_file(self.version.slug) File "/home/humitos/rtfd/code/readthedocs.org/readthedocs/projects/models.py", line 538, in conf_file u"Conf File Missing. Please make sure you have a conf.py in your project.") ProjectImportError: Conf file not found ``` That produces a not very well handled exception, ``` [27/Nov/2017 08:44:40] readthedocs.projects.tasks:135[32093]: ERROR An unhandled exception was raised outside the build environment Traceback (most recent call last): File "/home/humitos/rtfd/code/readthedocs.org/readthedocs/projects/tasks.py", line 131, in run self.run_build(record=record, docker=docker) File "/home/humitos/rtfd/code/readthedocs.org/readthedocs/projects/tasks.py", line 255, in run_build self.build_env.update_build(state=BUILD_STATE_FINISHED) File "/home/humitos/rtfd/code/readthedocs.org/readthedocs/doc_builder/environments.py", line 429, in update_build build_id=self.build['pk'] KeyError: 'pk' ``` ... and the build keeps in `Building` forever. The problem is this section ``` (Pdb++) l 527 files = self.find('conf.py', version) 528 if not files: 529 files = self.full_find('conf.py', version) 530 if len(files) == 1: 531 return files[0] 532 -> for filename in files: 533 if filename.find('doc', 70) != -1: 534 return filename 535 # Having this be translatable causes this odd error: 536 # ProjectImportError(<django.utils.functional.__proxy__ object at 537 # 0x1090cded0>,) (Pdb++) ``` It finaly raises the exception `ProjectImportError` because none of the files has `doc` on their path: ``` (Pdb++) pp files [u'/home/humitos/rtfd/code/readthedocs.org/user_builds/anprlocal/checkouts/multi-conf.py/src/conf.py', u'/home/humitos/rtfd/code/readthedocs.org/user_builds/anprlocal/checkouts/multi-conf.py/src/subentro/conf.py', u'/home/humitos/rtfd/code/readthedocs.org/user_builds/anprlocal/checkouts/multi-conf.py/src/subentro/src/conf.py'] ``` So, I think this logic is OK: "If there are more than one conf.py file and none of them has `doc` in their path, we don't know which one use" but maybe in this particular case, the error should be clearer > There are more than one conf.py file and none of them has `doc` in their path, we don't know which one use. Please, select the correct one under the `Advanced settings` tab in the project's settings. Instead of saying > Conf File Missing. Please make sure you have a conf.py in your project. BTW, that error is not showed either because nobody handles the `ProjectImportError`
2017-11-27T15:51:27
readthedocs/readthedocs.org
3,331
readthedocs__readthedocs.org-3331
[ "3268" ]
cd9802ef2a4d478d9ccb7696b5a99d33b297767b
diff --git a/readthedocs/projects/version_handling.py b/readthedocs/projects/version_handling.py --- a/readthedocs/projects/version_handling.py +++ b/readthedocs/projects/version_handling.py @@ -1,24 +1,37 @@ -"""Project version handling""" -from __future__ import absolute_import +# -*- coding: utf-8 -*- +"""Project version handling.""" +from __future__ import ( + absolute_import, division, print_function, unicode_literals) import unicodedata +from builtins import object, range from collections import defaultdict -from builtins import (object, range) -from packaging.version import Version -from packaging.version import InvalidVersion import six +from packaging.version import InvalidVersion, Version -from readthedocs.builds.constants import LATEST_VERBOSE_NAME -from readthedocs.builds.constants import STABLE_VERBOSE_NAME +from readthedocs.builds.constants import ( + LATEST_VERBOSE_NAME, STABLE_VERBOSE_NAME, TAG) def get_major(version): + """ + Return the major version. + + :param version: version to get the major + :type version: packaging.version.Version + """ # pylint: disable=protected-access return version._version.release[0] def get_minor(version): + """ + Return the minor version. + + :param version: version to get the minor + :type version: packaging.version.Version + """ # pylint: disable=protected-access try: return version._version.release[1] @@ -28,7 +41,7 @@ def get_minor(version): class VersionManager(object): - """Prune list of versions based on version windows""" + """Prune list of versions based on version windows.""" def __init__(self): self._state = defaultdict(lambda: defaultdict(list)) @@ -72,13 +85,13 @@ def get_version_list(self): versions.extend(version_list) versions = sorted(versions) return [ - version.public - for version in versions - if not version.is_prerelease] + version.public for version in versions if not version.is_prerelease + ] def version_windows(versions, major=1, minor=1, point=1): - """Return list of versions that have been pruned to version windows + """ + Return list of versions that have been pruned to version windows. Uses :py:class:`VersionManager` to prune the list of versions @@ -111,6 +124,18 @@ def version_windows(versions, major=1, minor=1, point=1): def parse_version_failsafe(version_string): + """ + Parse a version in string form and return Version object. + + If there is an error parsing the string, ``None`` is returned. + + :param version_string: version as string object (e.g. '3.10.1') + :type version_string: str or unicode + + :returns: version object created from a string object + + :rtype: packaging.version.Version + """ if not isinstance(version_string, six.text_type): uni_version = version_string.decode('utf-8') else: @@ -126,11 +151,19 @@ def parse_version_failsafe(version_string): def comparable_version(version_string): - """This can be used as ``key`` argument to ``sorted``. + """ + Can be used as ``key`` argument to ``sorted``. The ``LATEST`` version shall always beat other versions in comparison. ``STABLE`` should be listed second. If we cannot figure out the version number then we sort it to the bottom of the list. + + :param version_string: version as string object (e.g. '3.10.1' or 'latest') + :type version_string: str or unicode + + :returns: a comparable version object (e.g. 'latest' -> Version('99999.0')) + + :rtype: packaging.version.Version """ comparable = parse_version_failsafe(version_string) if not comparable: @@ -144,12 +177,16 @@ def comparable_version(version_string): def sort_versions(version_list): - """Takes a list of ``Version`` models and return a sorted list, + """ + Take a list of Version models and return a sorted list. - The returned value is a list of two-tuples. The first is the actual - ``Version`` model instance, the second is an instance of - ``packaging.version.Version``. They are ordered in descending order (latest - version first). + :param version_list: list of Version models + :type version_list: list(readthedocs.builds.models.Version) + + :returns: sorted list in descending order (latest version first) of versions + + :rtype: list(tupe(readthedocs.builds.models.Version, + packaging.version.Version)) """ versions = [] for version_obj in version_list: @@ -158,13 +195,20 @@ def sort_versions(version_list): if comparable_version: versions.append((version_obj, comparable_version)) - return list(sorted( - versions, - key=lambda version_info: version_info[1], - reverse=True)) + return list( + sorted( + versions, + key=lambda version_info: version_info[1], + reverse=True, + )) def highest_version(version_list): + """ + Return the highest version for a given ``version_list``. + + :rtype: tupe(readthedocs.builds.models.Version, packaging.version.Version) + """ versions = sort_versions(version_list) if versions: return versions[0] @@ -172,18 +216,29 @@ def highest_version(version_list): def determine_stable_version(version_list): - """Determine a stable version for version list + """ + Determine a stable version for version list. + + :param version_list: list of versions + :type version_list: list(readthedocs.builds.models.Version) - Takes a list of ``Version`` model instances and returns the version - instance which can be considered the most recent stable one. It will return - ``None`` if there is no stable version in the list. + :returns: version considered the most recent stable one or ``None`` if there + is no stable version in the list + + :rtype: readthedocs.builds.models.Version """ versions = sort_versions(version_list) - versions = [ - (version_obj, comparable) - for version_obj, comparable in versions - if not comparable.is_prerelease] + versions = [(version_obj, comparable) + for version_obj, comparable in versions + if not comparable.is_prerelease] + if versions: + # We take preference for tags over branches. If we don't find any tag, + # we just return the first branch found. + for version_obj, comparable in versions: + if version_obj.type == TAG: + return version_obj + version_obj, comparable = versions[0] return version_obj return None diff --git a/readthedocs/restapi/utils.py b/readthedocs/restapi/utils.py --- a/readthedocs/restapi/utils.py +++ b/readthedocs/restapi/utils.py @@ -13,12 +13,9 @@ def sync_versions(project, versions, type): # pylint: disable=redefined-builtin """Update the database with the current versions from the repository.""" - # Bookkeeping for keeping tag/branch identifies correct - verbose_names = [v['verbose_name'] for v in versions] - project.versions.filter(verbose_name__in=verbose_names).update(type=type) - old_versions = {} - old_version_values = project.versions.values('identifier', 'verbose_name') + old_version_values = project.versions.filter(type=type).values( + 'identifier', 'verbose_name') for version in old_version_values: old_versions[version['verbose_name']] = version['identifier'] diff --git a/readthedocs/restapi/views/footer_views.py b/readthedocs/restapi/views/footer_views.py --- a/readthedocs/restapi/views/footer_views.py +++ b/readthedocs/restapi/views/footer_views.py @@ -1,35 +1,41 @@ +# -*- coding: utf-8 -*- """Endpoint to generate footer HTML.""" -from __future__ import absolute_import +from __future__ import ( + absolute_import, division, print_function, unicode_literals) -from django.shortcuts import get_object_or_404 -from django.template import RequestContext, loader as template_loader +import six from django.conf import settings - - +from django.shortcuts import get_object_or_404 +from django.template import loader as template_loader from rest_framework import decorators, permissions from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework_jsonp.renderers import JSONPRenderer -from readthedocs.builds.constants import LATEST -from readthedocs.builds.constants import TAG +from readthedocs.builds.constants import LATEST, TAG from readthedocs.builds.models import Version from readthedocs.projects.models import Project -from readthedocs.projects.version_handling import highest_version -from readthedocs.projects.version_handling import parse_version_failsafe +from readthedocs.projects.version_handling import ( + highest_version, parse_version_failsafe) from readthedocs.restapi.signals import footer_response -import six def get_version_compare_data(project, base_version=None): - """Retrieve metadata about the highest version available for this project. + """ + Retrieve metadata about the highest version available for this project. :param base_version: We assert whether or not the base_version is also the highest version in the resulting "is_highest" value. """ + versions_qs = project.versions.public().filter(active=True) + + # Take preferences over tags only if the project has at least one tag + if versions_qs.filter(type=TAG).exists(): + versions_qs = versions_qs.filter(type=TAG) + highest_version_obj, highest_version_comparable = highest_version( - project.versions.public().filter(active=True)) + versions_qs) ret_val = { 'project': six.text_type(highest_version_obj), 'version': six.text_type(highest_version_comparable), @@ -69,32 +75,30 @@ def footer_html(request): subproject = request.GET.get('subproject', False) source_suffix = request.GET.get('source_suffix', '.rst') - new_theme = (theme == "sphinx_rtd_theme") - using_theme = (theme == "default") + new_theme = (theme == 'sphinx_rtd_theme') + using_theme = (theme == 'default') project = get_object_or_404(Project, slug=project_slug) version = get_object_or_404( - Version.objects.public(request.user, project=project, only_active=False), + Version.objects.public( + request.user, project=project, only_active=False), slug=version_slug) main_project = project.main_language_project or project - if page_slug and page_slug != "index": - if ( - main_project.documentation_type == "sphinx_htmldir" or - main_project.documentation_type == "mkdocs"): - path = page_slug + "/" - elif main_project.documentation_type == "sphinx_singlehtml": - path = "index.html#document-" + page_slug + if page_slug and page_slug != 'index': + if (main_project.documentation_type == 'sphinx_htmldir' or + main_project.documentation_type == 'mkdocs'): + path = page_slug + '/' + elif main_project.documentation_type == 'sphinx_singlehtml': + path = 'index.html#document-' + page_slug else: - path = page_slug + ".html" + path = page_slug + '.html' else: - path = "" + path = '' if version.type == TAG and version.project.has_pdf(version.slug): print_url = ( - 'https://keminglabs.com/print-the-docs/quote?project={project}&version={version}' - .format( - project=project.slug, - version=version.slug)) + 'https://keminglabs.com/print-the-docs/quote?project={project}&version={version}' # noqa + .format(project=project.slug, version=version.slug)) else: print_url = None @@ -115,14 +119,28 @@ def footer_html(request): 'settings': settings, 'subproject': subproject, 'print_url': print_url, - 'github_edit_url': version.get_github_url(docroot, page_slug, source_suffix, 'edit'), - 'github_view_url': version.get_github_url(docroot, page_slug, source_suffix, 'view'), - 'bitbucket_url': version.get_bitbucket_url(docroot, page_slug, source_suffix), + 'github_edit_url': version.get_github_url( + docroot, + page_slug, + source_suffix, + 'edit', + ), + 'github_view_url': version.get_github_url( + docroot, + page_slug, + source_suffix, + 'view', + ), + 'bitbucket_url': version.get_bitbucket_url( + docroot, + page_slug, + source_suffix, + ), 'theme': theme, } - html = template_loader.get_template('restapi/footer.html').render(context, - request) + html = template_loader.get_template('restapi/footer.html').render( + context, request) resp_data = { 'html': html, 'version_active': version.active, @@ -130,8 +148,9 @@ def footer_html(request): 'version_supported': version.supported, } - # Allow folks to hook onto the footer response for various information collection, - # or to modify the resp_data. - footer_response.send(sender=None, request=request, context=context, resp_data=resp_data) + # Allow folks to hook onto the footer response for various information + # collection, or to modify the resp_data. + footer_response.send( + sender=None, request=request, context=context, resp_data=resp_data) return Response(resp_data)
diff --git a/readthedocs/rtd_tests/tests/test_footer.py b/readthedocs/rtd_tests/tests/test_footer.py --- a/readthedocs/rtd_tests/tests/test_footer.py +++ b/readthedocs/rtd_tests/tests/test_footer.py @@ -1,12 +1,18 @@ -from __future__ import absolute_import -import mock +# -*- coding: utf-8 -*- +from __future__ import ( + absolute_import, division, print_function, unicode_literals) +import mock +from django.test import TestCase from rest_framework.test import APIRequestFactory, APITestCase +from readthedocs.builds.constants import BRANCH, LATEST, TAG +from readthedocs.builds.models import Version from readthedocs.core.middleware import FooterNoSessionMiddleware -from readthedocs.rtd_tests.mocks.paths import fake_paths_by_regex from readthedocs.projects.models import Project -from readthedocs.restapi.views.footer_views import footer_html +from readthedocs.restapi.views.footer_views import ( + footer_html, get_version_compare_data) +from readthedocs.rtd_tests.mocks.paths import fake_paths_by_regex class Testmaker(APITestCase): @@ -40,10 +46,10 @@ def test_footer(self): self.assertEqual(r.status_code, 200) def test_footer_uses_version_compare(self): - version_compare = 'readthedocs.restapi.views.footer_views.get_version_compare_data' + version_compare = 'readthedocs.restapi.views.footer_views.get_version_compare_data' # noqa with mock.patch(version_compare) as get_version_compare_data: get_version_compare_data.return_value = { - 'MOCKED': True + 'MOCKED': True, } r = self.render() self.assertEqual(r.status_code, 200) @@ -85,3 +91,117 @@ def test_no_session_logged_out(self): home_request = self.factory.get('/') mid.process_request(home_request) self.assertEqual(home_request.session.TEST_COOKIE_NAME, 'testcookie') + + +class TestVersionCompareFooter(TestCase): + fixtures = ['test_data'] + + def setUp(self): + self.pip = Project.objects.get(slug='pip') + + def test_highest_version_from_stable(self): + base_version = self.pip.get_stable_version() + valid_data = { + 'project': 'Version 0.8.1 of Pip (19)', + 'url': '/dashboard/pip/version/0.8.1/', + 'slug': ('0.8.1',), + 'version': '0.8.1', + 'is_highest': True, + } + returned_data = get_version_compare_data(self.pip, base_version) + self.assertDictEqual(valid_data, returned_data) + + def test_highest_version_from_lower(self): + base_version = self.pip.versions.get(slug='0.8') + valid_data = { + 'project': 'Version 0.8.1 of Pip (19)', + 'url': '/dashboard/pip/version/0.8.1/', + 'slug': ('0.8.1',), + 'version': '0.8.1', + 'is_highest': False, + } + returned_data = get_version_compare_data(self.pip, base_version) + self.assertDictEqual(valid_data, returned_data) + + def test_highest_version_from_latest(self): + Version.objects.create_latest(project=self.pip) + base_version = self.pip.versions.get(slug=LATEST) + valid_data = { + 'project': 'Version 0.8.1 of Pip (19)', + 'url': '/dashboard/pip/version/0.8.1/', + 'slug': ('0.8.1',), + 'version': '0.8.1', + 'is_highest': True, + } + returned_data = get_version_compare_data(self.pip, base_version) + self.assertDictEqual(valid_data, returned_data) + + def test_highest_version_over_branches(self): + Version.objects.create( + project=self.pip, + verbose_name='2.0.0', + identifier='2.0.0', + type=BRANCH, + active=True, + ) + + version = Version.objects.create( + project=self.pip, + verbose_name='1.0.0', + identifier='1.0.0', + type=TAG, + active=True, + ) + + base_version = self.pip.versions.get(slug='0.8.1') + valid_data = { + 'project': 'Version 1.0.0 of Pip ({})'.format(version.pk), + 'url': '/dashboard/pip/version/1.0.0/', + 'slug': ('1.0.0',), + 'version': '1.0.0', + 'is_highest': False, + } + returned_data = get_version_compare_data(self.pip, base_version) + self.assertDictEqual(valid_data, returned_data) + + def test_highest_version_without_tags(self): + self.pip.versions.filter(type=TAG).update(type=BRANCH) + + base_version = self.pip.versions.get(slug='0.8.1') + valid_data = { + 'project': 'Version 0.8.1 of Pip (19)', + 'url': '/dashboard/pip/version/0.8.1/', + 'slug': ('0.8.1',), + 'version': '0.8.1', + 'is_highest': True, + } + returned_data = get_version_compare_data(self.pip, base_version) + self.assertDictEqual(valid_data, returned_data) + + base_version = self.pip.versions.get(slug='0.8') + valid_data = { + 'project': 'Version 0.8.1 of Pip (19)', + 'url': '/dashboard/pip/version/0.8.1/', + 'slug': ('0.8.1',), + 'version': '0.8.1', + 'is_highest': False, + } + returned_data = get_version_compare_data(self.pip, base_version) + self.assertDictEqual(valid_data, returned_data) + + version = Version.objects.create( + project=self.pip, + verbose_name='2.0.0', + identifier='2.0.0', + type=BRANCH, + active=True, + ) + valid_data = { + 'project': 'Version 2.0.0 of Pip ({})'.format(version.pk), + 'url': '/dashboard/pip/version/2.0.0/', + 'slug': ('2.0.0',), + 'version': '2.0.0', + 'is_highest': False, + } + returned_data = get_version_compare_data(self.pip, base_version) + self.assertDictEqual(valid_data, returned_data) diff --git a/readthedocs/rtd_tests/tests/test_sync_versions.py b/readthedocs/rtd_tests/tests/test_sync_versions.py --- a/readthedocs/rtd_tests/tests/test_sync_versions.py +++ b/readthedocs/rtd_tests/tests/test_sync_versions.py @@ -1,26 +1,38 @@ # -*- coding: utf-8 -*- -from __future__ import absolute_import +from __future__ import ( + absolute_import, division, print_function, unicode_literals) + import json from django.test import TestCase +from readthedocs.builds.constants import BRANCH, STABLE, TAG from readthedocs.builds.models import Version -from readthedocs.builds.constants import STABLE from readthedocs.projects.models import Project class TestSyncVersions(TestCase): - fixtures = ["eric", "test_data"] + fixtures = ['eric', 'test_data'] def setUp(self): self.client.login(username='eric', password='test') self.pip = Project.objects.get(slug='pip') - Version.objects.create(project=self.pip, identifier='origin/master', - verbose_name='master', active=True, - machine=True) - Version.objects.create(project=self.pip, identifier='to_delete', - verbose_name='to_delete', active=False) + Version.objects.create( + project=self.pip, + identifier='origin/master', + verbose_name='master', + active=True, + machine=True, + type=BRANCH, + ) + Version.objects.create( + project=self.pip, + identifier='to_delete', + verbose_name='to_delete', + active=False, + type=TAG, + ) def test_proper_url_no_slash(self): version_post_data = { @@ -33,10 +45,11 @@ def test_proper_url_no_slash(self): 'identifier': 'origin/to_add', 'verbose_name': 'to_add', }, - ]} + ], + } r = self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -46,8 +59,12 @@ def test_proper_url_no_slash(self): def test_new_tag_update_active(self): - Version.objects.create(project=self.pip, identifier='0.8.3', - verbose_name='0.8.3', active=True) + Version.objects.create( + project=self.pip, + identifier='0.8.3', + verbose_name='0.8.3', + active=True, + ) version_post_data = { 'branches': [ @@ -69,22 +86,31 @@ def test_new_tag_update_active(self): 'identifier': '0.8.3', 'verbose_name': '0.8.3', }, - - ] + ], } self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) version_9 = Version.objects.get(slug='0.9') self.assertTrue(version_9.active) + # Version 0.9 becomes the stable version + self.assertEqual( + version_9.identifier, + self.pip.get_stable_version().identifier, + ) + def test_new_tag_update_inactive(self): - Version.objects.create(project=self.pip, identifier='0.8.3', - verbose_name='0.8.3', active=False) + Version.objects.create( + project=self.pip, + identifier='0.8.3', + verbose_name='0.8.3', + active=False, + ) version_post_data = { 'branches': [ @@ -106,21 +132,29 @@ def test_new_tag_update_inactive(self): 'identifier': '0.8.3', 'verbose_name': '0.8.3', }, - - ] + ], } self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) + # Version 0.9 becomes the stable version and active version_9 = Version.objects.get(slug='0.9') - self.assertTrue(version_9.active is False) + self.assertEqual( + version_9.identifier, + self.pip.get_stable_version().identifier, + ) + self.assertTrue(version_9.active) + + # Version 0.8.3 is still inactive + version_8 = Version.objects.get(slug='0.8.3') + self.assertFalse(version_8.active) class TestStableVersion(TestCase): - fixtures = ["eric", "test_data"] + fixtures = ['eric', 'test_data'] def setUp(self): self.client.login(username='eric', password='test') @@ -147,17 +181,16 @@ def test_stable_versions(self): 'identifier': '0.8', 'verbose_name': '0.8', }, - - ] + ], } self.assertRaises( Version.DoesNotExist, Version.objects.get, - slug=STABLE + slug=STABLE, ) self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -174,11 +207,11 @@ def test_pre_release_are_not_stable(self): {'identifier': '0.9b1', 'verbose_name': '0.9b1'}, {'identifier': '0.8', 'verbose_name': '0.8'}, {'identifier': '0.8rc2', 'verbose_name': '0.8rc2'}, - ] + ], } self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -192,11 +225,11 @@ def test_post_releases_are_stable(self): 'tags': [ {'identifier': '1.0', 'verbose_name': '1.0'}, {'identifier': '1.0.post1', 'verbose_name': '1.0.post1'}, - ] + ], } self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -210,12 +243,15 @@ def test_invalid_version_numbers_are_not_stable(self): version_post_data = { 'branches': [], 'tags': [ - {'identifier': 'this.is.invalid', 'verbose_name': 'this.is.invalid'}, - ] + { + 'identifier': 'this.is.invalid', + 'verbose_name': 'this.is.invalid' + }, + ], } self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -224,13 +260,19 @@ def test_invalid_version_numbers_are_not_stable(self): version_post_data = { 'branches': [], 'tags': [ - {'identifier': '1.0', 'verbose_name': '1.0'}, - {'identifier': 'this.is.invalid', 'verbose_name': 'this.is.invalid'}, - ] + { + 'identifier': '1.0', + 'verbose_name': '1.0', + }, + { + 'identifier': 'this.is.invalid', + 'verbose_name': 'this.is.invalid' + }, + ], } self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -255,11 +297,11 @@ def test_update_stable_version(self): 'identifier': '0.8', 'verbose_name': '0.8', }, - ] + ], } self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -278,7 +320,7 @@ def test_update_stable_version(self): } self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -293,11 +335,11 @@ def test_update_stable_version(self): 'identifier': '0.7', 'verbose_name': '0.7', }, - ] + ], } self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -319,11 +361,11 @@ def test_update_inactive_stable_version(self): 'identifier': '0.9', 'verbose_name': '0.9', }, - ] + ], } self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -339,7 +381,7 @@ def test_update_inactive_stable_version(self): }) self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) @@ -348,16 +390,80 @@ def test_update_inactive_stable_version(self): self.assertFalse(version_stable.active) self.assertEqual(version_stable.identifier, '1.0.0') + def test_stable_version_tags_over_branches(self): + version_post_data = { + 'branches': [ + # 2.0 development + {'identifier': 'origin/2.0', 'verbose_name': '2.0'}, + {'identifier': 'origin/0.9.1rc1', 'verbose_name': '0.9.1rc1'}, + ], + 'tags': [ + {'identifier': '1.0rc1', 'verbose_name': '1.0rc1'}, + {'identifier': '0.9', 'verbose_name': '0.9'}, + ], + } + + self.client.post( + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), + data=json.dumps(version_post_data), + content_type='application/json', + ) + + # If there is a branch with a higher version, tags takes preferences + # over the branches to select the stable version + version_stable = Version.objects.get(slug=STABLE) + self.assertTrue(version_stable.active) + self.assertEqual(version_stable.identifier, '0.9') + + version_post_data['tags'].append({ + 'identifier': '1.0', + 'verbose_name': '1.0', + }) + + self.client.post( + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), + data=json.dumps(version_post_data), + content_type='application/json', + ) + + version_stable = Version.objects.get(slug=STABLE) + self.assertTrue(version_stable.active) + self.assertEqual(version_stable.identifier, '1.0') + + def test_stable_version_same_id_tag_branch(self): + version_post_data = { + 'branches': [ + # old 1.0 development branch + {'identifier': 'origin/1.0', 'verbose_name': '1.0'}, + ], + 'tags': [ + # tagged 1.0 final version + {'identifier': '1.0', 'verbose_name': '1.0'}, + {'identifier': '0.9', 'verbose_name': '0.9'}, + ], + } + + self.client.post( + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), + data=json.dumps(version_post_data), + content_type='application/json', + ) + + version_stable = Version.objects.get(slug=STABLE) + self.assertTrue(version_stable.active) + self.assertEqual(version_stable.identifier, '1.0') + self.assertEqual(version_stable.type, 'tag') + def test_unicode(self): version_post_data = { 'branches': [], 'tags': [ {'identifier': 'foo-£', 'verbose_name': 'foo-£'}, - ] + ], } resp = self.client.post( - '/api/v2/project/%s/sync_versions/' % self.pip.pk, + '/api/v2/project/{}/sync_versions/'.format(self.pip.pk), data=json.dumps(version_post_data), content_type='application/json', ) diff --git a/requirements/testing.txt b/requirements/testing.txt --- a/requirements/testing.txt +++ b/requirements/testing.txt @@ -5,3 +5,6 @@ pytest-django==3.1.2 pytest-xdist==1.20.1 apipkg==1.4 execnet==1.5.0 + +# local debugging tools +pdbpp
"stable" appearing to track future release branches ## Details * Project URL: http://channels.readthedocs.io * Build URL (if applicable): http://channels.readthedocs.io/en/stable/ * Read the Docs username (if applicable): andrewgodwin ## Expected Result I expect the "stable" build version to only follow tags, not new branches, as described in http://docs.readthedocs.io/en/latest/versions.html ## Actual Result The "stable" build says it is following `origin/2.0`, which looks like a reference to a remote Git branch rather than the project's most recent tag, `1.1.8`, which means the "stable" docs have ended up being the in-development version docs. The "wipe" command does not appear to fix this, and I would like to avoid deleting and remaking the project just to see if it's a bad tag being stored somewhere.
```sh > git ls-remote --tags [email protected]:django/channels.git ``` Shows that the most recent tag is indeed 1.1.8. Looks like a bug to me. @andrewgodwin I just took a couple of screenshots of our JupyterHub configuration settings in RTD: This first screenshot shows the far right settings menu with Advanced Settings selected. <img width="596" alt="screenshot 2017-11-15 14 19 45" src="https://user-images.githubusercontent.com/2680980/32863539-ba50db46-ca10-11e7-8471-cc227bb5c3c6.png"> This screenshot shows the Versions page when selected from the far right settings menu (**This is different than the top level versions menu**). Double check that the versions desired match what you wish to build and see what SHA the stable version when enabled is picking up. <img width="604" alt="screenshot 2017-11-15 14 20 21" src="https://user-images.githubusercontent.com/2680980/32863540-ba6af8d2-ca10-11e7-801d-d993233110df.png"> If these settings are not correct, wipe will have no effect. Unfortunately, I can't see your settings. Let me know if you have further questions. Traveling the rest of the day but will be around tomorrow/Friday. There's not even a SHA in my stable build, there is `origin/2` again - here's screenshots of the same pages from the Channels project: ![snip1](https://user-images.githubusercontent.com/36182/32870888-cc31da0a-ca32-11e7-8b6e-4de5265a3d34.PNG) ![snip2](https://user-images.githubusercontent.com/36182/32870890-cfa7005c-ca32-11e7-891a-1602e8c8fbf4.PNG) I'll have to confirm this tomorrow, but my initial thoughts here are that we are in fact determining that the `2.0` branch is to take precedence over `1.x` series. If the `2.0` branch were to be named something along the lines of `2.0b1`, this might not surface. This isn't a good solution for your case, @andrewgodwin. Agreed that tags should probably take precedence over a branch name. I'm not fully certain of the best UX here though -- making versioning work for everyone is hard. Perhaps we need a way to turn off the handy wavy magic we do here to select a new version. I'll poke this tomorrow when I'm fresher. Right, I wasn't clear if `stable` was just tags or branches - I thought it was just tags, since we use branches for all sorts of things and haven't had this before (though I guess they didn't look like a version number). I don't mind too much what it is as long as it's well defined, but given I have a lot of links on the internet pointing to `/stable/`, some sort of alias/redirect-to-latest feature would be nice if it's determined this is working as intended, because right now people think my docs are broken. @agjohnson @andrewgodwin FWIW, one difference that we do with JupyterHub and friends is use a configuration file for RTD (`readthedocs.yml`) in the base of our project repo. - conda (environment.yml): https://github.com/jupyterhub/jupyterhub/blob/master/readthedocs.yml - pip (requirements.txt): https://github.com/jupyter/nbgrader/blob/master/readthedocs.yaml In setting up a test build on RTD (https://readthedocs.org/projects/test-channels/) using my fork as the source (https://github.com/willingc/channels) to see if the above configuration would change Andrew's build experience for stable, I discovered that trying to rebuild stable from the drop down selection on the main page or the build page results in a page with an API deprecation warning: Endpoint is deprecated <img width="1045" alt="screenshot 2017-11-16 10 10 20" src="https://user-images.githubusercontent.com/2680980/32908485-92a0dc10-cab8-11e7-80a9-a961e4555deb.png"> UI <img width="1045" alt="screenshot 2017-11-16 10 14 16" src="https://user-images.githubusercontent.com/2680980/32908486-92be9fac-cab8-11e7-886f-7d52ff37574f.png"> I think this is likely part of the problem. I, too, with the test build did not have a SHA for the stable version in the Versions page above. > I discovered that trying to rebuild stable from the drop down selection on the main page or the build page results in a page with an API deprecation warning Ups... Sorry. That's a bug that's already fixed in this PR at https://github.com/rtfd/readthedocs.org/pull/3260 Seems it's not deployed yet. It _shouldn't_ be related with andrew's issue regarding the `stable` version. @andrewgodwin if this goes on for longer without resolution lets just get a temporary redirect in at the web server level or something. I'll see if one of us can't get to this tomorrow, i ended up swamped with work today. Cool, thanks for your help on this! I did a quick test on my local instance and it was pretty easy to reproduce andrew's report. I created a git repo with `master` and `1.0` branches and one tag `0.9`. RTD mark `1.0` as `stable`. The code that decide the `stable` version is: https://github.com/rtfd/readthedocs.org/blob/7cbda6a9b318dc182cd304332a3045a1c53a4aef/readthedocs/projects/version_handling.py#L174-L189 where `version_list` is `Project.versions.all()` (this query includes branches and tags) and then in the `determine_stable_version` branch or tag doesn't matter, they are treated as the same. I wrote an horrible hack that make tags take preference over branches and I tested with the `channels` repo and `1.1.8` was what I got as `stable`, but I think we need to define in a clear way how we want this to work. I mean, how is the logic to decide what should be the sable verision. Once we have that defined and clear, I could try to write the chunk of code and test needed for this. It will probably involve touching other parts of the codebase also. What are you thoughts on the logic to decide the stable? Nice work @humitos. I'm cool with your logic. As a user, I would love to be able to provide a SHA commit for what I would like to have as stable and just have the default stable come in to play if I don't provide the SHA. Ah, I did wonder if it was something like that. For reference, the "versions" doc at http://docs.readthedocs.io/en/latest/versions.html describes stable as `We also create a stable version, if your project has any tagged releases`, so I had thought it was already preferring tags. > As a user, I would love to be able to provide a SHA commit for what I would like to have as stable and just have the default stable come in to play if I don't provide the SHA. That could be a good feature. But, suposing that the `stable` version would be working properly, I think it shouldn't be necessary and it could make more confusion maybe. Anyway, I will create a new issue to discuss about this feature and not mix with this report. That's why I wanted to more feedback on how the stable version should be determined to think in some cases that "take preference of tags over branches" won't work for a project/user. > We also create a stable version, if your project has any tagged releases Well, this sentence is very confusing for me because of that comma. My English knowledge doesn't help here. I suppose that it has the same meaning than "If your project has any tagged releases, we also create a stable version". So, I understand that the `stable` version is only created when your project doesn't have any tagged release, that's not the case of channels and the `stable` is created anyway, right? If I'm right, we should re-write that chunk of the documentation also. Channels does indeed have tagged releases, quite a few of them - the most recent being `1.1.8`
2017-11-29T15:36:32
readthedocs/readthedocs.org
3,387
readthedocs__readthedocs.org-3387
[ "2922" ]
b7434c09cfe086db3c67dec865c4f8cc13951049
diff --git a/readthedocs/projects/forms.py b/readthedocs/projects/forms.py --- a/readthedocs/projects/forms.py +++ b/readthedocs/projects/forms.py @@ -570,9 +570,10 @@ def clean_domain(self): def clean_canonical(self): canonical = self.cleaned_data['canonical'] + _id = self.initial.get('id') if canonical and Domain.objects.filter( - project=self.project, canonical=True).exclude( - domain=self.cleaned_data['domain']).exists(): + project=self.project, canonical=True + ).exclude(pk=_id).exists(): raise forms.ValidationError( _('Only 1 Domain can be canonical at a time.')) return canonical
diff --git a/readthedocs/rtd_tests/tests/test_domains.py b/readthedocs/rtd_tests/tests/test_domains.py --- a/readthedocs/rtd_tests/tests/test_domains.py +++ b/readthedocs/rtd_tests/tests/test_domains.py @@ -81,6 +81,26 @@ def test_https(self): project=self.project) self.assertFalse(form.is_valid()) + def test_canonical_change(self): + """Make sure canonical can be properly changed""" + form = DomainForm({'domain': 'example.com', 'canonical': True}, + project=self.project) + self.assertTrue(form.is_valid()) + domain = form.save() + self.assertEqual(domain.domain, 'example.com') + + form = DomainForm({'domain': 'example2.com', 'canonical': True}, + project=self.project) + self.assertFalse(form.is_valid()) + self.assertEqual(form.errors['canonical'][0], 'Only 1 Domain can be canonical at a time.') + + form = DomainForm({'domain': 'example2.com', 'canonical': True}, + project=self.project, + instance=domain) + self.assertTrue(form.is_valid()) + domain = form.save() + self.assertEqual(domain.domain, 'example2.com') + class TestAPI(TestCase):
Can't edit canonical domain ## Details Putting in a canonical domain and then trying to change the domain name results in "Only 1 Domain can be canonical at a time." ## Expected Result Domain is updated with new domain name ## Actual Result Form errors.
2017-12-08T18:40:56
readthedocs/readthedocs.org
3,400
readthedocs__readthedocs.org-3400
[ "3199" ]
1a053bdf358b29494a81055885029cfb7c60bf43
diff --git a/readthedocs/settings/base.py b/readthedocs/settings/base.py --- a/readthedocs/settings/base.py +++ b/readthedocs/settings/base.py @@ -77,7 +77,6 @@ def INSTALLED_APPS(self): # noqa 'django_gravatar', 'rest_framework', 'corsheaders', - 'copyright', 'textclassifier', 'annoying', 'django_extensions', @@ -315,7 +314,6 @@ def INSTALLED_APPS(self): # noqa # Misc application settings GLOBAL_ANALYTICS_CODE = 'UA-17997319-1' GRAVATAR_DEFAULT_IMAGE = 'https://media.readthedocs.org/images/silhouette.png' # NOQA - COPY_START_YEAR = 2010 RESTRICTEDSESSIONS_AUTHED_ONLY = True RESTRUCTUREDTEXT_FILTER_SETTINGS = { 'cloak_email_addresses': True,
Remove copyright application This was brought up in review and not handled. Doesn't look like we need it any longer?
Hi! I'm new to rtd. Is this referring to removing from base.py? Greetings! 👋 It is, though the `copyright` application is likely called somewhere else in code as well. It shouldn't take much work at all, but I haven't looked into removing this yet. If you want to try removing this, our development installation guide is here: http://docs.readthedocs.io/en/latest/install.html#installing-read-the-docs Original PR here: #1300 Cool! I'll give it a try =) Thanks for replying so quickly! I would like to do an PR, or are you working on this, @kikisdeliveryservice?
2017-12-14T13:56:51
readthedocs/readthedocs.org
3,427
readthedocs__readthedocs.org-3427
[ "3203" ]
6fd828216fede4a64259c5d5f199f8e4fd5163e1
diff --git a/readthedocs/builds/models.py b/readthedocs/builds/models.py --- a/readthedocs/builds/models.py +++ b/readthedocs/builds/models.py @@ -146,6 +146,7 @@ def commit_name(self): # If we came that far it's not a special version nor a branch or tag. # Therefore just return the identifier to make a safe guess. + log.error('TODO: Raise an exception here. Testing what cases it happens') return self.identifier def get_absolute_url(self): diff --git a/readthedocs/restapi/serializers.py b/readthedocs/restapi/serializers.py --- a/readthedocs/restapi/serializers.py +++ b/readthedocs/restapi/serializers.py @@ -73,6 +73,7 @@ class Meta(object): 'identifier', 'verbose_name', 'active', 'built', 'downloads', + 'type', )
diff --git a/readthedocs/rtd_tests/tests/test_api.py b/readthedocs/rtd_tests/tests/test_api.py --- a/readthedocs/rtd_tests/tests/test_api.py +++ b/readthedocs/rtd_tests/tests/test_api.py @@ -1,23 +1,25 @@ -from __future__ import absolute_import +# -*- coding: utf-8 -*- +from __future__ import ( + absolute_import, division, print_function, unicode_literals) -import json import base64 import datetime +import json +from builtins import str import mock -from builtins import str -from django.test import TestCase +from allauth.socialaccount.models import SocialAccount from django.contrib.auth.models import User +from django.core.urlresolvers import reverse +from django.test import TestCase from django_dynamic_fixture import get from rest_framework import status from rest_framework.test import APIClient -from allauth.socialaccount.models import SocialAccount from readthedocs.builds.models import Build, Version from readthedocs.integrations.models import Integration -from readthedocs.projects.models import Project, Feature -from readthedocs.oauth.models import RemoteRepository, RemoteOrganization - +from readthedocs.oauth.models import RemoteOrganization, RemoteRepository +from readthedocs.projects.models import Feature, Project super_auth = base64.b64encode(b'super:test').decode('utf-8') eric_auth = base64.b64encode(b'eric:test').decode('utf-8') @@ -27,9 +29,7 @@ class APIBuildTests(TestCase): fixtures = ['eric.json', 'test_data.json'] def test_make_build(self): - """ - Test that a superuser can use the API - """ + """Test that a superuser can use the API.""" client = APIClient() client.login(username='super', password='test') resp = client.post( @@ -42,7 +42,8 @@ def test_make_build(self): 'error': 'Test Error', 'state': 'cloning', }, - format='json') + format='json', + ) self.assertEqual(resp.status_code, status.HTTP_201_CREATED) build = resp.data self.assertEqual(build['state_display'], 'Cloning') @@ -54,7 +55,7 @@ def test_make_build(self): self.assertEqual(build['state_display'], 'Cloning') def test_make_build_without_permission(self): - """Ensure anonymous/non-staff users cannot write the build endpoint""" + """Ensure anonymous/non-staff users cannot write the build endpoint.""" client = APIClient() def _try_post(): @@ -67,7 +68,8 @@ def _try_post(): 'output': 'Test Output', 'error': 'Test Error', }, - format='json') + format='json', + ) self.assertEqual(resp.status_code, 403) _try_post() @@ -78,7 +80,7 @@ def _try_post(): _try_post() def test_update_build_without_permission(self): - """Ensure anonymous/non-staff users cannot update build endpoints""" + """Ensure anonymous/non-staff users cannot update build endpoints.""" client = APIClient() api_user = get(User, staff=False, password='test') client.force_authenticate(user=api_user) @@ -88,13 +90,15 @@ def test_update_build_without_permission(self): { 'project': 1, 'version': 1, - 'state': 'finished' + 'state': 'finished', }, - format='json') + format='json', + ) self.assertEqual(resp.status_code, 403) def test_make_build_protected_fields(self): - """Ensure build api view delegates correct serializer + """ + Ensure build api view delegates correct serializer. Super users should be able to read/write the `builder` property, but we don't expose this to end users via the API @@ -113,7 +117,7 @@ def test_make_build_protected_fields(self): self.assertIn('builder', resp.data) def test_make_build_commands(self): - """Create build and build commands""" + """Create build and build commands.""" client = APIClient() client.login(username='super', password='test') resp = client.post( @@ -123,7 +127,8 @@ def test_make_build_commands(self): 'version': 1, 'success': True, }, - format='json') + format='json', + ) self.assertEqual(resp.status_code, status.HTTP_201_CREATED) build = resp.data now = datetime.datetime.utcnow() @@ -137,7 +142,8 @@ def test_make_build_commands(self): 'start_time': str(now - datetime.timedelta(seconds=5)), 'end_time': str(now), }, - format='json') + format='json', + ) self.assertEqual(resp.status_code, status.HTTP_201_CREATED) resp = client.get('/api/v2/build/%s/' % build['id']) self.assertEqual(resp.status_code, 200) @@ -151,20 +157,24 @@ class APITests(TestCase): fixtures = ['eric.json', 'test_data.json'] def test_make_project(self): - """ - Test that a superuser can use the API - """ - post_data = {"name": "awesome-project", - "repo": "https://github.com/ericholscher/django-kong.git"} - resp = self.client.post('/api/v1/project/', - data=json.dumps(post_data), - content_type='application/json', - HTTP_AUTHORIZATION=u'Basic %s' % super_auth) + """Test that a superuser can use the API.""" + post_data = { + 'name': 'awesome-project', + 'repo': 'https://github.com/ericholscher/django-kong.git', + } + resp = self.client.post( + '/api/v1/project/', + data=json.dumps(post_data), + content_type='application/json', + HTTP_AUTHORIZATION='Basic %s' % super_auth, + ) self.assertEqual(resp.status_code, 201) - self.assertEqual(resp['location'], - '/api/v1/project/24/') - resp = self.client.get('/api/v1/project/24/', data={'format': 'json'}, - HTTP_AUTHORIZATION=u'Basic %s' % eric_auth) + self.assertEqual(resp['location'], '/api/v1/project/24/') + resp = self.client.get( + '/api/v1/project/24/', + data={'format': 'json'}, + HTTP_AUTHORIZATION='Basic %s' % eric_auth, + ) self.assertEqual(resp.status_code, 200) obj = json.loads(resp.content) self.assertEqual(obj['slug'], 'awesome-project') @@ -187,44 +197,41 @@ def test_user_doesnt_get_full_api_return(self): self.assertEqual(resp.data['conf_py_file'], 'foo') def test_invalid_make_project(self): - """ - Test that the authentication is turned on. - """ - post_data = {"user": "/api/v1/user/2/", - "name": "awesome-project-2", - "repo": "https://github.com/ericholscher/django-bob.git" - } + """Test that the authentication is turned on.""" + post_data = { + 'user': '/api/v1/user/2/', + 'name': 'awesome-project-2', + 'repo': 'https://github.com/ericholscher/django-bob.git', + } resp = self.client.post( - '/api/v1/project/', data=json.dumps(post_data), + '/api/v1/project/', + data=json.dumps(post_data), content_type='application/json', - HTTP_AUTHORIZATION=u'Basic %s' % base64.b64encode(b'tester:notapass').decode('utf-8') + HTTP_AUTHORIZATION='Basic %s' % + base64.b64encode(b'tester:notapass').decode('utf-8'), ) self.assertEqual(resp.status_code, 401) def test_make_project_dishonest_user(self): - """ - Test that you can't create a project for another user - """ + """Test that you can't create a project for another user.""" # represents dishonest data input, authentication happens for user 2 post_data = { - "users": ["/api/v1/user/1/"], - "name": "awesome-project-2", - "repo": "https://github.com/ericholscher/django-bob.git" + 'users': ['/api/v1/user/1/'], + 'name': 'awesome-project-2', + 'repo': 'https://github.com/ericholscher/django-bob.git', } resp = self.client.post( '/api/v1/project/', data=json.dumps(post_data), content_type='application/json', - HTTP_AUTHORIZATION=u'Basic %s' % base64.b64encode(b'tester:test').decode('utf-8') + HTTP_AUTHORIZATION='Basic %s' % + base64.b64encode(b'tester:test').decode('utf-8'), ) self.assertEqual(resp.status_code, 401) def test_ensure_get_unauth(self): - """ - Test that GET requests work without authenticating. - """ - - resp = self.client.get("/api/v1/project/", data={"format": "json"}) + """Test that GET requests work without authenticating.""" + resp = self.client.get('/api/v1/project/', data={'format': 'json'}) self.assertEqual(resp.status_code, 200) def test_project_features(self): @@ -233,7 +240,7 @@ def test_project_features(self): # One explicit, one implicit feature feature1 = get(Feature, projects=[project]) feature2 = get(Feature, projects=[], default_true=True) - feature3 = get(Feature, projects=[], default_true=False) + feature3 = get(Feature, projects=[], default_true=False) # noqa client = APIClient() client.force_authenticate(user=user) @@ -242,7 +249,7 @@ def test_project_features(self): self.assertIn('features', resp.data) self.assertEqual( resp.data['features'], - [feature1.feature_id, feature2.feature_id] + [feature1.feature_id, feature2.feature_id], ) def test_project_features_multiple_projects(self): @@ -256,20 +263,17 @@ def test_project_features_multiple_projects(self): resp = client.get('/api/v2/project/%s/' % (project1.pk)) self.assertEqual(resp.status_code, 200) self.assertIn('features', resp.data) - self.assertEqual( - resp.data['features'], - [feature.feature_id] - ) + self.assertEqual(resp.data['features'], [feature.feature_id]) class APIImportTests(TestCase): - """Import API endpoint tests""" + """Import API endpoint tests.""" fixtures = ['eric.json', 'test_data.json'] def test_permissions(self): - """Ensure user repositories aren't leaked to other users""" + """Ensure user repositories aren't leaked to other users.""" client = APIClient() account_a = get(SocialAccount, provider='github') @@ -279,33 +283,35 @@ def test_permissions(self): user_b = get(User, password='test', socialaccount_set=[account_b]) user_c = get(User, password='test', socialaccount_set=[account_c]) org_a = get(RemoteOrganization, users=[user_a], account=account_a) - repo_a = get(RemoteRepository, users=[user_a], organization=org_a, - account=account_a) - repo_b = get(RemoteRepository, users=[user_b], organization=None, - account=account_b) + repo_a = get( + RemoteRepository, + users=[user_a], + organization=org_a, + account=account_a, + ) + repo_b = get( + RemoteRepository, + users=[user_b], + organization=None, + account=account_b, + ) client.force_authenticate(user=user_a) - resp = client.get( - '/api/v2/remote/repo/', - format='json') + resp = client.get('/api/v2/remote/repo/', format='json') self.assertEqual(resp.status_code, status.HTTP_200_OK) repos = resp.data['results'] self.assertEqual(repos[0]['id'], repo_a.id) self.assertEqual(repos[0]['organization']['id'], org_a.id) self.assertEqual(len(repos), 1) - resp = client.get( - '/api/v2/remote/org/', - format='json') + resp = client.get('/api/v2/remote/org/', format='json') self.assertEqual(resp.status_code, status.HTTP_200_OK) orgs = resp.data['results'] self.assertEqual(orgs[0]['id'], org_a.id) self.assertEqual(len(orgs), 1) client.force_authenticate(user=user_b) - resp = client.get( - '/api/v2/remote/repo/', - format='json') + resp = client.get('/api/v2/remote/repo/', format='json') self.assertEqual(resp.status_code, status.HTTP_200_OK) repos = resp.data['results'] self.assertEqual(repos[0]['id'], repo_b.id) @@ -313,9 +319,7 @@ def test_permissions(self): self.assertEqual(len(repos), 1) client.force_authenticate(user=user_c) - resp = client.get( - '/api/v2/remote/repo/', - format='json') + resp = client.get('/api/v2/remote/repo/', format='json') self.assertEqual(resp.status_code, status.HTTP_200_OK) repos = resp.data['results'] self.assertEqual(len(repos), 0) @@ -324,7 +328,7 @@ def test_permissions(self): @mock.patch('readthedocs.core.views.hooks.trigger_build') class IntegrationsTests(TestCase): - """Integration for webhooks, etc""" + """Integration for webhooks, etc.""" fixtures = ['eric.json', 'test_data.json'] @@ -333,27 +337,25 @@ def setUp(self): self.version = get(Version, verbose_name='master', project=self.project) def test_github_webhook(self, trigger_build): - """GitHub webhook API""" + """GitHub webhook API.""" client = APIClient() - resp = client.post( + client.post( '/api/v2/webhook/github/{0}/'.format(self.project.slug), {'ref': 'master'}, format='json', ) - trigger_build.assert_has_calls([ - mock.call(force=True, version=mock.ANY, project=self.project) - ]) - resp = client.post( + trigger_build.assert_has_calls( + [mock.call(force=True, version=mock.ANY, project=self.project)]) + client.post( '/api/v2/webhook/github/{0}/'.format(self.project.slug), {'ref': 'non-existent'}, format='json', ) - trigger_build.assert_has_calls([ - mock.call(force=True, version=mock.ANY, project=self.project) - ]) + trigger_build.assert_has_calls( + [mock.call(force=True, version=mock.ANY, project=self.project)]) def test_github_invalid_webhook(self, trigger_build): - """GitHub webhook unhandled event""" + """GitHub webhook unhandled event.""" client = APIClient() resp = client.post( '/api/v2/webhook/github/{0}/'.format(self.project.slug), @@ -365,27 +367,25 @@ def test_github_invalid_webhook(self, trigger_build): self.assertEqual(resp.data['detail'], 'Unhandled webhook event') def test_gitlab_webhook(self, trigger_build): - """GitLab webhook API""" + """GitLab webhook API.""" client = APIClient() - resp = client.post( + client.post( '/api/v2/webhook/gitlab/{0}/'.format(self.project.slug), {'object_kind': 'push', 'ref': 'master'}, format='json', ) - trigger_build.assert_has_calls([ - mock.call(force=True, version=mock.ANY, project=self.project) - ]) - resp = client.post( + trigger_build.assert_has_calls( + [mock.call(force=True, version=mock.ANY, project=self.project)]) + client.post( '/api/v2/webhook/gitlab/{0}/'.format(self.project.slug), {'object_kind': 'push', 'ref': 'non-existent'}, format='json', ) - trigger_build.assert_has_calls([ - mock.call(force=True, version=mock.ANY, project=self.project) - ]) + trigger_build.assert_has_calls( + [mock.call(force=True, version=mock.ANY, project=self.project)]) def test_gitlab_invalid_webhook(self, trigger_build): - """GitLab webhook unhandled event""" + """GitLab webhook unhandled event.""" client = APIClient() resp = client.post( '/api/v2/webhook/gitlab/{0}/'.format(self.project.slug), @@ -396,50 +396,45 @@ def test_gitlab_invalid_webhook(self, trigger_build): self.assertEqual(resp.data['detail'], 'Unhandled webhook event') def test_bitbucket_webhook(self, trigger_build): - """Bitbucket webhook API""" + """Bitbucket webhook API.""" client = APIClient() - resp = client.post( + client.post( '/api/v2/webhook/bitbucket/{0}/'.format(self.project.slug), { 'push': { 'changes': [{ 'new': { - 'name': 'master' - } - }] - } + 'name': 'master', + }, + }], + }, }, format='json', ) - trigger_build.assert_has_calls([ - mock.call(force=True, version=mock.ANY, project=self.project) - ]) - resp = client.post( + trigger_build.assert_has_calls( + [mock.call(force=True, version=mock.ANY, project=self.project)]) + client.post( '/api/v2/webhook/bitbucket/{0}/'.format(self.project.slug), { 'push': { - 'changes': [{ - 'new': { - 'name': 'non-existent' - } - }] - } + 'changes': [ + { + 'new': {'name': 'non-existent'}, + }, + ], + }, }, format='json', ) - trigger_build.assert_has_calls([ - mock.call(force=True, version=mock.ANY, project=self.project) - ]) + trigger_build.assert_has_calls( + [mock.call(force=True, version=mock.ANY, project=self.project)]) def test_bitbucket_invalid_webhook(self, trigger_build): - """Bitbucket webhook unhandled event""" + """Bitbucket webhook unhandled event.""" client = APIClient() resp = client.post( '/api/v2/webhook/bitbucket/{0}/'.format(self.project.slug), - {'foo': 'bar'}, - format='json', - HTTP_X_EVENT_KEY='pull_request' - ) + {'foo': 'bar'}, format='json', HTTP_X_EVENT_KEY='pull_request') self.assertEqual(resp.status_code, 200) self.assertEqual(resp.data['detail'], 'Unhandled webhook event') @@ -453,18 +448,21 @@ def test_generic_api_fails_without_auth(self, trigger_build): self.assertEqual(resp.status_code, 403) self.assertEqual( resp.data['detail'], - 'Authentication credentials were not provided.' + 'Authentication credentials were not provided.', ) def test_generic_api_respects_token_auth(self, trigger_build): client = APIClient() integration = Integration.objects.create( project=self.project, - integration_type=Integration.API_WEBHOOK + integration_type=Integration.API_WEBHOOK, ) self.assertIsNotNone(integration.token) resp = client.post( - '/api/v2/webhook/{0}/{1}/'.format(self.project.slug, integration.pk), + '/api/v2/webhook/{0}/{1}/'.format( + self.project.slug, + integration.pk, + ), {'token': integration.token}, format='json', ) @@ -472,7 +470,10 @@ def test_generic_api_respects_token_auth(self, trigger_build): self.assertTrue(resp.data['build_triggered']) # Test nonexistent branch resp = client.post( - '/api/v2/webhook/{0}/{1}/'.format(self.project.slug, integration.pk), + '/api/v2/webhook/{0}/{1}/'.format( + self.project.slug, + integration.pk, + ), {'token': integration.token, 'branches': 'nonexistent'}, format='json', ) @@ -497,14 +498,84 @@ def test_generic_api_falls_back_to_token_auth(self, trigger_build): user = get(User) client.force_authenticate(user=user) integration = Integration.objects.create( - project=self.project, - integration_type=Integration.API_WEBHOOK - ) + project=self.project, integration_type=Integration.API_WEBHOOK) self.assertIsNotNone(integration.token) resp = client.post( - '/api/v2/webhook/{0}/{1}/'.format(self.project.slug, integration.pk), + '/api/v2/webhook/{0}/{1}/'.format( + self.project.slug, + integration.pk, + ), {'token': integration.token}, format='json', ) self.assertEqual(resp.status_code, 200) self.assertTrue(resp.data['build_triggered']) + + +class APIVersionTests(TestCase): + fixtures = ['eric', 'test_data'] + + def test_get_version_by_id(self): + """ + Test the full response of ``/api/v2/version/{pk}`` is what we expects. + + Allows us to notice changes in the fields returned by the endpoint + instead of let them pass silently. + """ + pip = Project.objects.get(slug='pip') + version = pip.versions.get(slug='0.8') + + data = { + 'pk': version.pk, + } + resp = self.client.get( + reverse('version-detail', kwargs=data), + content_type='application/json', + HTTP_AUTHORIZATION='Basic {}'.format(eric_auth), + ) + self.assertEqual(resp.status_code, 200) + + version_data = { + 'type': 'tag', + 'verbose_name': '0.8', + 'built': False, + 'id': 18, + 'active': True, + 'project': { + 'analytics_code': None, + 'canonical_url': 'http://readthedocs.org/docs/pip/en/latest/', + 'cdn_enabled': False, + 'conf_py_file': '', + 'container_image': None, + 'container_mem_limit': None, + 'container_time_limit': None, + 'default_branch': None, + 'default_version': 'latest', + 'description': '', + 'documentation_type': 'sphinx', + 'enable_epub_build': True, + 'enable_pdf_build': True, + 'features': ['allow_deprecated_webhooks'], + 'id': 6, + 'install_project': False, + 'language': 'en', + 'name': 'Pip', + 'python_interpreter': 'python', + 'repo': 'https://github.com/pypa/pip', + 'repo_type': 'git', + 'requirements_file': None, + 'skip': False, + 'slug': 'pip', + 'suffix': '.rst', + 'use_system_packages': False, + 'users': [1], + }, + 'downloads': {}, + 'identifier': '2404a34eba4ee9c48cc8bc4055b99a48354f4950', + 'slug': '0.8', + } + + self.assertDictEqual( + resp.data, + version_data, + )
links to github are broken ## Details * Project URL: sequana.readthedocs, bioservices.readthedocs, bioconvert.readtheodocs and more * Build URL (if applicable): http://sequana.readthedocs.io/en/master/ * Read the Docs username (if applicable): cokelaer ## Expected Result link should work (there were working) ## Actual Result links broken due to additional "origin" added in the links to github.
Broken here too: http://docs.ev3dev.org/en/ev3dev-stretch/index.html We have the same issue https://identityserver4.readthedocs.io/en/release/ any comment on this? Can we fix that somehow ourselves? AFAIC, the problem is still there for the projects mentioned above. I think this is the PR that fixes this issue: https://github.com/rtfd/readthedocs.org/pull/3302 @humitos I think this issue is specifically about the local remote alias being added to the version name, Github knows nothing of `origin/` which is currently part of `github_version` being used in the template. I've trying to reproduce this bug in my local instance using the `sequana` project but I wasn't able yet. On one hand, the `commit_name` property used in all the Version objects is correct and on the other hand, I wasn't able to build the documentation because the project fail with an issue that's not related to RTD. @cokelaer please, let me know when I can get a success build and I will try again with this project. I will try to debug this issue again with the other projects linked in this ticket (probably tomorrow) and I will comment here the results. Thanks for the reports. @humitos here are some examples of live projects with broken Edit buttons: http://django-wiki.readthedocs.io/en/master/ http://discretize.simpeg.xyz/en/master/ Bioservices project has the Same issue and may be easier to install or one of the projet that @benjaoming just mentionned. I believe the issues are all related. Could be pbl with à newer version of sphinx maybe? OK, I think I have "something to say" after my little research. It seems that this _only happens_ with the `master` branch. I just built `django-wiki` and `discretize` both using `latest` version and links works properly. Then I activated the `master` branch on those projects and the Github link start pointing to the wrong link (adding the "origin" to the URL). This is happening because in the `Version.commit_name` the value of `self.type` is `unknown` and it doesn't enter to this if, https://github.com/rtfd/readthedocs.org/blob/6fd828216fede4a64259c5d5f199f8e4fd5163e1/readthedocs/builds/models.py#L139 so it returns `self.identifier` which is `origin/master`. Now, I need to find/understand why the `Version` is detected as `unknown` instead of a `branch`. Sorry, I got confused with `discrete`. It's using the `dev` branch as `latest` and it's has the problem with the links to GH on that branch. It doesn't have the problem in `stable`.
2017-12-20T18:18:49
readthedocs/readthedocs.org
3,447
readthedocs__readthedocs.org-3447
[ "3351" ]
9bcb5fb2fe491ff68ac1466618344ce2347404e2
diff --git a/readthedocs/doc_builder/base.py b/readthedocs/doc_builder/base.py --- a/readthedocs/doc_builder/base.py +++ b/readthedocs/doc_builder/base.py @@ -1,11 +1,14 @@ +# -*- coding: utf-8 -*- """Base classes for Builders.""" -from __future__ import absolute_import -from builtins import object -from functools import wraps -import os +from __future__ import ( + absolute_import, division, print_function, unicode_literals) + import logging +import os import shutil +from builtins import object +from functools import wraps log = logging.getLogger(__name__) @@ -19,6 +22,7 @@ def decorator(*args, **kw): return fn(*args, **kw) finally: os.chdir(path) + return decorator @@ -27,11 +31,12 @@ class BaseBuilder(object): """ The Base for all Builders. Defines the API for subclasses. - Expects subclasses to define ``old_artifact_path``, - which points at the directory where artifacts should be copied from. + Expects subclasses to define ``old_artifact_path``, which points at the + directory where artifacts should be copied from. """ _force = False + # old_artifact_path = .. def __init__(self, build_env, python_env, force=False): @@ -41,13 +46,11 @@ def __init__(self, build_env, python_env, force=False): self.project = build_env.project self._force = force self.target = self.project.artifact_path( - version=self.version.slug, - type_=self.type - ) + version=self.version.slug, type_=self.type) def force(self, **__): """An optional step to force a build even when nothing has changed.""" - log.info("Forcing a build") + log.info('Forcing a build') self._force = True def build(self): @@ -59,16 +62,16 @@ def move(self, **__): if os.path.exists(self.old_artifact_path): if os.path.exists(self.target): shutil.rmtree(self.target) - log.info("Copying %s on the local filesystem", self.type) + log.info('Copying %s on the local filesystem', self.type) shutil.copytree(self.old_artifact_path, self.target) else: - log.warning("Not moving docs, because the build dir is unknown.") + log.warning('Not moving docs, because the build dir is unknown.') def clean(self, **__): - """Clean the path where documentation will be built""" + """Clean the path where documentation will be built.""" if os.path.exists(self.old_artifact_path): shutil.rmtree(self.old_artifact_path) - log.info("Removing old artifact path: %s", self.old_artifact_path) + log.info('Removing old artifact path: %s', self.old_artifact_path) def docs_dir(self, docs_dir=None, **__): """Handle creating a custom docs_dir if it doesn't exist.""" @@ -87,9 +90,11 @@ def create_index(self, extension='md', **__): """Create an index file if it needs it.""" docs_dir = self.docs_dir() - index_filename = os.path.join(docs_dir, 'index.{ext}'.format(ext=extension)) + index_filename = os.path.join( + docs_dir, 'index.{ext}'.format(ext=extension)) if not os.path.exists(index_filename): - readme_filename = os.path.join(docs_dir, 'README.{ext}'.format(ext=extension)) + readme_filename = os.path.join( + docs_dir, 'README.{ext}'.format(ext=extension)) if os.path.exists(readme_filename): return 'README' else: @@ -101,9 +106,13 @@ def create_index(self, extension='md', **__): This is an autogenerated index file. -Please create a ``{dir}/index.{ext}`` or ``{dir}/README.{ext}`` file with your own content. +Please create an ``index.{ext}`` or ``README.{ext}`` file with your own content +under the root (or ``/docs``) directory in your repository. If you want to use another markup, choose a different builder in your settings. +Check out our `Getting Started Guide +<https://docs.readthedocs.io/en/latest/getting_started.html>`_ to become more +familiar with Read the Docs. """ index_file.write(index_text.format(dir=docs_dir, ext=extension)) @@ -111,5 +120,5 @@ def create_index(self, extension='md', **__): return 'index' def run(self, *args, **kwargs): - """Proxy run to build environment""" + """Proxy run to build environment.""" return self.build_env.run(*args, **kwargs)
Invalid message on just imported / simple repositories When you create a project in github with just a `README.md` and import it on RTD, you get this message: ![captura de pantalla_2017-12-04_10-14-16](https://user-images.githubusercontent.com/244656/33559815-fee4658c-d8db-11e7-8d03-f1324102758f.png) This message is wrong since the PATH of those failes are invalid/useless for the user. I think this is generated by Sphinx automatically, so I'm not sure if we can change that easily.
Where is generated this file? The only relevant file I found is this https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/doc_builder/templates/doc_builder/conf.py.tmpl :/ Maybe passing some additional context? Not really sure but IIRC this file is generated by Sphinx itself, maybe that _it's something_ that could help you to find out :/ Found! https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/doc_builder/base.py#L104 So, what should we put on there? Something like this? > Create an index file on _your repository_ (or docs). Nice! Please create an ``index.{ext}`` or ``README.{ext}`` file with your own content under the root directory in your repository (or under ``/docs`` directory). Maybe something like that? @humitos PR on the way!
2017-12-26T00:19:07
readthedocs/readthedocs.org
3,464
readthedocs__readthedocs.org-3464
[ "2600", "2600" ]
bc248aa6a7d2bb54e88e779fe4f78b9f0266acf4
diff --git a/readthedocs/projects/migrations/0030_change-max-length-project-slug.py b/readthedocs/projects/migrations/0030_change-max-length-project-slug.py new file mode 100644 --- /dev/null +++ b/readthedocs/projects/migrations/0030_change-max-length-project-slug.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.16 on 2018-11-01 20:55 +from __future__ import unicode_literals + +from django.db import migrations, models +from django.db.models.functions import Length + + +def forwards_func(apps, schema_editor): + max_length = 63 + Project = apps.get_model('projects', 'Project') + projects_invalid_slug = ( + Project + .objects + .annotate(slug_length=Length('slug')) + .filter(slug_length__gt=max_length) + ) + for project in projects_invalid_slug: + project.slug = project.slug[:max_length] + project.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ('projects', '0029_add_additional_languages'), + ] + + operations = [ + migrations.RunPython(forwards_func), + migrations.AlterField( + model_name='project', + name='slug', + field=models.SlugField(max_length=63, unique=True, verbose_name='Slug'), + ), + ] diff --git a/readthedocs/projects/models.py b/readthedocs/projects/models.py --- a/readthedocs/projects/models.py +++ b/readthedocs/projects/models.py @@ -81,7 +81,8 @@ class Project(models.Model): users = models.ManyToManyField(User, verbose_name=_('User'), related_name='projects') name = models.CharField(_('Name'), max_length=255) - slug = models.SlugField(_('Slug'), max_length=255, unique=True) + # A DNS label can contain up to 63 characters. + slug = models.SlugField(_('Slug'), max_length=63, unique=True) description = models.TextField(_('Description'), blank=True, help_text=_('The reStructuredText ' 'description of the project'))
Project slug names that are not valid DNS names are not caught on project creation A sufficiently long enough project name will still be linked from RTD, but the DNS lookup will fail viewing these docs. We should be double checking for slugs that would be 63 characters or more and failing validation. Project slug names that are not valid DNS names are not caught on project creation A sufficiently long enough project name will still be linked from RTD, but the DNS lookup will fail viewing these docs. We should be double checking for slugs that would be 63 characters or more and failing validation.
2017-12-29T22:00:39