-
Notifications
You must be signed in to change notification settings - Fork 805
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
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
01c4674
add build task to generate *.fs from *.resx files
brettfo 67295f7
generate source for embedded resources in tests
brettfo 0727149
generate source for embedded resources in FSharp.Editor
brettfo 1ce305b
generate source for embedded resources in FSharp.LanguageService
brettfo e26198f
generate source for embedded resources in FSharp.ProjectSystem.FSharp
brettfo 9105693
generate source for embedded resources in FSharp.VS.FSI
brettfo 289dd15
don't generate non-string resources when <=netstandard1.6
brettfo c1ab08a
update baseline error message for tests
brettfo decdcb0
perform up-to-date check before generating *.fs from *.resx
brettfo 71c0931
remove non-idiomatic fold for an array comprehension
brettfo 1245d59
correct newline replacement
brettfo 7209630
output more friendly error message
brettfo 4f321fd
throw if boolean value isn't explicitly `true` or `false`
brettfo c89546f
only generate object resource code on non `netstandard1.*` and `netco…
brettfo 7594f7f
ensure FSharp.Core specifies a target framework for resource generaton
brettfo 18ea1fa
rename attributes to be non-ambiguous and properly include them
brettfo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
// 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 sourcePath = Path.Combine(_outputPath, justFileName + ".fs") | ||
|
||
// simple up-to-date check | ||
if File.Exists(resx) && File.Exists(sourcePath) && | ||
File.GetLastWriteTime(resx) <= File.GetLastWriteTime(sourcePath) then | ||
printMessage (sprintf "Skipping generation: '%s' since it is up-to-date." sourcePath) | ||
Some(sourcePath) | ||
else | ||
let namespaceName, moduleName = | ||
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 = not (_targetFramework.StartsWith("netstandard1.") || _targetFramework.StartsWith("netcoreapp1.")) | ||
printMessage (sprintf "Generating code for target framework %s" _targetFramework) | ||
let sb = StringBuilder().AppendLine(String.Format(boilerplate, namespaceName, moduleName, justFileName)) | ||
if generateGetObject then sb.AppendLine(boilerplateGetObject) |> ignore | ||
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 (sprintf "Missing resource name on element '%s'" (node.ToString())) | ||
| 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 | ||
| (false, _) -> | ||
let isStringResource = match node.Attribute(xname "type") with | ||
| null -> true | ||
| _ -> false | ||
match (isStringResource, generateGetObject) with | ||
| (true, _) -> sprintf " let %s() = GetString(\"%s\")" identifier name | ||
| (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 -> | ||
match value.ToLowerInvariant() with | ||
| "true" -> true | ||
| "false" -> false | ||
| _ -> failwith (sprintf "Expected boolean value for '%s' found '%s'" metadataName value) | ||
let mutable success = true | ||
let generatedSource = | ||
[| for item in this.EmbeddedResource do | ||
if getBooleanMetadata "GenerateSource" false item then | ||
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) -> yield TaskItem(source) :> ITaskItem | ||
| None -> success <- false | ||
|] | ||
_generatedSource <- generatedSource | ||
success |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.