Skip to content

Commit

Permalink
Collect crate metadata during 'prepare' phase of build
Browse files Browse the repository at this point in the history
* If metadata collection fails for some reason, it would be good if we
  hadn't already performed any operations on the package.
* It would be good to have the metadata earlier in the process so we
  can use it in other operations.
  • Loading branch information
cottsay committed Dec 19, 2024
1 parent bb6308e commit c56a200
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions colcon_cargo/task/cargo/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,16 @@ async def build( # noqa: D102
elif build_dir.exists():
shutil.rmtree(build_dir)

# Invoke build step
if CARGO_EXECUTABLE is None:
raise RuntimeError("Could not find 'cargo' executable")

# Get package metadata
metadata = await self._get_metadata(env)

cargo_args = args.cargo_args
if cargo_args is None:
cargo_args = []
# Invoke build step
cmd = self._build_cmd(cargo_args)

self.progress('build')
Expand All @@ -85,7 +88,7 @@ async def build( # noqa: D102
# We also need to check if the package has any binaries, because if it
# has no binaries then cargo install will return an error.
cmd = self._install_cmd(cargo_args)
if cmd is not None and await self._has_binaries(env):
if cmd is not None and self._has_binaries(metadata):
self.progress('install')
rc = await run(
self.context, cmd, cwd=self.context.pkg.path, env=env)
Expand Down Expand Up @@ -141,15 +144,17 @@ def _install_cmd(self, cargo_args):
cmd += ['--profile', 'dev']
return cmd + cargo_args

# Identify if there are any binaries to install for the current package
async def _has_binaries(self, env):
async def _get_metadata(self, env):
cmd = [
CARGO_EXECUTABLE,
'metadata',
'--no-deps',
'--format-version', '1',
]

# TODO: The reported target_directory is wrong. Does it matter here?
# We could maybe override it with --config

rc = await run(
self.context,
cmd,
Expand All @@ -167,7 +172,11 @@ async def _has_binaries(self, env):
"Failed to capture stdout from 'cargo metadata'"
)

metadata = json.loads(rc.stdout)
return json.loads(rc.stdout)

# Identify if there are any binaries to install for the current package
@staticmethod
def _has_binaries(metadata):
for package in metadata.get('packages', {}):
for target in package.get('targets', {}):
for crate_type in target.get('crate_types', {}):
Expand Down

0 comments on commit c56a200

Please sign in to comment.