tox-dev / platformdirs

A small Python module for determining appropriate platform-specific dirs, e.g. a "user data dir".
https://platformdirs.readthedocs.io
MIT License
593 stars 51 forks source link

Fix android detection when python4android is present #277

Closed tmolitor-stud-tu closed 6 months ago

tmolitor-stud-tu commented 6 months ago

When using platformdirs in an android app located on adopted storage, _android_folder() in android.py returned None which lead platformdirs to believe that it doesn't run on android and use the Unix flavor instead.

In android.py#L126 autoclass("android.content.Context") returns a class instead of an instance, which throws an exception on the next line trying to access an instance method named getFilesDir().

That exception is catched and a fallback implementation invoked, that uses a regular expression to search in sys.path for an import path rooted in /data. Apps installed on adopted storage don't have such paths but begin with /mnt/expand/ instead. The regular expression therefore fails and _android_folder() returns None.

This pull request fixes the issue at least for cases where python4android is available, by first trying to import the android module and using it's mActivity export to get hold of the main activity. That activity is then used to get a proper application context upon which getFilesDir() can be invoked.

If that fails with an exception the original codepath is taken, trying the autoclassapproach next and if that fails resorting to the regular expression.

tmolitor-stud-tu commented 6 months ago

done

tmolitor-stud-tu commented 6 months ago

I've added a test with a mocked android import (test_android_folder_from_p4a) and I also added an adopted storage path to test_android_folder_from_sys_path and adapted the implementation to do a regex fallback for adopted storage, too.