Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 43 additions & 9 deletions conda_lock/conda_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ def make_lock_files( # noqa: C901
with_cuda: str | None = None,
strip_auth: bool = False,
mapping_url: str,
) -> None:
) -> bool:
"""
Generate a lock file from the src files provided

Expand Down Expand Up @@ -322,6 +322,11 @@ def make_lock_files( # noqa: C901
None will pick a default version and warn if cuda packages are installed.
metadata_yamls:
YAML or JSON file(s) containing structured metadata to add to metadata section of the lockfile.

Returns
-------
bool
Whether any lockfile was written.
"""
# Compute lock specification
filtered_categories: Set[str] | None = None
Expand Down Expand Up @@ -421,6 +426,7 @@ def make_lock_files( # noqa: C901
)
platforms_to_lock = sorted(set(platforms_to_lock))

written = False
if not platforms_to_lock:
new_lock_content = original_lock_content
else:
Expand Down Expand Up @@ -460,6 +466,7 @@ def make_lock_files( # noqa: C901
lockfile_path,
metadata_choices=metadata_choices,
)
written = True
print(
" - Install lock using:",
KIND_USE_TEXT["lock"].format(lockfile=str(lockfile_path)),
Expand All @@ -485,14 +492,15 @@ def make_lock_files( # noqa: C901
logger.warning(_implicit_cuda_message)
break

do_render(
rendered = do_render(
new_lock_content,
kinds=[k for k in kinds if k != "lock"],
include_dev_dependencies=include_dev_dependencies,
filename_template=filename_template,
extras=extras,
check_input_hash=check_input_hash,
)
return written or rendered


def do_render(
Expand All @@ -503,7 +511,7 @@ def do_render(
extras: Set[str] | None = None,
check_input_hash: bool = False,
override_platform: Sequence[str] | None = None,
) -> None:
) -> bool:
"""Render the lock content for each platform in lockfile

Parameters
Expand All @@ -522,6 +530,11 @@ def do_render(
Do not re-render if specifications are unchanged
override_platform :
Generate only this subset of the platform files

Returns
-------
bool
Whether any output was rendered.
"""
platforms = lockfile.metadata.platforms
if override_platform is not None and len(override_platform) > 0:
Expand All @@ -544,6 +557,7 @@ def do_render(
)
sys.exit(1)

rendered = False
for plat in platforms:
for kind in kinds:
if filename_template:
Expand All @@ -561,6 +575,7 @@ def do_render(
else:
filename = f"conda-{plat}.lock"

filename += KIND_FILE_EXT[kind]
if pathlib.Path(filename).exists() and check_input_hash:
with open(filename) as f:
previous_hash = extract_input_hash(f.read())
Expand All @@ -580,9 +595,9 @@ def do_render(
platform=plat,
)

filename += KIND_FILE_EXT[kind]
with open(filename, "w") as fo:
fo.write("\n".join(lockfile_contents) + "\n")
rendered = True

print(
f" - Install lock using {'(see warning below)' if kind == 'env' else ''}:",
Expand All @@ -601,6 +616,7 @@ def do_render(
"makes them useful when updating existing environments.",
file=sys.stderr,
)
return rendered


def render_lockfile_for_platform( # noqa: C901
Expand Down Expand Up @@ -1183,7 +1199,8 @@ def run_lock(
metadata_yamls: Sequence[pathlib.Path] = (),
strip_auth: bool = False,
mapping_url: str,
) -> None:
) -> bool:
"""Generate lockfiles and return whether any lockfile was written."""
if len(environment_files) == 0:
environment_files = handle_no_specified_source_files(lockfile_path)

Expand All @@ -1195,7 +1212,7 @@ def run_lock(
).strip()
logger.debug(f"Executable has version: {version_info}")

make_lock_files(
return make_lock_files(
conda=_conda_exe,
src_files=environment_files,
platform_overrides=platforms,
Expand Down Expand Up @@ -1319,7 +1336,13 @@ def main() -> None:
"--check-input-hash",
is_flag=True,
default=False,
help="Check existing input hashes in lockfiles before regenerating lock files. If no files were updated exit with exit code 4. Incompatible with --strip-auth",
help="Check existing input hashes in lockfiles before regenerating lock files. Incompatible with --strip-auth",
)
@click.option(
"--fail-on-no-change",
is_flag=True,
default=False,
help="Exit with status 4 if no lockfiles are written. Requires --check-input-hash; incompatible with --strip-auth.",
)
@click.option(
"--log-level",
Expand Down Expand Up @@ -1401,6 +1424,7 @@ def lock(
extras: Sequence[str],
filter_categories: bool,
check_input_hash: bool,
fail_on_no_change: bool,
log_level: TLogLevel,
pdb: bool,
virtual_package_spec: PathLike | None,
Expand All @@ -1426,6 +1450,14 @@ def lock(
version: The version of conda-lock used to generate this lock file.
timestamp: The approximate timestamp of the output file in ISO8601 basic format.
"""
if fail_on_no_change:
if not check_input_hash:
raise click.UsageError("--fail-on-no-change requires --check-input-hash.")
if strip_auth:
raise click.UsageError(
"--fail-on-no-change is incompatible with --strip-auth."
)

logging.basicConfig(level=log_level, force=True)

# Set the flag for deleting temporary paths (files/dirs)
Expand Down Expand Up @@ -1491,7 +1523,9 @@ def lock(
lockfile_content = _strip_auth_from_lockfile(lockfile_content)
write_file(lockfile_content, os.path.join(filename_template_dir, file))
else:
lock_func(filename_template=filename_template)
changed = lock_func(filename_template=filename_template)
if fail_on_no_change and not changed:
ctx.exit(4)


DEFAULT_INSTALL_OPT_MAMBA = HAVE_MAMBA
Expand Down Expand Up @@ -1840,7 +1874,7 @@ def render(
"--check-input-hash",
is_flag=True,
default=None,
help="Check existing input hashes in lockfiles before regenerating lock files. If no files were updated exit with exit code 4. Incompatible with --strip-auth",
help="Check existing input hashes in lockfiles before regenerating lock files. Incompatible with --strip-auth",
hidden=True,
)
@click.option(
Expand Down
27 changes: 24 additions & 3 deletions docs/flags.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,35 @@ When generating lockfiles that make use of extras it is recommended to make use

## --check-input-hash

Under some situation you may want to run conda lock in some kind of automated way (eg as a precommit) and want to not
need to regenerate the lockfiles if the underlying input specification for that particular lock as not changed.
Use `--check-input-hash` to skip regenerating lockfiles when their input specification
has not changed, for example in a pre-commit hook.

```bash
conda-lock --check-input-hash --platform linux-64
```

When the input_hash of the input files, channels match those present in a given lockfile, that lockfile will not be regenerated.
Matching input hashes allow conda-lock to skip solving platforms already present in
the unified lockfile and skip rendering existing explicit or environment lockfiles.
By default, a successful command exits with status 0 even when every output is skipped.

### --fail-on-no-change

Add `--fail-on-no-change` when a script needs to distinguish skipped outputs from
regeneration:

```bash
conda-lock --check-input-hash --fail-on-no-change --platform linux-64
```

With both flags, a successful command exits with:

- **4** if no lockfiles were written because their input hashes already match.
- **0** if any lockfile was written, including a missing rendered output or an update
to just one platform. Writing a file counts even if its contents are identical.

Errors keep their usual exit status. `--fail-on-no-change` requires
`--check-input-hash` and cannot be combined with `--strip-auth`.
Leave it off in pre-commit hooks, where skipping unchanged outputs should succeed.

---

Expand Down
Loading
Loading