hey-red / Mime

.NET wrapper for libmagic
MIT License
84 stars 22 forks source link

Copy native libs to correct build output directory for Azure Functions #51

Open ntsim opened 1 year ago

ntsim commented 1 year ago

This issue is basically a continuation of issue #36.

Currently, when running Mime in an Azure Function project app, it appears that the function build targets strip out any unnecessary native libs such as libmagic-1.so and magic.mgc.

For context, Azure Functions are run via func start (see azure-functions-core-tools repository). The build target for this creates a second build directory with unnecessary dependencies and native libs stripped out.

This results in the following output directories:

This curiously results in a bin directory within the bin directory. This bin/output/bin directory is what is deployed to the function runtime.

Unfortunately, it doesn't seem like we can easily configure what files are included in the function build output directory and this is causing most of Mime's native libs to be removed.

If we look in the bin/output/bin/runtimes directory, we end up with something like this:

runtimes/
  linux-msl-64/ <-- No Mime native libs
  linux-x64/    <-- No Mime native libs
  osx-arm64/    <-- No Mime native libs
  osx-x64/
  win-x64/
    native/     <-- Has native Mime libs, but missing magic.mgc
      libgnurx-0.dll
      libmagic-1.dll

As the native libs aren't included, this causes Mime to throw errors around not being able to find libmagic-1 or magic.mgc.

Ideal solution

Ideally, it would be nice if Mime had a built-in way to ensure that its native libs are included in build output for Azure Functions. I'm really just a MSBuild novice so I don't really know what to suggest though.

Workaround

One workaround I've currently settled on is to include the following in my csproj:

<!-- Copy files that function build strips out that should normally be included  -->
<Target Name="CopyFilesAfterBuild" AfterTargets="_GenerateFunctionsPostBuild">
  <ItemGroup>
    <NativeLibs Include="$(OutDir)runtimes\**\libmagic-1.so" />
    <NativeLibs Include="$(OutDir)runtimes\**\libmagic-1.dylib" />
    <NativeLibs Include="$(OutDir)runtimes\**\libmagic-1.dll" />
    <NativeLibs Include="$(OutDir)runtimes\**\libgnurx-0.dll" />
  </ItemGroup>
  <Copy SourceFiles="@(NativeLibs)" DestinationFolder="$(OutDir)bin\runtimes\%(RecursiveDir)" />
  <!-- Doesn't matter which runtime the magic.mgc file comes from, they're all the same -->
  <Copy SourceFiles="$(OutDir)runtimes\win-x64\native\magic.mgc" DestinationFolder="$(OutDir)bin" />
</Target>