@@ -319,7 +319,8 @@ function create_sysimg_object_file(object_file::String,
319319 script:: Union{Nothing, String} ,
320320 sysimage_build_args:: Cmd ,
321321 extra_precompiles:: String ,
322- incremental:: Bool )
322+ incremental:: Bool ,
323+ import_into_main:: Bool )
323324 julia_code_buffer = IOBuffer ()
324325 # include all packages into the sysimg
325326 print (julia_code_buffer, """
@@ -419,10 +420,21 @@ function create_sysimg_object_file(object_file::String,
419420 """
420421
421422 # Make packages available in Main. It is unclear if this is the right thing to do.
422- for pkg in packages
423- print (julia_code_buffer, """
424- import $pkg
423+ if import_into_main
424+ for pkg in packages
425+ print (julia_code_buffer, """
426+ if isdefined(Main, Symbol("$pkg "))
427+ @warn(
428+ "Skipping the import of $pkg into Main. A package with this name has " *
429+ "already been imported. You can disable importing packages into Main " *
430+ "by setting the `import_into_main` flag to `false`. " *
431+ "Ref: https://github.com/JuliaLang/PackageCompiler.jl/issues/768"
432+ )
433+ else
434+ import $pkg
435+ end
425436 """ )
437+ end
426438 end
427439
428440 print (julia_code_buffer, precompile_code)
@@ -504,6 +516,9 @@ compiler (can also include extra arguments to the compiler, like `-g`).
504516 transitive dependencies into the sysimage. This only makes a difference if some
505517 packages do not load all their dependencies when themselves are loaded. Defaults to `true`.
506518
519+ - `import_into_main::Bool`: If `true`, import all packages from `packages` into `Main`.
520+ This allows calling `using .Package` without the Project.toml the sysimage was built with.
521+
507522### Advanced keyword arguments
508523
509524- `base_sysimage::Union{Nothing, String}`: If a `String`, names an existing sysimage upon which to build
@@ -537,6 +552,7 @@ function create_sysimage(packages::Union{Nothing, Symbol, Vector{String}, Vector
537552 soname= nothing ,
538553 compat_level:: String = " major" ,
539554 extra_precompiles:: String = " " ,
555+ import_into_main:: Bool = true ,
540556 )
541557 # We call this at the very beginning to make sure that the user has a compiler available. Therefore, if no compiler
542558 # is found, we throw an error immediately, instead of making the user wait a while before the error is thrown.
@@ -634,7 +650,8 @@ function create_sysimage(packages::Union{Nothing, Symbol, Vector{String}, Vector
634650 script,
635651 sysimage_build_args,
636652 extra_precompiles,
637- incremental)
653+ incremental,
654+ import_into_main)
638655 object_files = [object_file]
639656 if julia_init_c_file != = nothing
640657 if julia_init_c_file isa String
0 commit comments