-
Notifications
You must be signed in to change notification settings - Fork 790
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Generate source for .resx files on build. #3607
Changes from 7 commits
01c4674
67295f7
0727149
1ce305b
e26198f
9105693
289dd15
c1ab08a
decdcb0
71c0931
1245d59
7209630
4f321fd
c89546f
7594f7f
18ea1fa
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. | ||
|
||
namespace Microsoft.FSharp.Build | ||
|
||
open System | ||
open System.Collections | ||
open System.Globalization | ||
open System.IO | ||
open System.Linq | ||
open System.Text | ||
open System.Xml.Linq | ||
open Microsoft.Build.Framework | ||
open Microsoft.Build.Utilities | ||
|
||
type FSharpEmbedResXSource() = | ||
let mutable _buildEngine : IBuildEngine = null | ||
let mutable _hostObject : ITaskHost = null | ||
let mutable _embeddedText : ITaskItem[] = [||] | ||
let mutable _generatedSource : ITaskItem[] = [||] | ||
let mutable _outputPath : string = "" | ||
let mutable _targetFramework : string = "" | ||
|
||
let boilerplate = @"// <auto-generated> | ||
|
||
namespace {0} | ||
|
||
open System.Reflection | ||
|
||
module internal {1} = | ||
type private C (_dummy:System.Object) = class end | ||
let mutable Culture = System.Globalization.CultureInfo.CurrentUICulture | ||
let ResourceManager = new System.Resources.ResourceManager(""{2}"", C(null).GetType().GetTypeInfo().Assembly) | ||
let GetString(name:System.String) : System.String = ResourceManager.GetString(name, Culture)" | ||
|
||
let boilerplateGetObject = " let GetObject(name:System.String) : System.Object = ResourceManager.GetObject(name, Culture)" | ||
|
||
let generateSource (resx:string) (fullModuleName:string) (generateLegacy:bool) (generateLiteral:bool) = | ||
try | ||
let printMessage = printfn "FSharpEmbedResXSource: %s" | ||
let justFileName = Path.GetFileNameWithoutExtension(resx) | ||
let namespaceName, moduleName = | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please check https://github.com/Microsoft/visualfsharp/pull/3614/files#diff-f583ab0cc0cd86307b6b05f78682f65a for the hack I put in to make sure this doesn't repeatedly re-generate content, causing unexpected rebuilds on a simple repeated build like Please also manually check that repeated There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. Extra commits coming soon. |
||
let parts = fullModuleName.Split('.') | ||
if parts.Length = 1 then ("global", parts.[0]) | ||
else (String.Join(".", parts, 0, parts.Length - 1), parts.[parts.Length - 1]) | ||
let generateGetObject = | ||
match _targetFramework with | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. netcoreapp1.* as well There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks, updated commits coming. |
||
| "netstandard1.0" | ||
| "netstandard1.1" | ||
| "netstandard1.2" | ||
| "netstandard1.3" | ||
| "netstandard1.4" | ||
| "netstandard1.5" | ||
| "netstandard1.6" -> false // these targets don't support the `ResourceManager.GetObject()` method | ||
| _ -> true // other supported runtimes, do | ||
let sb = StringBuilder().AppendLine(String.Format(boilerplate, namespaceName, moduleName, justFileName)) | ||
if generateGetObject then sb.AppendLine(boilerplateGetObject) |> ignore | ||
let sourcePath = Path.Combine(_outputPath, justFileName + ".fs") | ||
printMessage <| sprintf "Generating: %s" sourcePath | ||
let body = | ||
let xname = XName.op_Implicit | ||
XDocument.Load(resx).Descendants(xname "data") | ||
|> Seq.fold (fun (sb:StringBuilder) (node:XElement) -> | ||
let name = | ||
match node.Attribute(xname "name") with | ||
| null -> failwith "Missing resource name" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we provide a more helpful message here? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. Updated commits coming soon. |
||
| attr -> attr.Value | ||
let docComment = | ||
match node.Elements(xname "value").FirstOrDefault() with | ||
| null -> failwith <| sprintf "Missing resource value for '%s'" name | ||
| element -> element.Value.Trim() | ||
let identifier = if Char.IsLetter(name.[0]) || name.[0] = '_' then name else "_" + name | ||
let commentBody = | ||
XElement(xname "summary", docComment).ToString().Split([|"\r\n"; "\r"; "\n"|], StringSplitOptions.None) | ||
|> Array.fold (fun (sb:StringBuilder) line -> sb.AppendLine(" /// " + line)) (StringBuilder()) | ||
// add the resource | ||
let accessorBody = | ||
match (generateLegacy, generateLiteral) with | ||
| (true, true) -> sprintf " [<Literal>]\n let %s = \"%s\"" identifier name | ||
| (true, false) -> sprintf " let %s = \"%s\"" identifier name // the [<Literal>] attribute can't be used for FSharp.Core | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we not automatically detect if we're generating for FSharp.Core? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not directly. This generator only has access to whatever is in the project file, and while we could detect |
||
| (false, _) -> | ||
let isStringResource = match node.Attribute(xname "type") with | ||
| null -> true | ||
| _ -> false | ||
match (isStringResource, generateGetObject) with | ||
| (true, _) -> sprintf " let %s() = GetString(\"%s\")" identifier name | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just a thought, but could we replace let MyString (parameter1 : string) = String.Format(GetString("MyString"), parameter1) It means string formatting identifiers in the resx will fail the build if they aren't expanded. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Regarding the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Some of the SR modules that you removed did this already - although am I right in saying that this code is for all FSharp projects, not just VFT projects? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As for detecting |
||
| (false, true) -> sprintf " let %s() = GetObject(\"%s\")" identifier name | ||
| (false, false) -> "" // the target runtime doesn't support non-string resources | ||
// TODO: When calling the `GetObject` version, parse the `type` attribute to discover the proper return type | ||
sb.AppendLine().Append(commentBody).AppendLine(accessorBody) | ||
) sb | ||
File.WriteAllText(sourcePath, body.ToString()) | ||
printMessage <| sprintf "Done: %s" sourcePath | ||
Some(sourcePath) | ||
with e -> | ||
printf "An exception occurred when processing '%s'\n%s" resx (e.ToString()) | ||
None | ||
|
||
[<Required>] | ||
member this.EmbeddedResource | ||
with get() = _embeddedText | ||
and set(value) = _embeddedText <- value | ||
|
||
[<Required>] | ||
member this.IntermediateOutputPath | ||
with get() = _outputPath | ||
and set(value) = _outputPath <- value | ||
|
||
member this.TargetFramework | ||
with get() = _targetFramework | ||
and set(value) = _targetFramework <- value | ||
|
||
[<Output>] | ||
member this.GeneratedSource | ||
with get() = _generatedSource | ||
|
||
interface ITask with | ||
member this.BuildEngine | ||
with get() = _buildEngine | ||
and set(value) = _buildEngine <- value | ||
member this.HostObject | ||
with get() = _hostObject | ||
and set(value) = _hostObject <- value | ||
member this.Execute() = | ||
let getBooleanMetadata (metadataName:string) (defaultValue:bool) (item:ITaskItem) = | ||
match item.GetMetadata(metadataName) with | ||
| value when String.IsNullOrWhiteSpace(value) -> defaultValue | ||
| value -> String.Compare(value, "true", StringComparison.OrdinalIgnoreCase) = 0 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Throw if the result isn't false? e.g. someone could write There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good idea. Updated commits coming soon. |
||
let generatedFiles, generatedResult = | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please check the latest code in https://github.com/Microsoft/visualfsharp/pull/3614/files#diff-f583ab0cc0cd86307b6b05f78682f65a for a cleaner way to write this. A general rule is not to use There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. Extra commits coming soon. |
||
this.EmbeddedResource | ||
|> Array.filter (getBooleanMetadata "GenerateSource" false) | ||
|> Array.fold (fun (resultList, aggregateResult) item -> | ||
let moduleName = | ||
match item.GetMetadata("GeneratedModuleName") with | ||
| null -> Path.GetFileNameWithoutExtension(item.ItemSpec) | ||
| value -> value | ||
let generateLegacy = getBooleanMetadata "GenerateLegacyCode" false item | ||
let generateLiteral = getBooleanMetadata "GenerateLiterals" true item | ||
match generateSource item.ItemSpec moduleName generateLegacy generateLiteral with | ||
| Some (source) -> ((source :: resultList), aggregateResult) | ||
| None -> (resultList, false) | ||
) ([], true) | ||
let generatedSources = generatedFiles |> List.map (fun item -> TaskItem(item) :> ITaskItem) | ||
_generatedSource <- generatedSources |> List.rev |> List.toArray | ||
generatedResult |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can't this be replaced with
Assembly.GetCallingAssembly
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's the current executing assembly that is interesting not the calling assembly. This irritating code is the magic formulation because GetExecutingAssembly() didn\t make it into coreclr until V2.0, and the buildtask is compiled for both the desktop and coreclr.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In which case can we make the
C
class simpler:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@saul sure.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can't use
typeof<>
because this generator is used byFSharp.Core
and at the point that we need these strings is before thetypeof<>
operator can be defined (i.e., inprim-types.fs/fsi
). I could do a custom switch onFSharp.Core
, but that seemed like a nasty hack given that the hack already there will always work.Edit: and the
.GetType().GetTypeInfo()
method works in both desktop and CoreCLR scenarios and I'd rather have one method that always works than switching on platform for something that doesn't matter to the end user.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@brettfo thanks for clearing that up, I couldn't for the life of me remember why we did it this way.