Coder Social home page Coder Social logo

pascalre / vscode-yaml-sort Goto Github PK

View Code? Open in Web Editor NEW
42.0 0.0 2.0 5.86 MB

This VS Code extension exposes the possibility to sort, format and validate yaml files.

Home Page: https://marketplace.visualstudio.com/items?itemName=PascalReitermann93.vscode-yaml-sort

License: MIT License

TypeScript 85.73% JavaScript 14.27%
vscode visual-studio-code yaml yaml-validator yaml-sorting yaml-sort sort yaml-format

vscode-yaml-sort's People

Contributors

deepsourcebot avatar dependabot[bot] avatar pascalre avatar renovate[bot] avatar snyk-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vscode-yaml-sort's Issues

emptyLinesUntilLevel doesn't work with keys containing spaces

Brand:
  baz: blub
Some blubtest:
  another: key

foo:
  test: 2

is the result of sorting with these settings:

    "vscode-yaml-sort.emptyLinesUntilLevel": 1,
    "vscode-yaml-sort.useLeadingDashes": false,

When I remove the space in Some blubtest then it works correctly:

Brand:
  baz: blub

Someblubtest:
  another: key

foo:
  test: 2

Using YAML Sort v5.1.6

Sort all files in directory

I was found plugin usefull but found that i'm stuck in that workflow
open file press ctrl+shift+p select most last used command and press enter.
i was tied to do this on 5-th file and i got much more then thousand.

can you please add option on directory level in left menu to sort all files in directory

Configurable manual sort order

Dear @pascalre ,

I would like to ask if it is possible to add a configurable option with witch I could manually specify sort order for some keys. Let me explain. The main reason I use YAML sort plugin if to reduce difficulties during merging YAML-configuration across different git branches. It is much easier to merge when the order of keys is the same in the conflicting branches. Most of the YAML files I work with is either Kubernetes manifests or different their variations, e.g. Kustomize rules (kustomization.yaml). The thing is, in such files there is some natural order of keys which is not always alphabetical. I've seen #3 about Kubernetes-friendly sort, but I suppose it is better to have an option, so I can manually configure the plugin specifically for my project. Just as a motivating example, please, consider typical kustomization.yaml:

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
commonLabels: ...
patches: ...
resources: ...

For this type of files the "natural" sort order is the following:

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources: ...
patches: ...
commonLabels: ...

which obviously differs from the alphabetical order.

Allow for configuration of line length

Thanks for the extension. I've kept Atom around specifically to sort a few files.

Would you consider either defaulting to a long line length on sort ( > 500), or potentially adding a configuration point for it?

    let sorted_yaml = yaml_parser.safeDump(doc, {
      sortKeys: true,
      lineWidth: config.lineWidth
    });

I'm happy to work up a PR for it, though I've never authored an extension so I'm not sure what's involved.

Merges mappings even with noCompatMode: true

I am using Merge Key Language-Independent Type for YAML™ Version 1.1 as described here because it's more convenient to have some keys in one place. Still, the extension inserts all the mappings where they were used with << merge key even when noCompatMode: true is set.

Is the behavior expected?

Add new line after 2nd/Nth level key

First of all, thanks for this great extension. I'm using this to sort my AWS CloudFormation Stacks.

For a better readability of big files it would be great to add empty lines after second-level keys, too - like vscode-yaml-sort.addNewLineAfterTopLevelKey does for first level. Maybe it could be even possible to configure with an int value until which level a new line will be added.

Sort by Value

I think this is a feature request:

The extension sorts by Key. But I have not seen the possibility to sort by Value.

Do you accept merge request for this?

Keep comments in the yaml file

The tool removes all comments in the yaml file. Please keep the comments and if possible, provide an option (sticky comment) where the comment won't be sorted and stay with the non-comment line below.

Use custom sort recursively on the whole file

Can the custom sort order be extended so that it works recursively on the whole file? I do see that it is sorting the whole file but the custom sort order seem to be only applied at the top level?

Im using this to get a custom sort on a swagger yml file:

For example:

top_thing:
  /some_path:
    get:
      description: returns a list of things
      parameters:
        - in: query
          name: color     <---- I would like 'name' to appear before 'in', sorting keeps moving this down
          required: false
          type: string
        - in: query
          name: width
          required: false
          type: number

In the meantime I did this:
https://gist.github.com/RodriguezLucha/1dda9637d32fc085533774cf63dd3c29

keep multiline strings on sort

I use multiline strings to meet linter line length requirements for my team. But after the sort my multiline string becomes the single line string and I have to split it again.

Commented lines are being removed

IMO, there should be a config option to allow the user choose whether or not the sorter should remove commented lines. Eg, in a list of items, the user might comment/uncomment items to experiment stuff or she might add important information as a line comment

Support multiple yaml documents when sorting

Unfortunately, this plugin does not support YAML-documents with several YAMLs inside separated by ---. It is quite typical to have several Kubernetes manifests in a single YAML-file. For example, we have a lot of manifests with both kind: Service & kind: Deployment inside. Plugin does not work on these files. It would be nice to support this kind of files.

sort drops value from key, when key in custom sort list

Sorting snippet below with Custom sort list, where "proxyext_urls" is in custom list, looses the "b"

##Start
proxyext_urls:
  - aa: "b" #6631
test2: ok
##End

ctrl+shift+p
custom sort 3

results in

proxyext_urls:
  - aa: 
test2: ok

Add support for sorting arrays

Please add support for sorting arrays and arrays of objects.

As per the example animations, it does not sort pascal, python and perl.

Add support for CloudFormation schema

What a great extension !

I would like the ability to sort AWS CloudFromation YAML e.g. https://raw.githubusercontent.com/awslabs/aws-cloudformation-templates/master/aws/solutions/CloudFrontCustomOriginLambda%40Edge/CloudFront.yaml

At the moment the Extension throws an error due to !Sub / !Join / !Ref Cloudformation functions - with Invalid Yaml (Maybe this validation could omit the validity check?)

What would also be VERY nice if it was possible to group Yaml blocks based on linkages used by the !Ref or !Sub

Consider two yaml blocks at the same level feature would be IAM role is put next to an IAM policy because there is a !Ref marker to the IAM role in the IAM policy.

kubernetes friendly sort

Can you please add an option to sort options in a way that can be kubernetes manifests friendly.

by meaning so i am talking about sorting files like configmaps. let me describe problem. most of kubernets files starts with

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    service: activator-default
  name: activator-default
spec:

and so on. there can be clearly seen api version and kind also metadata. that info is pretty useful and have them in one place.

but not for configmaps
they are lack of spec but use data attribute. so we will get

apiVersion: v1
data:
....
metadata:
  name: noc-configmap

where data can and probably will be pretty long. so during sort we have to define list of keys that should be unsorted and always on the top.

that is only for top most keys. probably everything else should be sorted as always by alphabet

Sort based on number/length of children

Is it possible somehow to sort based on the number of lines taken up by children of a given key?

For example, this:

c: foo
b:
  x: foo
  z: bar
  y: baz
a:
  - foo: bar
  - bar: foo

would sort as:

c: foo
a:
  - bar: foo
  - foo: bar
b:
  x: foo
  y: baz
  z: bar

Although not shown here, it'd be helpful if this was supported recursively too.

The use case for this is to avoid putting small keys/values after large, extensively indented ones, like this:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: some-cron
  namespace: my-namespace
spec:
  concurrencyPolicy: Forbid
  failedJobsHistoryLimit: 1
  jobTemplate:
    metadata:
      creationTimestamp: null
    spec:
      backoffLimit: 3
      template:
        metadata:
          creationTimestamp: null
        spec:
          containers:
            - name: somecron
              image: some/image:1.2.3
              imagePullPolicy: IfNotPresent
              args:
                - echo
              command:
                - Foo
              env:
                - name: ENVIRONMENT
                  value: my_env
                - name: ALLOWED_HOST
                  value: some.host.com
              resources:
                limits:
                  cpu: 1
                  memory: 500M
                requests:
                  cpu: 1
                  memory: 500M
              terminationMessagePath: /dev/termination-log
              terminationMessagePolicy: File
          dnsPolicy: ClusterFirst
          imagePullSecrets:
            - name: mysecrets
          restartPolicy: OnFailure
          schedulerName: default-scheduler
          terminationGracePeriodSeconds: 30
  schedule: 10 * * * *  # These keys should be moved above the huge 'jobTemplate' tree
  successfulJobsHistoryLimit: 3
  suspend: false

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update dependency @types/node to v20.14.2
  • fix(deps): update dependency @types/vscode to v1.90.0
  • fix(deps): update dependency @vscode/test-electron to v2.4.0
  • fix(deps): update dependency glob to v10.4.1
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update dependency eslint to v9
  • chore(deps): update dependency sinon to v18
  • chore(deps): update dependency sonarqube-scanner to v4
  • chore(deps): update github/codeql-action action to v3

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

docker-compose
docker-compose.yml
github-actions
.github/workflows/action.yml
  • actions/checkout v4
  • actions/setup-node v3
  • GabrielBB/xvfb-action v1
.github/workflows/codeql-analysis.yml
  • actions/checkout v4
  • github/codeql-action v2
  • github/codeql-action v2
  • github/codeql-action v2
.github/workflows/publish.yml
  • actions/checkout v4
  • actions/setup-node v3
npm
package.json
  • @types/js-yaml ^4.0.6
  • @types/vscode ^1.88.0
  • @vscode/test-electron ^2.1.5
  • cloudformation-js-yaml-schema ^0.4.2
  • glob ^10.3.5
  • homeassistant-js-yaml-schema ^1.1.0
  • js-yaml ^4.1.0
  • @types/mocha ^10.0.4
  • @types/node ^20.11.5
  • @types/sinon ^17.0.3
  • @typescript-eslint/eslint-plugin ^7.2.0
  • @typescript-eslint/parser ^7.2.0
  • coveralls 3.1.1
  • dependency-cruiser ^16.0.0
  • eslint ^8.57.0
  • eslint-import-resolver-typescript ^3.5.3
  • eslint-plugin-import ^2.27.5
  • jsdoc ^4.0.2
  • mocha ^10.2.0
  • nyc 15.1.0
  • sinon ^17.0.0
  • sonarqube-scanner ^3.0.1
  • ts-node 10.9.2
  • typescript ^5.3.3
  • typescript-require 0.3.0
  • vscode ^1.49.0

  • Check this box to trigger a request for Renovate to run again on this repository

Add support for single line arrays

Is it possible to avoid line brakes for specific keys? EX: I use health checks sometimes in docker compose, and it makes it look kind of messy /w it breaking out the array. I'd like to have the ability to exclode for example below... test.

EX:
test: [ "CMD", "pg_isready", "-q", "-d", "${DB_NAME}", "-U", "${DB_USER}" ]
becomes

      test:
        - "CMD"
        - "pg_isready"
        - "-q"
        - "-d"
        - "${DB_NAME}"
        - "-U"
        - "${DB_USER}"

Support line breaks

Currently when yaml is sorted, line breaks are removed. It'd be nice to either maintain line breaks or have a config option to insert line breaks between keywords. For instance

name: app
description: A new application.

version: 1.0.0+2

environment:
  sdk: ">=2.6.0 <3.0.0"

instead of

name: app
description: A new application.
version: 1.0.0+2
environment:
  sdk: ">=2.6.0 <3.0.0"

trying to sort a nested dictionary results in removing it completely

Apparently the only option to sort is to sort root level keys as for others this extension removes the lines.

artcl_commands:
  system:
    cpuinfo:
      capture_file: /var/log/extra/cpuinfo.txt
      cmd: cat /proc/cpuinfo
    dmesg:
      cmd: dmesg
    meminfo:
      capture_file: /var/log/extra/meminfo.txt
      cmd: cat /proc/meminfo
    pcs:
      cmd: |
        if type pcs &>/dev/null; then
          echo "+ pcs status"
          pcs status
          echo "+ pcs config"
          pcs config
        fi
    swaps:
      cmd: cat /proc/swaps
      capture_file: /var/log/extra/swaps.txt
    top:
      cmd: top -b -n 1
    rpm-list:
      cmd: rpm -qa | sort -f
    package-list-installed:
      cmd: "{{ ansible_pkg_mgr }} list installed"
      cmd: "{{ ansible_pkg_mgr }} repolist -v"
    selinux:
      cmd: /usr/sbin/getenforce
    installed_crons:
      cmd: |
        for user in $(cut -f1 -d':' /etc/passwd); do
        echo $user; crontab -u $user -l | grep -v '^$\|^\s*\#\|^\s*PATH'
        done

I am not sure what is confusing the sorting but I hope to be fixed as on big dics is very useful.

emptyLinesUntilLevel doesn't work with keywords containing dashes

Hello,

Love the extension! However, I have found it is not always consistent /w the emptyLinesUntilLevel settings. I haven't been able to identify the root cause thus far. I used this for sort my yaml and you can see how it is missing the nested line breaks on lines 33, 247, and 390.

Here is my yaml file:

https://github.com/Dulanic/docker-compose/blob/main/docker-compose.yml

These are my settings:


    "vscode-yaml-sort.customSortKeywords_1": [
        "version",
        "services",
        "container_name",
        "image",
        "user",
        "depends_on",
        "enviroment",
        "env_file",
        "shm_size",
        "hostname",
        "ports",
        "volumes",
        "restart",
        "volumes",
        "command",
        "health_check"
    ],
    "vscode-yaml-sort.useAsFormatter": true,
    "vscode-yaml-sort.emptyLinesUntilLevel": 2,
    "vscode-yaml-sort.quotingType": "\"",
    "vscode-yaml-sort.forceQuotes": true,

Force quotes on strings when sorting

When sorting a yaml block, strings that were double quoted gets stripped of quotes.

Before

  - matched_address: "peer1"
    map: "Standard-1"
    seq: "20"
    pfs: "group5"
    peer: "Peer-1"
    ike: "ikev1"
    transform: "Standard-Transform"
    sa: "28800"

After

  - ike: ikev1
    map: Standard-1
    matched_address: peer1
    peer: Peer-1
    pfs: group5
    sa: '28800'
    seq: '20'
    transform: Standard-Transform

Use as formatter

I wonder if it's possible to register this extension as a formatter for yaml files? When I'm in a .yml file in VSCode and run "Format Document", it tells me There is no formatter for 'yaml' files installed..

Having this wonderful extension as a formatter would also allow me to configure that it auto-formats on save 🙃

Add support for Helm charts

Consider this snippet:
apiVersion: keycloak.org/v1alpha1
kind: KeycloakClient
metadata:
labels:
app: clientsso
name: {{ .Values.ui.environment.keycloakClientId }}
namespace: {{ required "Keycloak namespace required" .Values.keycloak.namespace }}

If I use yamlsort on it, I get this:

apiVersion: keycloak.org/v1alpha1
kind: KeycloakClient
metadata:
labels:
app: clientsso
name:
'[object Object]': null <<<<<<<<<<<<<<<<<
namespace:
'[object Object]': null <<<<<<<<<<<<<<<<<

Note that the values for name and namespace have been modified.
Is there a workaround?

Sorting an arbitrary section (with leading spaces)

YAML to be sorted
# yaml-language-server: $schema=https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/schema.json
blocks:
  - type: prompt
    alignment: left
    newline: true
    segments:
      - type: iterm
        style: plain
        foreground: cyan
        template: "{{ .PromptMark }}"
      - type: os
        style: diamond
        trailing_diamond: <transparent,></>
        foreground: cyan
        properties:
          alpine: 
          arch: 
          centos: 
          debian: 
          elementary: 
          fedora: 
          gentoo: 
          linux: 
          macos: 
          manjaro: 
          mint: 
          opensuse: 
          raspbian: 
          ubuntu: 
          windows: 
          wsl: 
          wsl_separator: 
        template: " {{ if .WSL }}{{ end }}{{.Icon}}═"
      - type: shell
        style: diamond
        leading_diamond: 
        background: green
        foreground: black
        template: "  {{ .Name }} "
      - type: session
        style: powerline
        powerline_symbol: 
        background: magenta
        foreground: black
        template: " {{ if .SSHSession }} {{ end }}{{ .UserName }}@{{ .HostName }} "
      - type: angular
        style: powerline
        powerline_symbol: 
        background: lightRed
        foreground: black
        properties:
          fetch_version: true
        template: " ﮰ {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} "
      - type: aws
        style: powerline
        powerline_symbol: 
        background_templates:
          - '{{if contains "default" .Profile}}yellow{{end}}'
          - '{{if contains "jan" .Profile}}magenta{{end}}'
        foreground: black
        properties:
          display_default: false
        template: "  {{ .Profile }}{{ if .Region }}@{{ .Region }}{{ end }} "
      - type: az
        style: powerline
        powerline_symbol: 
        background: lightBlue
        foreground: black
        properties:
          display_default: false
        template: ' ﴃ Subscription {{ .Name }} ({{ if .EnvironmentName | contains \"AzureCloud\" }}{{ \"Global\" }}{{ else }}{{ .EnvironmentName }}{{ end }}) '
      - type: azfunc
        style: powerline
        powerline_symbol: 
        background: yellow
        foreground: black
        properties:
          display_mode: files
          fetch_version: false
        template: " ﴃ {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} "
      - type: cds
        style: powerline
        powerline_symbol: 
        template: '  cds {{ .Full }} '
      - type: go
        style: powerline
        powerline_symbol: 
        background: lightCyan
        foreground: black
        properties:
          fetch_version: true
        template: "  {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} "
      - type: java
        style: powerline
        powerline_symbol: 
        background: lightCyan
        foreground: black
        template: "  {{ .Full }}"
      - type: julia
        style: powerline
        powerline_symbol: 
        background: lightCyan
        foreground: black
        properties:
          fetch_version: true
        template: "  {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} "
      - type: kubectl
        style: powerline
        powerline_symbol: 
        background: lightYellow
        foreground: black
        template: " ﴱ {{.Context}}{{if .Namespace}} :: {{.Namespace}}{{end}} "
      - type: node
        style: powerline
        powerline_symbol: 
        background: lightGreen
        foreground: black
        properties:
          fetch_version: true
        template: "  {{ if .PackageManagerIcon }}{{ .PackageManagerIcon }} {{ end }}{{ .Full }} "
      - type: php
        style: powerline
        powerline_symbol: 
        background: lightCyan
        foreground: black
        template: "  {{ .Full }} "
      - type: project
        style: powerline
        powerline_symbol: 
        background: lightYellow
        foreground: black
        template: " {{ if .Error }}{{ .Error }}{{ else }}{{ if .Version }} {{.Version}}{{ end }} {{ if .Name }}{{ .Name }}{{ end }}{{ end }} "
      - type: python
        style: powerline
        powerline_symbol: 
        background: lightYellow
        foreground: black
        properties:
          display_mode: files
          fetch_virtual_env: false
        template: "  {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} "
      - type: ruby
        style: powerline
        powerline_symbol: 
        background: red
        foreground: black
        properties:
          display_mode: files
          fetch_version: true
        template: "  {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} "
      - type: time
        style: powerline
        powerline_symbol: 
        background: yellow
        foreground: black
        properties:
          time_format: Mon | 15:04:05
        template: " {{ .CurrentDate | date .Format }} "
      - type: executiontime
        style: diamond
        trailing_diamond: 
        background: cyan
        foreground: black
        properties:
          style: austin
          threshold: 0
        template: " {{ .FormattedMs }} "
  - type: prompt
    alignment: right
    segments:
      - type: git
        style: diamond
        leading_diamond: 
        trailing_diamond: 
        background: magenta
        foreground: black
        properties:
          branch_icon: ""
          fetch_stash_count: true
          fetch_status: true
          fetch_upstream_icon: true
          fetch_worktree_count: true
        template: "{{ .UpstreamIcon }}{{ .HEAD }}{{ .BranchStatus }}{{ if .Working.Changed }}  {{ .Working.String }}{{ end }}{{ if and (.Working.Changed) (.Staging.Changed) }} |{{ end }}{{ if .Staging.Changed }}  {{ .Staging.String }}{{ end }}{{ if gt .StashCount 0 }}  {{ .StashCount }}{{ end }}"
  - type: prompt
    alignment: left
    newline: true
    segments:
      - type: text
        style: plain
        foreground: cyan
        template: ""
      - type: exit
        style: diamond
        leading_diamond: 
        background: blue
        background_templates:
          - "{{ if gt .Code 0 }}red{{ end }}"
        foreground: black
        properties:
          always_enabled: true
        template: "{{ if gt .Code 0 }}  {{ else }} {{ end }}"
      - type: path
        style: powerline
        powerline_symbol: 
        background: blue
        background_templates:
          - "{{ if not .Writable }}red{{ end }}"
        foreground: black
        properties:
          style: agnoster_short
          folder_icon: 
          folder_separator_icon: ""
          home_icon: 
          max_depth: 3
        template: "{{ if gt .Code 0 }} {{ else }}{{ end }} {{ .Path }}{{ if not .Writable }}  {{  end  }}"
      - type: text
        style: accordion
        powerline_symbol: 
        background: blue
        background_templates:
          - "{{ if and .Segments.Path.Writable (not .Root) }}{{ else }}red{{ end }}"
        foreground: white
        properties:
          root_icon: 
        template: "{{ if and .Root (not .Segments.Path.Writable) }}  {{ end }}{{ if and .Root .Segments.Path.Writable }}  {{ end }}"
console_title_template: "{{ .Folder }}"
osc99: true
palette:
  black: "#1B1A23"
  blue: "#9580FF"
  black-background: "#22212C"
  lightBlue-brightBlue: "#AA99FF"
  lightCyan-brightCyan: "#99FFEE"
  lightGreen-brightGreen: "#A2FF99"
  lightMagenta-brightPurple: "#FF99CC"
  lightRed-brightRed: "#FFAA99"
  lightWhite-brightWhite: "#FFFFFF"
  lightYellow-brightYellow: "#FFFF80"
  selection-selectionBackground: "#454158"
  comment-brightBlack: "#7970A9"
  cyan: "#80FFEA"
  green: "#8AFF80"
  magenta-purple: "#FF80BF"
  red: "#FF9580"
  white-cursorColor-foreground: "#F8F8F2"
  yellow: "#FFCA80"
version: 2

Let's say I wanted to sort from Line 46 - type: angular to Line 150 template: "  {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} ". This is a subset of a list. I select my text, summon vscode-yaml-sort, and...

YAML selection is invalid. Please check the ending of your selection.
YAML is invalid: bad indentation of a mapping entry (2:14)

 1 | - type: angular
 2 |         style: powerline
------------------^
 3 |         powerline_symbol: 
 4 |         background: lightRed

I have to shift-tab them back over to the left so they're valid YAML before running vscode-yaml-sort, then tab them back home again. It would be nice if the extension could identify left-aligned blocks of whitespace shared by all lines in a text selection, then ignore them before it validates the YAML.

Ultimately I'd like to be able to sort the list elements by a specific key shared by all (Type, or the first key in this case), but I recognize that is a whole other layer of complexity.

Make formatter configurable

Hi,

the automatic formatting of YAML-files is a great feature.
Working a lot with Ansible, there's YAML all over the place.

Unfortunately the updated plugin now "aggressively" removes empty lines,
quotes and curly-braces. (I guess the change was #30 )

Often it is a good idea to remove useless characters like quotes and curly-braces, I agree.
I think it would be nice to have these "cleanup" configurable or executable as a separate command.

Currently I disabled the extension completely because

  • I have too many changes in my files
  • I no longer can read / structure my files because of deleted empty lines

Unexpected date string format

Hi and thanks again for this great extension.

I found out that a simple unquoted date string will be formatted into ISO 8601 Date and time string.

AWSTemplateFormatVersion: 2010-09-09

becomes

AWSTemplateFormatVersion: 2010-09-09T00:00:00.000Z

Is this a bug or a feature? My expected behavior is to keep the short date string even when unquoted.

Custom sort of desired keys, then resume with alphabetical sort?

Hello, I saw that there is a custom sort option that allows me to pass in a series of keys that I want to be sorted in a specific order. That said if you only pass in a few keys it only sorts those relative to each other once they appear alphabetically.

For example, say I have this:

- type: custom:button-card
            aspect_ratio: 1/1
            color_type: card
            color: '#1a759f'
            background: '#8d99ae'
            heading: 🚗 Driveway
            tap_action:
              action: navigate
              navigation_path: living-room
            icon: mdi:sofa
            show_name: false
            hold_action:
              action: none

I want to sort this alphabetically, but only after I sort a few specific keys.

type
title
heading

So I want to sort those specific keys to always be at the top of the list and in this order IF they appear, and then all other keys should be sorted alphabetically following them. I would expect this:

- type: custom:button-card
            heading: 🚗 Driveway
            aspect_ratio: 1/1
            background: '#8d99ae'
            color_type: card
            color: '#1a759f'
            hold_action:
              action: none
            icon: mdi:sofa
            show_name: false
            tap_action:
              action: navigate
              navigation_path: living-room

Instead though using those keys I provided to the custom sort I get this:

- aspect_ratio: 1/1
            color: '#8d99ae'
            color_type: card
            hold_action:
              action: none
            heading: 🚗 Driveway
            icon: mdi:garage
            show_name: false
            tap_action:
              action: navigate
              navigation_path: driveway
            type: custom:button-card

Sorting tabs indented yaml removes code

Using this tool on visual studio, resulted in all the YAML being deleted.
VS code reported that there was an internal bug in the YAML, specifically that there was a duplicated key (there was not, all the parent keys are unique).
If there are such issues, it should keep the code as is before the sort.

Update: after debugging I deducted that the actual issue was that the YAML was tab formated.

Sample:

a-1:
	b:
		d: g
	c:
		d: g
a-2:
	b:
		d: g
	c:
		d: g
b:
	b:
		d: g
	c:
		d: g

How to sort on save?

I'm trying to sort automatically on save like this... but cannot run.

// .vscode/settings.json

"[yaml]": {
      "editor.codeActionsOnSave": {
        "vscode-yaml-sort.sortYaml": true
      }
    },

Do you know a good way to sort files on save?

Un-quoted "on" and "off" strings are quoted after sorting YAML

When having keys and/or values like on and off within YAML files they get quoted when sorting the file. I expect this is due to the fact that in YAML 1.1 those keys evaluate to true or false. Anyway this has been dropped with YAML 1.2 and I would prefer using the latest specification instead of YAML 1.1.

The issue can easily be reproduced by sorting the following unsorted YAML file:

---
key:
  on: foo
  off: egg

Sorted:

---
key:
  'off': egg
  'on': foo

Expected:

---
key:
  off: egg
  on: foo

error in Recursively sort

When I attempt to sort my yaml file, I receive a dialog box with the following message:

"Command 'YAML Sort: Recursively sort YAML files' resulted in an error (Cannot read properties of undefined (reading 'fsPath'))"

Screenshot:
image

Running WSL2 Ubuntu on Windows 11.

uname -a
Linux Carbon 5.10.102.1-microsoft-standard-WSL2 #1 SMP Wed Mar 2 00:30:59 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

About VS Code:

Version: 1.66.2 (user setup)
Commit: dfd34e8260c270da74b5c2d86d61aee4b6d56977
Date: 2022-04-11T07:46:01.075Z
Electron: 17.2.0
Chromium: 98.0.4758.109
Node.js: 16.13.0
V8: 9.8.177.11-electron.0
OS: Windows_NT x64 10.0.22000

YAML file:

---
- key: cert-dcl16-c.NewSuffixes
  value: L;LL;LU;LLU
- key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic
  value: '1'
- key: google-readability-braces-around-statements.ShortStatementLines
  value: '1'
- key: google-readability-function-size.StatementThreshold
  value: '800'
- key: google-readability-namespace-comments.ShortNamespaceLines
  value: '10'
- key: google-readability-namespace-comments.SpacesBeforeComments
  value: '2'
- key: modernize-loop-convert.MaxCopySize
  value: '16'
- key: modernize-loop-convert.MinConfidence
  value: reasonable
- key: modernize-loop-convert.NamingStyle
  value: CamelCase
- key: modernize-pass-by-value.IncludeStyle
  value: llvm
- key: modernize-replace-auto-ptr.IncludeStyle
  value: llvm
- key: modernize-use-nullptr.NullMacros
  value: 'NULL'
- key: readability-identifier-naming.NamespaceCase
  value: lower_case
- key: readability-identifier-naming.InlineNamespaceCase
  value: lower_case
- key: readability-identifier-naming.EnumConstantCase
  value: lower_case
- key: readability-identifier-naming.ConstantMemberCase
  value: lower_case
- key: readability-identifier-naming.PrivateMemberCase
  value: lower_case
- key: readability-identifier-naming.ProtectedMemberCase
  value: lower_case
- key: readability-identifier-naming.PublicMemberCase
  value: lower_case
- key: readability-identifier-naming.MemberCase
  value: lower_case
- key: readability-identifier-naming.ClassConstantCase
  value: lower_case
- key: readability-identifier-naming.ClassMemberCase
  value: lower_case
- key: readability-identifier-naming.GlobalConstantCase
  value: lower_case
- key: readability-identifier-naming.GlobalConstantPointerCase
  value: lower_case
- key: readability-identifier-naming.GlobalPointerCase
  value: lower_case
- key: readability-identifier-naming.GlobalVariableCase
  value: lower_case
- key: readability-identifier-naming.LocalConstantCase
  value: lower_case
- key: readability-identifier-naming.LocalConstantPointerCase
  value: lower_case
- key: readability-identifier-naming.LocalPointerCase
  value: lower_case
- key: readability-identifier-naming.LocalVariableCase
  value: lower_case
- key: readability-identifier-naming.StaticConstantCase
  value: lower_case
- key: readability-identifier-naming.StaticVariableCase
  value: lower_case
- key: readability-identifier-naming.ConstantCase
  value: lower_case
- key: readability-identifier-naming.VariableCase
  value: lower_case
- key: readability-identifier-naming.ConstantParameterCase
  value: lower_case
- key: readability-identifier-naming.ParameterPackCase
  value: lower_case
- key: readability-identifier-naming.ParameterCase
  value: lower_case
- key: readability-identifier-naming.PointerParameterCase
  value: lower_case
- key: readability-identifier-naming.ConstantPointerParameterCase
  value: lower_case
- key: readability-identifier-naming.AbstractClassCase
  value: lower_case
- key: readability-identifier-naming.StructCase
  value: lower_case
- key: readability-identifier-naming.ClassCase
  value: lower_case
- key: readability-identifier-naming.UnionCase
  value: lower_case
- key: readability-identifier-naming.EnumCase
  value: lower_case
- key: readability-identifier-naming.GlobalFunctionCase
  value: lower_case
- key: readability-identifier-naming.FunctionCase
  value: lower_case
- key: readability-identifier-naming.VirtualMethodCase
  value: lower_case
- key: readability-identifier-naming.PrivateMethodCase
  value: lower_case
- key: readability-identifier-naming.ProtectedMethodCase
  value: lower_case
- key: readability-identifier-naming.PublicMethodCase
  value: lower_case
- key: readability-identifier-naming.MethodCase
  value: lower_case
- key: readability-identifier-naming.TypedefCase
  value: lower_case
- key: readability-identifier-naming.ValueTemplateParameterCase
  value: CamelCase
- key: readability-identifier-naming.TemplateTemplateParameterCase
  value: CamelCase
- key: readability-identifier-naming.TypeAliasCase
  value: lower_case
- key: readability-identifier-naming.MacroDefinitionCase
  value: UPPER_CASE
- key: readability-identifier-naming.ObjcIvarCase
  value: lower_case
- key: readability-identifier-naming.NamespacePrefix
  value: ''
- key: readability-identifier-naming.InlineNamespacePrefix
  value: ''
- key: readability-identifier-naming.EnumConstantPrefix
  value: ''
- key: readability-identifier-naming.ConstexprVariablePrefix
  value: ''
- key: readability-identifier-naming.ConstantMemberPrefix
  value: ''
- key: readability-identifier-naming.PrivateMemberPrefix
  value: _
- key: readability-identifier-naming.ProtectedMemberPrefix
  value: _
- key: readability-identifier-naming.PublicMemberPrefix
  value: ''
- key: readability-identifier-naming.MemberPrefix
  value: ''
- key: readability-identifier-naming.ClassConstantPrefix
  value: ''
- key: readability-identifier-naming.ClassMemberPrefix
  value: ''
- key: readability-identifier-naming.GlobalConstantPrefix
  value: ''
- key: readability-identifier-naming.GlobalConstantPointerPrefix
  value: ''
- key: readability-identifier-naming.GlobalPointerPrefix
  value: ''
- key: readability-identifier-naming.GlobalVariablePrefix
  value: ''
- key: readability-identifier-naming.LocalConstantPrefix
  value: ''
- key: readability-identifier-naming.LocalConstantPointerPrefix
  value: ''
- key: readability-identifier-naming.LocalPointerPrefix
  value: ''
- key: readability-identifier-naming.LocalVariablePrefix
  value: ''
- key: readability-identifier-naming.StaticConstantPrefix
  value: ''
- key: readability-identifier-naming.StaticVariablePrefix
  value: ''
- key: readability-identifier-naming.ConstantPrefix
  value: ''
- key: readability-identifier-naming.VariablePrefix
  value: ''
- key: readability-identifier-naming.ConstantParameterPrefix
  value: ''
- key: readability-identifier-naming.ParameterPackPrefix
  value: ''
- key: readability-identifier-naming.ParameterPrefix
  value: ''
- key: readability-identifier-naming.PointerParameterPrefix
  value: ''
- key: readability-identifier-naming.ConstantPointerParameterPrefix
  value: ''
- key: readability-identifier-naming.AbstractClassPrefix
  value: ''
- key: readability-identifier-naming.StructPrefix
  value: ''
- key: readability-identifier-naming.ClassPrefix
  value: ''
- key: readability-identifier-naming.UnionPrefix
  value: ''
- key: readability-identifier-naming.EnumPrefix
  value: ''
- key: readability-identifier-naming.GlobalFunctionPrefix
  value: ''
- key: readability-identifier-naming.ConstexprFunctionPrefix
  value: ''
- key: readability-identifier-naming.FunctionPrefix
  value: ''
- key: readability-identifier-naming.ConstexprMethodPrefix
  value: ''
- key: readability-identifier-naming.VirtualMethodPrefix
  value: ''
- key: readability-identifier-naming.ClassMethodPrefix
  value: ''
- key: readability-identifier-naming.PrivateMethodPrefix
  value: ''
- key: readability-identifier-naming.ProtectedMethodPrefix
  value: ''
- key: readability-identifier-naming.PublicMethodPrefix
  value: ''
- key: readability-identifier-naming.MethodPrefix
  value: ''
- key: readability-identifier-naming.TypedefPrefix
  value: ''
- key: readability-identifier-naming.TypeTemplateParameterPrefix
  value: ''
- key: readability-identifier-naming.ValueTemplateParameterPrefix
  value: ''
- key: readability-identifier-naming.TemplateTemplateParameterPrefix
  value: ''
- key: readability-identifier-naming.TemplateParameterPrefix
  value: ''
- key: readability-identifier-naming.TypeAliasPrefix
  value: ''
- key: readability-identifier-naming.MacroDefinitionPrefix
  value: ''
- key: readability-identifier-naming.ObjcIvarPrefix
  value: ''
- key: readability-identifier-naming.NamespaceSuffix
  value: ''
- key: readability-identifier-naming.InlineNamespaceSuffix
  value: ''
- key: readability-identifier-naming.EnumConstantSuffix
  value: ''
- key: readability-identifier-naming.ConstexprVariableSuffix
  value: ''
- key: readability-identifier-naming.ConstantMemberSuffix
  value: ''
- key: readability-identifier-naming.PrivateMemberSuffix
  value: ''
- key: readability-identifier-naming.ProtectedMemberSuffix
  value: ''
- key: readability-identifier-naming.PublicMemberSuffix
  value: ''
- key: readability-identifier-naming.MemberSuffix
  value: ''
- key: readability-identifier-naming.ClassConstantSuffix
  value: ''
- key: readability-identifier-naming.ClassMemberSuffix
  value: ''
- key: readability-identifier-naming.GlobalConstantSuffix
  value: ''
- key: readability-identifier-naming.GlobalConstantPointerSuffix
  value: ''
- key: readability-identifier-naming.GlobalPointerSuffix
  value: ''
- key: readability-identifier-naming.GlobalVariableSuffix
  value: ''
- key: readability-identifier-naming.LocalConstantSuffix
  value: ''
- key: readability-identifier-naming.LocalConstantPointerSuffix
  value: ''
- key: readability-identifier-naming.LocalPointerSuffix
  value: ''
- key: readability-identifier-naming.LocalVariableSuffix
  value: ''
- key: readability-identifier-naming.StaticConstantSuffix
  value: ''
- key: readability-identifier-naming.StaticVariableSuffix
  value: ''
- key: readability-identifier-naming.ConstantSuffix
  value: ''
- key: readability-identifier-naming.VariableSuffix
  value: ''
- key: readability-identifier-naming.ConstantParameterSuffix
  value: ''
- key: readability-identifier-naming.ParameterPackSuffix
  value: ''
- key: readability-identifier-naming.ParameterSuffix
  value: ''
- key: readability-identifier-naming.PointerParameterSuffix
  value: ''
- key: readability-identifier-naming.ConstantPointerParameterSuffix
  value: ''
- key: readability-identifier-naming.AbstractClassSuffix
  value: ''
- key: readability-identifier-naming.StructSuffix
  value: ''
- key: readability-identifier-naming.ClassSuffix
  value: ''
- key: readability-identifier-naming.UnionSuffix
  value: ''
- key: readability-identifier-naming.EnumSuffix
  value: ''
- key: readability-identifier-naming.GlobalFunctionSuffix
  value: ''
- key: readability-identifier-naming.ConstexprFunctionSuffix
  value: ''
- key: readability-identifier-naming.FunctionSuffix
  value: ''
- key: readability-identifier-naming.ConstexprMethodSuffix
  value: ''
- key: readability-identifier-naming.VirtualMethodSuffix
  value: ''
- key: readability-identifier-naming.ClassMethodSuffix
  value: ''
- key: readability-identifier-naming.PrivateMethodSuffix
  value: ''
- key: readability-identifier-naming.ProtectedMethodSuffix
  value: ''
- key: readability-identifier-naming.PublicMethodSuffix
  value: ''
- key: readability-identifier-naming.MethodSuffix
  value: ''
- key: readability-identifier-naming.TypedefSuffix
  value: ''
- key: readability-identifier-naming.TypeTemplateParameterSuffix
  value: ''
- key: readability-identifier-naming.ValueTemplateParameterSuffix
  value: ''
- key: readability-identifier-naming.TemplateTemplateParameterSuffix
  value: ''
- key: readability-identifier-naming.TemplateParameterSuffix
  value: ''
- key: readability-identifier-naming.TypeAliasSuffix
  value: ''
- key: readability-identifier-naming.MacroDefinitionSuffix
  value: ''
- key: readability-identifier-naming.ObjcIvarSuffix
  value: ''
- key: readability-identifier-naming.FunctionIgnoredRegexp
  value: LLVMFuzzerTestOneInput

Unable to sort a multi document yaml file

This feature use to work on previous versions however it seems to be broken now.

VSCode error -> YAML is invalid: expected a single document in the stream, but found more

Plugin Version: v2.7.1 (rolling back to v2.6.0 worked fine)
Example yaml:

example.yml.txt

Add possibility to add specific custom sorts to file association

I have FluxCD project which incorporates a lot of YAML files which require a lot more than three custom sort sets to properly manage. It would be awesome to add some pre-defined and/or array of custom sorts and specifically reference them via file name.

Example, the .pre-commit.yaml gets butchered, from:

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.0.1
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
        args: [--allow-multiple-documents, --unsafe]
      - id: check-added-large-files

to:

repos:
  - hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - args:
          - '--allow-multiple-documents'
          - '--unsafe'
        id: check-yaml
      - id: check-added-large-files
    repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.0.1

But the repositoy also contains kustomization-files, K8S-files, Home Assistant-files, and some others. They all carry their own best practices in terms of readable sorting.

Sort using localeCompare

The sorting at the moment doesn't sort how you would normally expect strings to be sorted, e.g. in my YAML file I have completedDate and completeTask however, completeTask is sorted first because the T appears to come first compared to the d. This isn't how people would normally expect these to be sorted.

I think updating the sorting to return a.localeCompare(b, locale) would result in a more human expected sorting order. It would be great if this could be the default, although I expect that would break a number of existing files, so perhaps it would be possible to have this as a configuration option along with the locale to use for the sorting (possibly defaulting to 'en' since I expect that would be the largest part of the userbase).

Add 'newLine' at end of file option

Some coding conventions say that a newline must always be present at the end of a file. Sorting a YAML-file now removes any newlines, including the one at the end. Can it be made optional to add it?

Sort happens only once in editor life

Hi.
I just installed vscode because of your extension.
Press yaml sort and vualya i got sorted kubenetes manifest. Then i open next file and try to make the trick again.
Editor say Keys resorted successfully but really nothing happens.
I close vscode and open it again.
This help for another file :)

Can you please an option to restart vscode after successfull sort automaticaly?
Is there anything wrong in my install ?

Version: 1.35.0
Commit: 553cfb2c2205db5f15f3ee8395bbd5cf066d357d
Date: 2019-06-04T01:13:26.790Z
Electron: 3.1.8
Chrome: 66.0.3359.181
Node.js: 10.2.0
V8: 6.6.346.32
OS: Linux x64 4.15.0-51-generic snap

yaml sort 1.0.0

publish to Open VSX

Please consider publishing to OpenVSX registry.

We are running Web version of VS Code in Gitpod. But only MS products like VS Code may use MS VS Code extensions Marketplace. So we have to use Open VSX instead. It is a vendor neutral alternative. Also products like VSCodium, Theia, code-server and so on are using OpenVSX registry.

Docs are here: https://github.com/eclipse/openvsx/wiki/Publishing-Extensions Technically it should be straightforward. You are basically have to get a token and call ovsx publish with it, for instance how RedHat is publishing the java extension: https://github.com/redhat-developer/vscode-java/blob/ff51dbffc30dd23190335c929e9f34ccdf511554/Jenkinsfile#L73-L82

No need to send notification when used as a formatter

I found the extension will notify when sort, validate, and format.

As other language's default formatters, when something is done successfully, there is no notification except bad things happened.

This is make sense for such a tool.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.