Accessing HOME path in sublime text 2 command - sublimetext2

I want to have a simple sublime-command to open a specific (dot config) file in my home folder. Is there a variable or other magic I can use like ${packages}, but for the user's home folder?
Currently I have (Default.sublime-commands)
{
"caption": "Edit my config",
"command": "open_file",
"args": {
"file": "/Users/MyName/.myconfig"
}
}
but want to get rid of the hard coded user name.
Unfortunately I can't find anything in the api "documentation" of sublime.

It can be done using custom command like this:
import sublime_plugin, getpass
class OpenCustomFileCommand(sublime_plugin.WindowCommand):
def run(self, file_name):
if("{username}" in file_name):
file_name = file_name.replace("{username}", getpass.getuser())
self.window.open_file(file_name)
and the following (Default.sublime-commands):
{
"caption": "Edit my config",
"command": "open_custom_file",
"args": { "file_name": "/Users/{username}/.myconfig" }
}
And of course you can extend OpenCustomFileCommand with your own replacements.
P.S. Command must be stored within Packages directory of ST2, i.e. in file open_custom_file.py

Related

ASP.NET Core 3 - Serilog how to configure Serilog.Sinks.Map in appsettings.json file?

I came across the Serilog.Sinks.Map addon today which will solve my challenge with routing specific log events to a specific sink interface. In my environment, I am writing to a log file as well as using the SQL interface. I only want certain logs to be written to the SQL Server though.
Reading the instructions on GitHub by the author, I can only see an example for implementing the LoggerConfiguration through C# in the Program.CS, but I am using the appsettings.json file and unsure what to change from the provided example to the required json format.
Example given by Serilog on GitHub:
Log.Logger = new LoggerConfiguration()
.WriteTo.Map("Name", "Other", (name, wt) => wt.File($"./logs/log-{name}.txt"))
.CreateLogger();
My current configuration: Note I haven't implemented the Sinks.Map in my code yet.
Program.CS File:
public static void Main(string[] args)
{
// Build a configuration system with the route of the app settings.json file.
// this is becuase we dont yet have dependancy injection available, that comes later.
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
var host = CreateHostBuilder(args).Build();
}
And here is my appsettings.json file. I want to be able configure sink name 'MSSqlServer' as the special route, then use the standard file appender sink for all the other general logging.
"AllowedHosts": "*",
"Serilog": {
"Using": [],
"MinumumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
//"path": "C:\\NetCoreLogs\\log.txt", // Example path to Windows Drive.
"path": ".\\Logs\\logs.txt",
//"rollingInterval": "Day", // Not currently in use.
"rollOnFileSizeLimit": true,
//"retainedFileCountLimit": null, // Not currently in use.
"fileSizeLimitBytes": 10000000,
"outputTemplate": "{Timestamp:dd-MM-yyyy HH:mm:ss.fff G} {Message}{NewLine:1}{Exception:1}"
// *Template Notes*
// Timestamp 'G' means UTC Time
}
},
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "DefaultConnection",
"schemaName": "EventLogging",
"tableName": "Logs",
"autoCreateSqlTable": true,
"restrictedToMinimumLevel": "Information",
"batchPostingLimit": 1000,
"period": "0.00:00:30"
}
}
//{
// "Name": "File",
// "Args": {
// "path": "C:\\NetCoreLogs\\log.json",
// "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
// }
//}
]
}
Lastly if i could squeeze in another quick question on the topic, when using the SQL sink interface, how do manage the automatic purging/deletion of the oldest events i.e. DB should only store max 1,000,000 events then automatically write over the oldest event first, thanks in advance
I believe it is currently impossible to configure the standard Map call in json, since it relies on a few types that have no serialization support right now, like Action<T1, T2>. I created an issue to discuss this in the repository itself:
Unable to configure default Map call in json? #22
However, there is a way to still get some functionality out of it in Json, by creating a custom extension method. In your particular case, it would be something like this:
public static class SerilogSinkConfigurationExtensions
{
public static LoggerConfiguration MapToFile(
this LoggerSinkConfiguration loggerSinkConfiguration,
string keyPropertyName,
string pathFormat,
string defaultKey)
{
return loggerSinkConfiguration.Map(
keyPropertyName,
defaultKey,
(key, config) => config.File(string.Format(pathFormat, key));
}
}
Then, on your json file, add a section like this:
"WriteTo": [
...
{
"Name": "MapToFile",
"Args": {
"KeyPropertyName": "Name",
"DefaultKey": "Other",
"PathFormat": "./logs/log-{0}.txt"
}
}
]
To have these customizations work properly, Serilog needs to understand that your assembly has these kinds of extensions, to load them during the parsing stage. As per the documentation, you either need to have these extensions on a *.Serilog.* assembly, or add the Using clause on the json:
// Assuming the extension method is inside the "Company.Domain.MyProject" dll
"Using": [ "Company.Domain.MyProject" ]
More information on these constraints here:
https://github.com/serilog/serilog-settings-configuration#using-section-and-auto-discovery-of-configuration-assemblies

How to configure a custom kiosk-enabled app from Google Admin (App Management)?

I have some "Single app Chrome kiosk device management license" and I want to set a url remotely (from Google Admin) for each OU.
When using Chrome Sign Builder, it is easy, there is a "configure" button :
But now I built my App using Chrome App Builder and there is no way to have those "environment variables" through the json config file (the button "configure" is not there) :
How to show this "configure" button?
EDIT : https://support.google.com/chrome/a/answer/6137033?hl=en "If a Chrome app supports a config file, you can upload a config file to customize the app." -> So I guess It is definitely doable, but I can't find how
EDIT 2:
Admin Google did an interface update, so for those:
Use managed storage
Add this into manifest.json
"storage": {
"managed_schema": "schema.json"
}
example of schema.json :
{
"type": "object",
"properties": {
"defaultUrl": {
"type": "string"
}
}
}
Now you have the button, and you are able to upload a configuration file like this one :
{
"defaultUrl": {
"Value": "https://www.stackoverflow.com"
}
}
And in your code, you can get it like this :
chrome.storage.managed.get('defaultUrl', function (data) {
//data.defaultUrl
});

How do I configure VS Code to enable code completion on .json files (jsonschema support)?

In the Visual Stuido Code demo minute 28:57-29:20 and 30:20-31:10, some cool JSON code completion is shown.
Where and how do I add a schema for my JSON files to a project?
How does VS Code know which schema to use for a given .json file?
The association of JSON schemas to files is done in the settings (File, Preferences, User Settings or Workspace Settings), under the property 'json.schemas'.
This is an example how the JSON schema for bower is associated to the bower schema.
"json.schemas": [
{
"fileMatch": [
"/bower.json",
"/.bower.json"
],
"url": "http://json.schemastore.org/bower"
},
...
You can also use schemas located in your workspace or define a schema right in the settings itself. Check https://code.visualstudio.com/docs/languages/json for examples.
You can refer your JSON Schema in $schema node and get your intellisense in VS Code right away. No need to configure anywhere else.
For example,
{
"$schema": "http://json.schemastore.org/coffeelint",
"line_endings": "unix"
}
This is the intellisense I was talking about. JSON Schema has the list of possible JSON properties in your current cursor position and VS Code can pull out that list of intellisense.
Note that, every official JSON should have a concrete JSON Schema to prove the data integrity. This answer is still valid!
The three ways I've got VS Code to use a JSON schema are ...
So for something like the Azure Function schema from ... http://json.schemastore.org
"json.schemas": [
{
"fileMatch": [
"/function.json"
],
"url": "http://json.schemastore.org/function"
}
]
In User Settings", i.e. as an element in the users settings.json in 'C:\Users\\AppData\Roaming\Code\User'
In the "Workspace Settings", then in it's the "settings" section in the .code-workspace file ... assuming your're using a VS Code Workspace
In the "Folder Settings", it's "settings" section in the settings.json, which is in the .vscode directory ... assuming your're using a VS Code Workspace
The Folder takes precedence over Workspace, and Workspace over User
And the Workspace and Folder work with relative paths, e.g. in the .code-workspace file ...
"settings": {
"json.schemas": [
{
"fileMatch": [
"/task.json"
],
"url": "./schema/tasks.schema.json"
}
]
}
or in the Folder Settings settings.json in \.vscode\ ...
"json.schemas": [
{
"fileMatch": [
"/task.json"
],
"url": "./schema/tasks.schema.json"
}
]
Just add the following configuration item to the settings file to fix it:
"json.validate.enable": false
Or use the GUI way:

How to indent JSON data inside of TextMate, Emacs, BBEdit, or Sublime Text 2?

[Update: 8 hours after this question was posted, the author of JSON bundle was notified of the issue and he fixed it.]
I have the following JSON data in a file application.json, shown at the end of this post, and I have used TextMate with the JSON bundle, Emacs, BBEdit, and Sublime Text 2 to properly indent it, but all seemed like they couldn't.
Both TextMate and Sublime Text 2 insisted that the first { should not be indented, and the first major issue was for the closing brace for "child": {. Both TextMate and Sublime Text 2 refused to align the } under the left side of "child": {. Emacs kept on indenting further and further for each line, and BBEdit didn't seem to have an re-indent function at all (could this be?).
Is there a way to properly indent the file, or are TextMate and Sublime Text 2 both doing the right thing for the JSON data?
[
{
"settings": [ "master" ],
"appPort": "8666",
"specs": {
"frame" : {
"type" : "HTMLFrameMojit",
"config": {
"deploy": true,
"child": {
"type" : "HelloWorldMojit"
},
"assets": {
"top": {
"css": [
"/static/HelloWorldMojit/assets/index.css"
]
}
}
}
}
}
},
{
"settings": [ "environment:development" ],
"staticHandling": {
"forceUpdate": true
}
}
]
EDIT: For BBEdit use siegel's suggestion of Text > Reformat Document
Original Reply:
I found a solution for BBEdit that is easy and works well.
Put the following script in
~/Library/Containers/BBEdit/Data/Library/Application Support/BBEdit/Text Filters/FormatJSON.sh (on MacOS 11 Big Sur, or above)
For MacOS 10.15 Catalina and below, use this location: ~/Library/Application Support/BBEdit/Text Filters/FormatJSON.sh
#!/bin/bash
python -m json.tool
Open a JSON file in BBEdit. There is no need to restart BBEdit because BBEdit rocks!
Select Text > Apply Text Filter > FormatJSON
I tested this with a JSON file that had 3,612,683 characters on a single line. BBEdit opened this file and reformatted without showing a "Spinning Beachball of Death" busy-wait mouse cursor.
Solution 1: Using Python
This answer is similar to this answer, except I am using python file to do the JSON format.
Exit bbedit application if it is open,
put following script pretty-json.py in ~/Library/Application\ Support/BBEdit/Text\ Filters/ path
#!/usr/bin/env python
# You can change above she-bang line depending on your Mac configuration
import sys
import json
def main():
input = sys.stdin.read()
try:
obj = json.loads(input)
except Exception as e:
print input + "\n\nERROR: " + str(e)
return 1
print(json.dumps(obj, indent=2))
return 0
if __name__ == '__main__':
sys.exit(main())
To Test, open a JSON file in BBEdit.
Select Text --> Apply Text Filter --> pretty-json.py
If you face any issue like formatting error, then the above script will add error in New file and will not change the original JSON.
which is not the case with this answer
Ref: https://gist.github.com/brokaw/95ade1358954cd97d0f2c8e992e14b08
For more info: Refer this
The above filter works fine for smaller JSON files, but if the JSON file is large(~ 40MB) then formatting will be slow.
To solve this, use the following solution
Solution 2: Using jq
For faster json formatting,
Install jq brew install jq
Check if you are able to execute jq in terminal, or need a full path, add whichever works in following file in place of jq
Add fast-json-pretty.sh file in ~/Library/Application\ Support/BBEdit/Text\ Filters/ location
Restart bbedit.
#!/bin/bash
jq
In BBEdit 14.0 and later, "Reformat Document" on the text menu will reflow JSON. You can also use the built-in Language Server Support with a JSON language server that supports reformatting.
I just corrected this issue in the bundle, for 2.0 users the bundle should update within 24 hours with the correction.
According to http://jsonprettyprint.com/ Textmate and Sublime aren't doing the right thing.
What version of Emacs did you use?
With 24.2.1, your JSON blob indented perfectly without issues in js-mode (Emac's default javascript major-mode).
If you do any significant Javascript development I recommend checkint out js2-mode https://github.com/mooz/js2-mode, which turns Emacs into a great JS IDE.
Sublime Pretty JSON
Sublime Pretty JSON indents the first { well.
This is what I get:
[
{
"settings": [
"master"
],
"appPort": "8666",
"specs": {
"frame": {
"type": "HTMLFrameMojit",
"config": {
"deploy": true,
"child": {
"type": "HelloWorldMojit"
},
"assets": {
"top": {
"css": [
"/static/HelloWorldMojit/assets/index.css"
]
}
}
}
}
}
},
{
"settings": [
"environment:development"
],
"staticHandling": {
"forceUpdate": true
}
}
]
Installation
Within Sublime Text 2: Preference => Package Control => Install Package => "Pretty Json" => Restart Sublime => Select JSON Text => Press:
Linux: ctrl+alt+j
Windows: ctrl+alt+j
OS X: cmd+ctrl+j
This is a solution simply using Google Chrome or NodeJS itself, and here is how:
Just open up the Google Chrome dev tool or NodeJS prompt, and type in
obj =
and copy and paste the object into it, so it will be like
obj = [
{
// etc
Now, in Google Chrome, just type
JSON.stringify(obj, null, 4)
and you will have the formatted JSON. In NodeJS, since it prints out the \n verbatim, you can use
console.log(JSON.stringify(obj, null, 4))
If you want the indentation to be just 2 spaces, just use 2 instead of 4.
If you want the indentation to be tabs instead of spaces, simply use
JSON.stringify(obj, null, "\t")
Create a script file fast-json-pretty.sh in ~/Library/Application\ Support/BBEdit/Text\ Filters/
Insert the following script:
#!/usr/bin/env bash
/usr/local/bin/jq .
Apply the text filter as follows: Menu bar --> Text --> Apply Text Filter --> fast-json-pretty
This is a reworked version of DKB's version of his JQ script as it, at least for me, required the full path and a dot (.) at the end to make this work.
Just check to see which version of python is installed:
using json_pretty will only work if the python interpreter is whatever is installed in the shell being called. For example, my json_pretty works and I have modded it as follows on Ventura:
#!/bin/zsh
python3 -m json.tool

How to configure a Sublime Build System for TypeScript

I'm looking to configure a Build System in Sublime Text for TypeScript.
I'm currently using...
{
"cmd": ["tsc", "$file"],
"selector": "source.ts"
}
I'd also like to set the 'file_regex' property to handle error messages.
Anyone know what to set this to?
Use this on OS-X:
{
"cmd": ["tsc","$file"],
"file_regex": "(.*\\.ts?)\\s\\(([0-9]+)\\,([0-9]+)\\)\\:\\s(...*?)$",
"selector": "source.ts",
"osx": {
"path": "/usr/local/bin:/opt/local/bin"
}
}
EDIT:
Here is the Sublime Build System created for Windows. Tested and working as expected. However you need to include tsc.cmd path in the windows environment, otherwise you should define the root to the Typescript command in the cmd section below:
{
"cmd": ["tsc","$file"],
"file_regex": "(.*\\.ts?)\\s\\(([0-9]+)\\,([0-9]+)\\)\\:\\s(...*?)$",
"selector": "source.ts",
"windows": {
"cmd": ["tsc.cmd", "$file"]
}
}
There are two versions now. This one, or this one. Creating your own is easy, by referring to this document.