Automatically create i18n directory for VSCode extension - visual-studio-code

I am trying to understand the workflow presented in https://github.com/microsoft/vscode-extension-samples/tree/master/i18n-sample for localizing Visual Studio Code extensions.
I cannot figure out how the i18n directory gets created to begin with, as well as how the set of string keys in that directory get maintained over time.
There is one line in the README.md which says "You could have created this folder by hand, or you could have used the vscode-nls-dev tool to extract it."...how would one use vscode-nls-dev tool to extract it?
What I Understand
I understand that you can use vscode-nls, and wrap strings like this: localize("some.key", "My String") to pick up the localized version of that string at runtime.
I am pretty sure I understand that vscode-nls-dev is used at build time to substitute the content of files in the i18n directory into the transpiled JavaScript code, as well as creating files like out/extension.nls.ja.json
What is missing
Surely it is not expected that: for every file.ts file in your project you create an i18n/lang/out/file.i18n.json for every lang you support...and then keep the set of keys in that file up to date manually with every string change.
I am assuming that there is some process which automatically goes "are there any localize("key", "String") calls in file.ts for new keys not yet in file.i18n.json? If so, add those keys with some untranslated values". What is that process?

I have figured this out, referencing https://github.com/Microsoft/vscode-extension-samples/issues/74
This is built to work if you use Transifex for your translator. At the bare minimum you need to use .xlf files as your translation file format.
I think that this is best illustrated with an example, so lets say you wanted to get the sample project working after you had deleted the i18n folder
Step 1: Clone that project, and delete the i18n directory
Step 2: Modify the gulp file so that the compile function also generates nls metadata files in the out directory. Something like:
function compile(buildNls) {
var r = tsProject.src()
.pipe(sourcemaps.init())
.pipe(tsProject()).js
.pipe(buildNls ? nls.rewriteLocalizeCalls() : es.through())
.pipe(buildNls ? nls.createAdditionalLanguageFiles(languages, 'i18n', 'out') : es.through())
.pipe(buildNls ? nls.bundleMetaDataFiles('ms-vscode.node-debug2', 'out') : es.through())
.pipe(buildNls ? nls.bundleLanguageFiles() : es.through())
Step 3: Run the gulp build command. This will generate several necessary metadata files in the out/ directory
Step 4: Create and run a new gulp function to export the necessarry translations to the xlf file. Something like:
gulp.task('export-i18n', function() {
return gulp.src(['package.nls.json', 'out/nls.metadata.header.json', 'out/nls.metadata.json'])
.pipe(nls.createXlfFiles("vscode-extensions", "node-js-debug2"))
.pipe(gulp.dest(path.join('vscode-translations-export')));
}
Step 5: Get the resulting xlf file translated. Or, add some dummy values. I cant find if/where there is documentation for the file format needed, but this worked for me (for the extension):
<?xml version="1.0" encoding="utf-8"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file original="package" source-language="en" target-language="ja" datatype="plaintext"><body>
<trans-unit id="extension.sayHello.title">
<source xml:lang="en">Hello</source>
<target>JA_Hello</target>
</trans-unit>
<trans-unit id="extension.sayBye.title">
<source xml:lang="en">Bye</source>
<target>JA_Bye</target>
</trans-unit>
</body></file>
<file original="out/extension" source-language="en" target-language="ja" datatype="plaintext"><body>
<trans-unit id="sayHello.text">
<source xml:lang="en">Hello</source>
<target>JA_Hello</target>
</trans-unit>
</body></file>
<file original="out/command/sayBye" source-language="en" target-language="ja" datatype="plaintext"><body>
<trans-unit id="sayBye.text">
<source xml:lang="en">Bye</source>
<target>JA_Bye</target>
</trans-unit>>
</body></file>
</xliff>
Step 6: Stick that file in some known location, let's say /path/to/translation.xlf. Then add/run another new gulp task to import the translation. Something like:
gulp.task('i18n-import', () => {
return es.merge(languages.map(language => {
console.log(language.folderName)
return gulp.src(["/path/to/translation.xlf"])
.pipe(nls.prepareJsonFiles())
.pipe(gulp.dest(path.join('./i18n', language.folderName)));
}));
});
Step 7: Run the gulp build again.
The i18n/ directory should now be recreated correctly! Running the same build/export/translate/import/build steps will pick up any new changes to the localize() calls in your TypeScript code
Obviously this is not perfect, there are a lot of hardcoded paths and such, but hopefully it helps out anyone else who hits this issue.

Related

Vala Gtk css provider load_from_path

I don't know why load_from_path does not work during sudo ninja install. It returns:
warning: unhandled error `GLib.Error'
css_provider.load_from_path ("com.github.saidbakr.quick-shutdown.css");
I tried to catch the exception, but the same Warning:
Gtk.CssProvider css_provider = new Gtk.CssProvider ();
try {
css_provider.load_from_path ("com.github.saidbakr.quick-shutdown.css");
}
catch (IOError e){
GLib.error("", e.message);
}
I checkedout the meson.build:
...
install_data(
join_paths('data', meson.project_name()+ '.css'),
install_dir: join_paths(get_option('datadir'))
)
The path of the file is added and it is installed to /usr/local/share
I don't know how to solve this issue.
The docs for Gtk.CssProvider.load_from_path() make no mention of searching in /usr/local/share/<app-data-dir> or any other standard directory. It's expecting an absolute path.
The standard way to solve this is to use GResource. If you're using a tutorial or template, it probably has something on GResource that you can use.
If not:
Create a file, quick-shutdown.gresource.xml, with the following:
<?xml version="1.0" encoding="UTF-8"?>
<gresources>
<gresource prefix="/com/github/saidbakr/quick-shutdown">
<file>com.github.saidbakr.quick-shutdown.css</file>
</gresource>
</gresources>
Add this to your meson.build:
gnome = import('gnome')
resources = gnome.compile_resources('com.github.saidbakr.quick-shutdown',
files('quick-shutdown.gresource.xml'),
)
Add resources to the list of sources in your executable() call in meson.build
Use Gtk.CssProvider.load_from_resource() instead: css_provider.load_from_resource ("/com/github/saidbakr/quick-shutdown/com.github.saidbakr.quick-shutdown.css")
Remove the meson code where you install the CSS file. It is now built directly into your executable.
For a real-world example of how to do this, check out the GNOME Clocks source code.
This may sound like a lot of steps, but it's the same steps as adding GtkBuilder UI files (or really any other kind of static file you need in your program). If you need to do that later, all you'll have to do is add <file> entries to the .gresource.xml file.

ERROR in There is a placeholder name mismatch with the translation provided

We use #angular/localize (Version 9.1.12) and have a problem with the placeholders in localized text.
E. g. we have:
$localize`:##form.hint:Some text ${name} in service.`;
or
$localize`:##form.hint:Some text ${name}:name: in service.`;
Because the localize text strings in typescript files aren't extracted we put these into a component template.
E. g.:
<p i18n="##form.hint">Some text {{ name }} in service.</p>
After execution of xi18n we get the messages.xlf (and messages.de.xlf) files which contain the following:
<trans-unit id="form.hint" datatype="html">
<source>Some text <x id="INTERPOLATION" equiv-text="{{ name }}"/> in service.</source>
<target state="new">Some text <x id="INTERPOLATION" equiv-text="{{ name }}"/> in service.</target>
<context-group purpose="location">
<context context-type="sourcefile">src/app/translation/translation.component.html</context>
<context context-type="linenumber">207</context>
</context-group>
</trans-unit>
When we start the application with ng serve we get the following error:
ERROR in There is a placeholder name mismatch with the translation provided for the message "form.hint" ("Some text {$PH} in service.").
The translation contains a placeholder with name INTERPOLATION, which does not exist in the message.
The application does not work. After a restart the error does not occur and the application works. Nothing was changed before the restart.
We can work with a local restart but after each change of the messages.xlf files the error occurs again and we need two ci-builds on our build server to get a working installation on our test machine.
Any ideas what can be the cause of the placeholder mismatch?
For the current angular version (10.1.3) you need to opt in to extraction of translation tokens via ivy:
ng xi18n --ivy
The result will include texts from $localize.

Is it possible to replace a file from one repository to another with android repo tool?

I'm using repo tool to build a Yocto project, the repositories used are A, B, yocto ..., and I need to replace a file from A to B, the structure is something like this:
A/MyFile.sh
B/TheFile.sh
yocto/Some_dirs_and_files
So, I use the copyfile like this:
<?xml version="1.0" encoding="UTF-8"?>
<manifest>
<remote fetch="mygitrepo" name="origin"/>
<default remote="origin"/>
<project name="yocto" revision="myrevision"/>
<project name="meta-openembedded" path="yocto/meta-openembedded" revision="myrevision"/>
<project name="B" path="yocto/B" revision="myrevision"/>
<project name="C" path="yocto/meta-swi-extras" revision="myrevision"/>
<project name="poky" path="yocto/poky" revision="myrevision"/>
<project name="A" path="yocto/custom-builds" revision="myrevision">
<copyfile src="MyFile.sh" dest="yocto/B/TheFile.sh"/>
</project>
</manifest>
The problem is that the copyfile is not replacing the file "TheFile.sh" with "MyFile.sh"
Is there a way to do it without an additional script?
Note: If I change the dest name from
dest="yocto/B/TheFile.sh
to
dest="yocto/B/AnotherFile.sh
the file is succesfully copied, but if I set the name to the file I want to replace it doesn't.
It seems repo do now allow overwrite file by <copyfile src=.. dest ...>
From repo source code project.py
class _CopyFile(object):
def __init__(self, src, dest, abssrc, absdest):
self.src = src
self.dest = dest
self.abs_src = abssrc
self.abs_dest = absdest
def _Copy(self):
src = self.abs_src
dest = self.abs_dest
# copy file if it does not exist or is out of date
if not os.path.exists(dest) or not filecmp.cmp(src, dest): ※
※line shows the condition to do a file copy.
code below your pice
if not os.path.exists(dest) or not filecmp.cmp(src, dest):
try:
# remove existing file first, since it might be read-only
if os.path.exists(dest):
platform_utils.remove(dest)
else:
dest_dir = os.path.dirname(dest)
if not platform_utils.isdir(dest_dir):
os.makedirs(dest_dir)
shutil.copy(src, dest)
# make the file read-only
mode = os.stat(dest)[stat.ST_MODE]
mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
os.chmod(dest, mode)
so it can replace ...
is this still open?
I just happened to come across the same issue, wanting to overwrite a file from repository2 with a file from repository1, the <copyfile> was in place to replace myfile from repository2 with myfile from repository1. I was using a yocto distribution (with several layers, as git repositories).
But it did not work.
Copying myfile from repository1 as myfile2 to repository2 (another name) worked.
What I discovered was that running the repo init/sync commands several times I did not get the repos to be populated in the same order.
So basically my <copyfile> did what is was supposed to do when repository1 was populated, but that happened before repository2 was populated (even if they were in the right order in the manifest file). And repository2 simply brought its own myfile, overwriting the one copied by repository1.
My mega-solution was to use two <copyfile> tags: one in repository1 to copy myfile as myfile2 into repository2, and the other in repository2 to copy myfile2 as myfile.
You have to make sure though that repository1 is always populated before repository2.
This all thing is very strange, since repo does not guarantee the order in which repositoruies are populated.

Is there an MSBuild macro for build date/time?

Suppose I have a build script with a Target section like the following:
<Target Name="AssemblyVersionMAIN" Inputs="#(AssemblyVersionFiles)" Outputs="UpdatedAssemblyVersionFiles">
<Attrib Files="%(AssemblyVersionFiles.FullPath)" Normal="true"/>
<AssemblyInfo
CodeLanguage="CS"
OutputFile="%(AssemblyVersionFiles.FullPath)"
AssemblyProduct="$(ProductName)"
AssemblyTitle="$(ProductName)"
AssemblyCompany="$(CompanyName)"
AssemblyCopyright="© $(CompanyName) 2014" <!-- THIS LINE -->
AssemblyVersion="$(Major).$(Minor).$(Build).$(Revision)"
AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)"
AssemblyInformationalVersion="$(Major).$(Minor).$(Build).$(Revision)">
<Output TaskParameter="OutputFile" ItemName="UpdatedAssemblyVersionFiles"/>
</AssemblyInfo>
</Target>
At the moment, the year is static and has to be changed manually. Is there a simple way of replacing "2014" with something like $(Year)? I've checked the MSBuild reference but nothing jumps out at me.
Since you are using MsBuild 4 you could also use a property function for this, like e.g.:
<PropertyGroup>
<CurrentDate>$([System.DateTime]::Now.ToString(yyyy.MM.dd))</CurrentDate>
</PropertyGroup>
Just format the recieved date as you need it. There are also plenty of other functions available, see also http://msdn.microsoft.com/en-us/library/dd633440(v=vs.100).aspx.
Since I'm using MSBuild Community Tasks and MSBuild 4, I can substitute the following:
AssemblyCopyright="© $(CompanyName) $([System.DateTime]::Now.ToString(`yyyy`))"
which seems to work.

How to write AssemblyVersion to file using MSBuild?

FinalEdit: Despite relative directories not working in the first post, it worked if I simply removed the $(MsBuildThisFileDirectory) from the Exec line.
Edit2: I added the new targets to the DefaultTargets. Which now runs them by default. However, timing was now off with the postbuild command. I added <Exec Command="call $(MsBuildThisFileDirectory)documentation\tools\GenerateDocumentation.bat" IgnoreExitCode="false" /> to the target, but it gives an error that C:\Users\my is not a valid batch file because of the space which is actually C:\Users\my program\documentation\tools\GenerateDocumentation.bat. Putting quotes around the path gives me error MSB4025 that Name cannot begin with $.
Edit: I have tried stijn's code and it works when I explicitly run it from the command line using /t:RetrieveIdentities, but for some reason it doesn't seem to run otherwise.
I have been using Doxygen to generate documentation for my source code, however, I would like to be able to do it automatically. I wrote a simple .bat script to run Doxygen with my desired config file and compile the output into a .chm help file, but I have been unable to change the revision number automatically in Doxygen.
I was attempting to simply update the config file by adding a new line to the config file with the new revision number using MSBuild, but I have been unable to get anything to print or even create a new file when none is present.
The code I have so far I have gotten from other similar questions, but I cannot seem to get it to work.
<ItemGroup>
<MyTextFile Include="\documentation\DoxygenConfigFile.doxyconfig"/>
<MyItems Include="PROJECT_NUMBER = %(MyAssemblyIdentitiesAssemblyInfo.Version)"/>
</ItemGroup>
<Target Name="RetrieveIdentities">
<GetAssemblyIdentity AssemblyFiles="bin\foo.exe">
<Output TaskParameter="Assemblies" ItemName="MyAssemblyIdentities"/>
</GetAssemblyIdentity>
<WriteLinesToFile File="#(MyTextFile)" Lines="#(MyItems)" Overwrite="false" Encoding="UTF8" />
</Target>
Encoding is wrong, it should be UTF-8
When working with items/properties, the % and # and $ must come right before the (, no spacing in between: %(MyAssemblyIdentitiesAssemblyInfo.Version)
MyAssemblyIdentitiesAssemblyInfo does not exist, you probably meant MyAssemblyIdentities
Look up how msbuild evaluates properties and items. Basically what it will do in your script is evaluate MyItems, but at that time MyAssemblyIdentities does not yet exist so is empty, and only afterwards the GetAssemblyIdentity gets executed. Fix this by enforcing correct evaluation order: put your items inside the target and make it depend on another target that creates MyAssemblyIdentities before evaluating your items.
To summarize:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="GetAssemblyIdentities">
<GetAssemblyIdentity AssemblyFiles="bin\foo.exe">
<Output TaskParameter="Assemblies" ItemName="MyAssemblyIdentities"/>
</GetAssemblyIdentity>
</Target>
<Target Name="RetrieveIdentities" DependsOnTargets="GetAssemblyIdentities">
<ItemGroup>
<MyTextFile Include="\documentation\DoxygenConfigFile.doxyconfig"/>
<MyItems Include="PROJECT_NUMBER = %(MyAssemblyIdentities.Version)"/>
</ItemGroup>
<WriteLinesToFile File="#(MyTextFile)" Lines="#(MyItems)"
Overwrite="false" Encoding="UTF-8" />
</Target>
</Project>
Note this will only work if you invoke msbuild in the directory where the script is, else the paths (documentation/foo) will be wrong. That could be fixed by using eg $(MsBuildThisFileDirectory)\bin\foo.exe)