Skip to content

snap: report missing snaps instead of raising IndexError - #12570

Merged
felixfontein merged 4 commits into
ansible-collections:mainfrom
Developer1010x:fix/12375-snap-no-snap-found
Aug 18, 2026
Merged

felixfontein merged 4 commits into
ansible-collections:mainfrom
Developer1010x:fix/12375-snap-no-snap-found

Conversation

@Developer1010x

Copy link
Copy Markdown
Contributor
SUMMARY

Fixes #12375.

snap info reports a missing snap two different ways:

snaps queried message stream rc
several warning: no snap found for "..." stdout 0
one error: no snap found for "..." stderr 1

names_from_snaps only matched the warning form, so the single-snap case fell through to process_one, where the output contains no name: line and res[0] raised IndexError instead of reporting the missing snap. That is the traceback in the issue, and the run info there confirms it:

"results_err": "error: no snap found for \"hello-world\"\n",
"results_out": "",
"results_rc": 1

The same block also scanned stdout for the snap names while the single-snap message is on stderr, so even a matching prefix would have produced an empty list. It now scans check_error, which is already the correct stream in both branches.

Three changes:

  1. Match both warning: no snap found and error: no snap found, and read them from check_error.
  2. Strip the surrounding quotes, so the failure reads Snaps not found: ['hello-world']. rather than ['"hello-world"'].
  3. Raise a clear error from process_one when there is no name: line, so a future change in snap info output fails with a message rather than an IndexError.
ISSUE TYPE
  • Bugfix Pull Request
COMPONENT NAME

snap

ADDITIONAL INFORMATION

Added a unit case mocking exactly the output from the report: rc 1, empty stdout, error: no snap found for "hello-world" on stderr.

Against the current code it reproduces the reported failure:

AssertionError: 'msg': 'Module failed with exception: list index out of range'
                    != 'Snaps not found: ['hello-world'].'

With this change the full test_snap.py suite passes (5 passed).

Happy to change the wording of the failure message if you would prefer something else.

snap info reports a missing snap two different ways. When several snaps are
queried it emits "warning: no snap found" on stdout and exits 0; when a single
snap is queried it emits "error: no snap found" on stderr and exits 1.

names_from_snaps only matched the warning form, so the single-snap case fell
through to process_one, where snap info output contains no "name:" line and
res[0] raised IndexError instead of reporting the missing snap.

The same block also scanned stdout for the snap names while the single-snap
message is on stderr, so even a matching prefix would have produced an empty
list. It now scans check_error, which is already the correct stream for both
cases, and strips the surrounding quotes so the failure reads

    Snaps not found: ['hello-world'].

process_one also raises a clear error when there is no "name:" line, so a
future change in snap info output fails with a message rather than an
IndexError.

Adds a unit case mocking the exact output from the report: rc 1, empty stdout,
and 'error: no snap found for "hello-world"' on stderr. Against the previous
code it reproduces the reported failure; with this change the full snap suite
passes.

Signed-off-by: S Prajwall Narayana <[email protected]>
@ansibullbot

Copy link
Copy Markdown
Collaborator

Session ansible-lint failed.

Please see the CI output for details.

click here for bot help

@ansibullbot

Copy link
Copy Markdown
Collaborator

@ansibullbot ansibullbot added bug This issue/PR relates to a bug module module needs_revision This PR fails CI tests or a maintainer has requested a review/revision of the PR new_contributor Help guide this first time contributor plugins plugin (any type) tests tests unit tests/unit labels Aug 15, 2026
The collection's fragments link both the issue and the pull request; this
one only had the issue because the PR did not exist when it was written.

Signed-off-by: S Prajwall Narayana <[email protected]>
@ansibullbot ansibullbot removed the needs_revision This PR fails CI tests or a maintainer has requested a review/revision of the PR label Aug 15, 2026
@felixfontein felixfontein added check-before-release PR will be looked at again shortly before release and merged if possible. backport-12 Automatically create a backport for the stable-12 branch backport-13 Automatically create a backport for the stable-13 branch labels Aug 15, 2026

@felixfontein felixfontein left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your contribution!

Comment thread tests/unit/plugins/modules/test_snap.py Outdated
]
)

TEST_SPEC["test_cases"].append(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not add this directly to the above list?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not only that, but please also add a corresponding test case with multiple snaps.

@russoz russoz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @Developer1010x

Thanks for your contribution! Got a couple of comments.

@@ -0,0 +1,2 @@
bugfixes:
- "snap - fix ``IndexError`` when a snap does not exist. ``snap info`` reports a missing snap as ``error: no snap found`` on stderr when a single snap is queried, but the module only matched the ``warning: no snap found`` emitted on stdout when several are, so the single-snap case fell through and crashed instead of reporting the missing snap (https://github.com/ansible-collections/community.general/issues/12375, https://github.com/ansible-collections/community.general/pull/12570)."

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest making it a little bit more terse - the explanation of what happened to trigger the problem is not exactly a log of the change ;-)

Comment thread plugins/modules/snap.py Outdated
Comment on lines +400 to +403
# is, so both prefixes and both streams have to be handled. Matching
# only the warning let the single-snap case fall through to
# process_one, which then raised IndexError because there is no
# "name:" line to read.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

over-explained - could you please make it more concise?

Comment thread plugins/modules/snap.py Outdated
# "name:" line to read.
snaps_not_found = [
x.split()[-1].strip('"')
for x in check_error.split("\n")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, the error was that the code was line splitting out when it should have been check_err. I believe that was me, a while back.

Comment thread plugins/modules/snap.py Outdated
snaps_not_found = [
x.split()[-1].strip('"')
for x in check_error.split("\n")
if x.startswith(("warning: no snap found", "error: no snap found"))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would consider using a regexp with the expression r'^(warning|error): no snap found'. We are already using re` in this module, and there is a nifty block of pre-defined regexps by the beggining of the code.

Comment thread plugins/modules/snap.py Outdated
Comment on lines +375 to +376
if not res:
self.do_raise(msg=f"Unable to determine snap name from 'snap info' output:\n{out}")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This happens when the snap name is not recognized by snapd (regardless of installation status). I tried locally:

$ snap info bogus-hello-world
error: no snap found for "bogus-hello-world"

If we run the module with only one snap name, and an invalid one (like the above), then the res list will come out empty in L374, and the exception will be raised in L376.

However, this function is only called in L411 below, after the validation in L404-409, which will raise an exception in case of error. Therefore, this change here is redundant, please remove it.

Comment thread tests/unit/plugins/modules/test_snap.py Outdated
]
)

TEST_SPEC["test_cases"].append(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not only that, but please also add a corresponding test case with multiple snaps.

Comment thread tests/unit/plugins/modules/test_snap.py Outdated
# snapd emits "error: no snap found" on stderr with rc=1 when a single
# snap is queried, not the "warning:" on stdout it uses for several.
id="issue_12375_single_snap_not_found",
input={"name": ["hello-world"]},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To prevent confusion for unwary, please use an obviously wrong name for this test, like bogus-world or this-snap-does-not-exist or something like that. Using the name of a valid, real, existing one to test the non-existing case might cause trouble to people learning their way into this.

… the tests

- Remove the process_one guard: names_from_snaps only calls it after the
  no-snap-found check above, which already raises, so it was unreachable.
- Match the missing-snap lines with a precompiled regexp alongside the other
  module-level patterns, instead of a startswith tuple.
- Cut the inline comment and the changelog fragment down to the change itself.
- Move both test cases into the TEST_SPEC list rather than appending after it,
  use an obviously invalid snap name, and add the multiple-snap case.

Note: the regexp captures the name, so the multi-snap failure message now reads
['a', 'b'] rather than ['"a"', '"b"'] — the quotes snapd emits are no longer
carried into the message. The new multi-snap test pins that.
@Developer1010x

Copy link
Copy Markdown
Contributor Author

Thanks both — all seven comments addressed in 4ba4e94.

@russoz one thing worth flagging explicitly, because it is a user-visible change rather than a pure refactor. Moving to a named capture group means the multi-snap failure message now reads:

Snaps not found: ['a', 'b'].

where the previous x.split()[-1] carried snapd's quotes through:

Snaps not found: ['"a"', '"b"'].

The single-snap path is new, so it has no prior behaviour to preserve — but that one does, and I did not want to change it silently. I went with the unquoted form so both paths report the same way, and added issue_12375_multiple_snaps_not_found to pin it.

Happy to strip only the leading prefix and keep the quotes if you would rather leave the existing message untouched.

On the redundant guard — you were right, it was unreachable: names_from_snaps only calls process_one after the check above has already raised. Removed.

@russoz russoz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two minor nits and I think we're good.

Comment thread plugins/modules/snap.py Outdated
__disable_re = re.compile(r"(?:\S+\s+){5}(?P<notes>\S+)")
__set_param_re = re.compile(r"(?P<snap_prefix>\S+:)?(?P<key>\S+)\s*=\s*(?P<value>.+)")
__list_re = re.compile(r"^(?P<name>\S+)\s+\S+\s+(?P<rev>\S+)\s+(?P<channel>\S+)\s+\S+\s+(?P<notes>\S+)")
__no_snap_re = re.compile(r"^(?:warning|error): no snap found for \"(?P<name>[^\"]+)\"")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would recommend avoiding the escaped quotes within the string. To differentiate the string quoting, I am suggesting the triple ''', but feel free to use something else.

Suggested change
__no_snap_re = re.compile(r"^(?:warning|error): no snap found for \"(?P<name>[^\"]+)\"")
__no_snap_re = re.compile(r'''^(?:warning|error): no snap found for "(?P<name>[^\"]+)"''')

Comment thread tests/unit/plugins/modules/test_snap.py Outdated
),
),
dict(
# https://github.com/ansible-collections/community.general/issues/12375

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is redundant. When the PR is merged, all commits are squashed ibto one and its commit hash gets associated with the line in git blame. If memory serves the PR is easily spotted as well.

Moreover, you already got the PR number in the test case name.

@ansibullbot ansibullbot added the needs_ci This PR requires CI testing to be performed. Please close and re-open this PR to trigger CI label Aug 17, 2026
@Developer1010x

Copy link
Copy Markdown
Contributor Author

Both done, thanks.

On the first one I also dropped the backslash inside the character class — [^"] rather than [^\"]. Once the string is triple-quoted the escape isn't doing anything, and leaving it in seemed to defeat the point of the change. Behaviour is identical either way.

On the second: agreed, removed both. The PR number is already in the test case ids.

…ssue links

russoz's review on ansible-collections#12570:
- __no_snap_re: use a triple-quoted raw string so the embedded double quotes
  need no backslash escaping. The backslash inside the character class goes
  too, since it was only there to survive the old quoting.
- tests: drop the issue URL comments. The PR number is already in each test
  case id, and git blame ties the lines to the squashed merge commit.
@Developer1010x
Developer1010x force-pushed the fix/12375-snap-no-snap-found branch from 9986158 to 6b3b27f Compare August 17, 2026 04:17
@ansibullbot ansibullbot removed the needs_ci This PR requires CI testing to be performed. Please close and re-open this PR to trigger CI label Aug 17, 2026

@russoz russoz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@felixfontein
felixfontein merged commit 8287b00 into ansible-collections:main Aug 18, 2026
117 checks passed
@felixfontein felixfontein removed the check-before-release PR will be looked at again shortly before release and merged if possible. label Aug 18, 2026
@patchback

patchback Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Backport to stable-13: 💚 backport PR created

✅ Backport PR branch: patchback/backports/stable-13/8287b00a3140e75fa16d1ab0f7eae55c984c2202/pr-12570

Backported as #12582

🤖 @patchback
I'm built with octomachinery and
my source is open — https://github.com/sanitizers/patchback-github-app.

@felixfontein

Copy link
Copy Markdown
Collaborator

@Developer1010x thanks for fixing this!
@russoz thanks for reviewing!

@patchback

patchback Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Backport to stable-12: 💔 cherry-picking failed — conflicts found

❌ Failed to cleanly apply 8287b00 on top of patchback/backports/stable-12/8287b00a3140e75fa16d1ab0f7eae55c984c2202/pr-12570

Backporting merged PR #12570 into main

  1. Ensure you have a local repo clone of your fork. Unless you cloned it
    from the upstream, this would be your origin remote.
  2. Make sure you have an upstream repo added as a remote too. In these
    instructions you'll refer to it by the name upstream. If you don't
    have it, here's how you can add it:
    $ git remote add upstream https://github.com/ansible-collections/community.general.git
  3. Ensure you have the latest copy of upstream and prepare a branch
    that will hold the backported code:
    $ git fetch upstream
    $ git checkout -b patchback/backports/stable-12/8287b00a3140e75fa16d1ab0f7eae55c984c2202/pr-12570 upstream/stable-12
  4. Now, cherry-pick PR snap: report missing snaps instead of raising IndexError #12570 contents into that branch:
    $ git cherry-pick -x 8287b00a3140e75fa16d1ab0f7eae55c984c2202
    If it'll yell at you with something like fatal: Commit 8287b00a3140e75fa16d1ab0f7eae55c984c2202 is a merge but no -m option was given., add -m 1 as follows instead:
    $ git cherry-pick -m1 -x 8287b00a3140e75fa16d1ab0f7eae55c984c2202
  5. At this point, you'll probably encounter some merge conflicts. You must
    resolve them in to preserve the patch from PR snap: report missing snaps instead of raising IndexError #12570 as close to the
    original as possible.
  6. Push this branch to your fork on GitHub:
    $ git push origin patchback/backports/stable-12/8287b00a3140e75fa16d1ab0f7eae55c984c2202/pr-12570
  7. Create a PR, ensure that the CI is green. If it's not — update it so that
    the tests and any other checks pass. This is it!
    Now relax and wait for the maintainers to process your pull request
    when they have some cycles to do reviews. Don't worry — they'll tell you if
    any improvements are necessary when the time comes!

🤖 @patchback
I'm built with octomachinery and
my source is open — https://github.com/sanitizers/patchback-github-app.

felixfontein pushed a commit that referenced this pull request Aug 18, 2026
…nstead of raising IndexError (#12582)

snap: report missing snaps instead of raising IndexError (#12570)

* snap: report missing snaps instead of raising IndexError

snap info reports a missing snap two different ways. When several snaps are
queried it emits "warning: no snap found" on stdout and exits 0; when a single
snap is queried it emits "error: no snap found" on stderr and exits 1.

names_from_snaps only matched the warning form, so the single-snap case fell
through to process_one, where snap info output contains no "name:" line and
res[0] raised IndexError instead of reporting the missing snap.

The same block also scanned stdout for the snap names while the single-snap
message is on stderr, so even a matching prefix would have produced an empty
list. It now scans check_error, which is already the correct stream for both
cases, and strips the surrounding quotes so the failure reads

    Snaps not found: ['hello-world'].

process_one also raises a clear error when there is no "name:" line, so a
future change in snap info output fails with a message rather than an
IndexError.

Adds a unit case mocking the exact output from the report: rc 1, empty stdout,
and 'error: no snap found for "hello-world"' on stderr. Against the previous
code it reproduces the reported failure; with this change the full snap suite
passes.



* snap: cite the PR alongside the issue in the changelog fragment

The collection's fragments link both the issue and the pull request; this
one only had the issue because the PR did not exist when it was written.



* snap: address review — use a regexp, drop the redundant guard, extend the tests

- Remove the process_one guard: names_from_snaps only calls it after the
  no-snap-found check above, which already raises, so it was unreachable.
- Match the missing-snap lines with a precompiled regexp alongside the other
  module-level patterns, instead of a startswith tuple.
- Cut the inline comment and the changelog fragment down to the change itself.
- Move both test cases into the TEST_SPEC list rather than appending after it,
  use an obviously invalid snap name, and add the multiple-snap case.

Note: the regexp captures the name, so the multi-snap failure message now reads
['a', 'b'] rather than ['"a"', '"b"'] — the quotes snapd emits are no longer
carried into the message. The new multi-snap test pins that.

* snap: address review nits — triple-quote the regexp, drop redundant issue links

russoz's review on #12570:
- __no_snap_re: use a triple-quoted raw string so the embedded double quotes
  need no backslash escaping. The backslash inside the character class goes
  too, since it was only there to survive the old quoting.
- tests: drop the issue URL comments. The PR number is already in each test
  case id, and git blame ties the lines to the squashed merge commit.

---------


(cherry picked from commit 8287b00)

Signed-off-by: S Prajwall Narayana <[email protected]>
Co-authored-by: S Prajwall Narayana <[email protected]>
russoz pushed a commit to russoz-ansible/community.general that referenced this pull request Sep 27, 2026
…lections#12570)

* snap: report missing snaps instead of raising IndexError

snap info reports a missing snap two different ways. When several snaps are
queried it emits "warning: no snap found" on stdout and exits 0; when a single
snap is queried it emits "error: no snap found" on stderr and exits 1.

names_from_snaps only matched the warning form, so the single-snap case fell
through to process_one, where snap info output contains no "name:" line and
res[0] raised IndexError instead of reporting the missing snap.

The same block also scanned stdout for the snap names while the single-snap
message is on stderr, so even a matching prefix would have produced an empty
list. It now scans check_error, which is already the correct stream for both
cases, and strips the surrounding quotes so the failure reads

    Snaps not found: ['hello-world'].

process_one also raises a clear error when there is no "name:" line, so a
future change in snap info output fails with a message rather than an
IndexError.

Adds a unit case mocking the exact output from the report: rc 1, empty stdout,
and 'error: no snap found for "hello-world"' on stderr. Against the previous
code it reproduces the reported failure; with this change the full snap suite
passes.

Signed-off-by: S Prajwall Narayana <[email protected]>

* snap: cite the PR alongside the issue in the changelog fragment

The collection's fragments link both the issue and the pull request; this
one only had the issue because the PR did not exist when it was written.

Signed-off-by: S Prajwall Narayana <[email protected]>

* snap: address review — use a regexp, drop the redundant guard, extend the tests

- Remove the process_one guard: names_from_snaps only calls it after the
  no-snap-found check above, which already raises, so it was unreachable.
- Match the missing-snap lines with a precompiled regexp alongside the other
  module-level patterns, instead of a startswith tuple.
- Cut the inline comment and the changelog fragment down to the change itself.
- Move both test cases into the TEST_SPEC list rather than appending after it,
  use an obviously invalid snap name, and add the multiple-snap case.

Note: the regexp captures the name, so the multi-snap failure message now reads
['a', 'b'] rather than ['"a"', '"b"'] — the quotes snapd emits are no longer
carried into the message. The new multi-snap test pins that.

* snap: address review nits — triple-quote the regexp, drop redundant issue links

russoz's review on ansible-collections#12570:
- __no_snap_re: use a triple-quoted raw string so the embedded double quotes
  need no backslash escaping. The backslash inside the character class goes
  too, since it was only there to survive the old quoting.
- tests: drop the issue URL comments. The PR number is already in each test
  case id, and git blame ties the lines to the squashed merge commit.

---------

Signed-off-by: S Prajwall Narayana <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-12 Automatically create a backport for the stable-12 branch backport-13 Automatically create a backport for the stable-13 branch bug This issue/PR relates to a bug module module new_contributor Help guide this first time contributor plugins plugin (any type) tests tests unit tests/unit

Projects

None yet

Development

Successfully merging this pull request may close these issues.

snap: module fails with list index out of range exception if cannot find snap

4 participants