Scripty icon indicating copy to clipboard operation
Scripty copied to clipboard

Consider automatically loading references from target project

Open daveaglick opened this issue 9 years ago • 2 comments

Consider loading the references that the host project uses and making them available in the script. Maybe there should be a preprocessor directive to opt-in to this behavior.

daveaglick avatar Nov 24 '16 13:11 daveaglick

... or making an event handler available for AppDomain.Current.AssemblyResolve in case the assembly isnt nearby.

StingyJack avatar Jan 23 '17 12:01 StingyJack

This would load the current references and namespaces. If it needs to be configurable it could use a new entry on Tools --> Options -->Scripty Options for global. Using the file properties where the custom tool is specified would be another config point.

I didnt find a clear distinction between the pairs of .Add()* or .With*() methods on script options, but these work (and i didnt really look that hard).

           var scriptFullPath = Path.GetFullPath(scriptName);
            var scriptCode = File.ReadAllText(scriptFullPath);
            var scriptOptions = ScriptOptions.Default
                .WithFilePath(scriptFullPath);
            var currentRefs = AppDomain.CurrentDomain.GetAssemblies();
            foreach (var asmRef in currentRefs)
            {
                scriptOptions.WithReferences(asmRef);
                if (asmRef.FullName.Contains("mscorlib"))
                {
                    continue;
                }
                try
                {
                    var namepsaces = asmRef.GetTypes()
                    .Where(t => string.IsNullOrWhiteSpace(t.Namespace) == false)
                    .Select(t => t.Namespace);

                    scriptOptions.AddImports(namepsaces.Distinct());
                }
                catch (ReflectionTypeLoadException reflx)
                {
                    Console.WriteLine($"Skipping assembly {asmRef.FullName}. Err: {reflx}");
                }

            }

            var script = CSharpScript.Create(scriptCode, scriptOptions, typeof(T));
            var result = script.RunAsync(globalsInstance).Result;

            return result;
        }

StingyJack avatar Feb 03 '17 12:02 StingyJack