동일한 YAML 파일의 다른 위치에서 YAML "설정"을 참조하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/2063616

  •  20-09-2019
  •  | 
  •  

문제

다음 YAML이 있습니다.

paths:
  patha: /path/to/root/a
  pathb: /path/to/root/b
  pathc: /path/to/root/c

제거하여 어떻게 이를 "정규화"할 수 있습니까? /path/to/root/ 세 가지 경로에서 다음과 같이 자체 설정으로 지정합니다.

paths:
  root: /path/to/root/
  patha: *root* + a
  pathb: *root* + b
  pathc: *root* + c

분명히 그것은 유효하지 않습니다. 방금 만들어 낸 것입니다.실제 구문은 무엇입니까?할 수 있나요?

도움이 되었습니까?

해결책

나는 그것이 가능하지 않다고 생각합니다. "노드"를 재사용 할 수는 있지만 그 일부는 아닙니다.

bill-to: &id001
    given  : Chris
    family : Dumars
ship-to: *id001

이것은 완벽하게 유효한 YAML과 필드입니다 given 그리고 family 재사용됩니다 ship-to 차단하다. 같은 방식으로 스칼라 노드를 재사용 할 수 있지만 내부의 것을 변경하고 Yaml 내부에서 경로의 마지막 부분을 추가 할 수있는 방법은 없습니다.

반복이 당신을 너무 귀찮게한다면 당신의 신청서를 알리기 위해 제안합니다. root 속성과 상대적으로 보이지 않는 모든 경로에 추가하십시오.

다른 팁

예, 사용자 정의 태그를 사용합니다. Python의 예제, 만들기 !join 배열에서 문자열 조인 태그 :

import yaml

## define custom tag handler
def join(loader, node):
    seq = loader.construct_sequence(node)
    return ''.join([str(i) for i in seq])

## register the tag handler
yaml.add_constructor('!join', join)

## using your sample data
yaml.load("""
paths:
    root: &BASE /path/to/root/
    patha: !join [*BASE, a]
    pathb: !join [*BASE, b]
    pathc: !join [*BASE, c]
""")

결과 :

{
    'paths': {
        'patha': '/path/to/root/a',
        'pathb': '/path/to/root/b',
        'pathc': '/path/to/root/c',
        'root': '/path/to/root/'
     }
}

논쟁의 배열 !join 문자열로 변환 할 수있는 한 데이터 유형의 여러 요소를 가질 수 있습니다. !join [*a, "/", *b, "/", *c] 당신이 기대할 수있는 일을합니다.

이것을 보는 또 다른 방법은 단순히 다른 필드를 사용하는 것입니다.

paths:
  root_path: &root
     val: /path/to/root/
  patha: &a
    root_path: *root
    rel_path: a
  pathb: &b
    root_path: *root
    rel_path: b
  pathc: &c
    root_path: *root
    rel_path: c

YML 정의 :

dir:
  default: /home/data/in/
  proj1: ${dir.default}p1
  proj2: ${dir.default}p2
  proj3: ${dir.default}p3 

Thymeleaf 어딘가

<p th:utext='${@environment.getProperty("dir.default")}' />
<p th:utext='${@environment.getProperty("dir.proj1")}' /> 

산출:/home/data/in//home/data/in/p1

일부 언어에서는 대체 라이브러리를 사용할 수 있습니다. TAMPAX YAML 처리 변수의 구현입니다.

const tampax = require('tampax');

const yamlString = `
dude:
  name: Arthur
weapon:
  favorite: Excalibur
  useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;

const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);

// output : "Arthur use Excalibur. The goal is to kill Mordred."

이 기능을 수행하는 Packagist에서 사용할 수있는 라이브러리를 만듭니다.https://packagist.org/packages/grasmash/yaml-expander

YAML 파일의 예 :

type: book
book:
  title: Dune
  author: Frank Herbert
  copyright: ${book.author} 1965
  protaganist: ${characters.0.name}
  media:
    - hardcover
characters:
  - name: Paul Atreides
    occupation: Kwisatz Haderach
    aliases:
      - Usul
      - Muad'Dib
      - The Preacher
  - name: Duncan Idaho
    occupation: Swordmaster
summary: ${book.title} by ${book.author}
product-name: ${${type}.title}

예제 논리 :

// Parse a yaml string directly, expanding internal property references.
$yaml_string = file_get_contents("dune.yml");
$expanded = \Grasmash\YamlExpander\Expander::parse($yaml_string);
print_r($expanded);

결과 배열 :

array (
  'type' => 'book',
  'book' => 
  array (
    'title' => 'Dune',
    'author' => 'Frank Herbert',
    'copyright' => 'Frank Herbert 1965',
    'protaganist' => 'Paul Atreides',
    'media' => 
    array (
      0 => 'hardcover',
    ),
  ),
  'characters' => 
  array (
    0 => 
    array (
      'name' => 'Paul Atreides',
      'occupation' => 'Kwisatz Haderach',
      'aliases' => 
      array (
        0 => 'Usul',
        1 => 'Muad\'Dib',
        2 => 'The Preacher',
      ),
    ),
    1 => 
    array (
      'name' => 'Duncan Idaho',
      'occupation' => 'Swordmaster',
    ),
  ),
  'summary' => 'Dune by Frank Herbert',
);

당신의 예는 유효하지 않다는 것입니다 스칼라를 시작하기 위해 예약 된 캐릭터를 선택했기 때문입니다. 당신이 교체하는 경우 * 다른 비율이없는 캐릭터와 함께 (일부 사양의 일부로 사용되지 않으므로 ASCII가 아닌 문자를 사용하는 경향이 있습니다), 당신은 완벽하게 합법적 인 Yaml로 끝납니다.

paths:
  root: /path/to/root/
  patha: ♦root♦ + a
  pathb: ♦root♦ + b
  pathc: ♦root♦ + c

이것은 파서가 사용하는 언어의 매핑에 대한 표준 표현으로로드되며 마술처럼 확장되지 않습니다.
이를 위해 다음 파이썬 프로그램에서와 같이 로컬 기본 객체 유형을 사용하십시오.

# coding: utf-8

from __future__ import print_function

import ruamel.yaml as yaml

class Paths:
    def __init__(self):
        self.d = {}

    def __repr__(self):
        return repr(self.d).replace('ordereddict', 'Paths')

    @staticmethod
    def __yaml_in__(loader, data):
        result = Paths()
        loader.construct_mapping(data, result.d)
        return result

    @staticmethod
    def __yaml_out__(dumper, self):
        return dumper.represent_mapping('!Paths', self.d)

    def __getitem__(self, key):
        res = self.d[key]
        return self.expand(res)

    def expand(self, res):
        try:
            before, rest = res.split(u'♦', 1)
            kw, rest = rest.split(u'♦ +', 1)
            rest = rest.lstrip() # strip any spaces after "+"
            # the lookup will throw the correct keyerror if kw is not found
            # recursive call expand() on the tail if there are multiple
            # parts to replace
            return before + self.d[kw] + self.expand(rest)
        except ValueError:
            return res

yaml_str = """\
paths: !Paths
  root: /path/to/root/
  patha: ♦root♦ + a
  pathb: ♦root♦ + b
  pathc: ♦root♦ + c
"""

loader = yaml.RoundTripLoader
loader.add_constructor('!Paths', Paths.__yaml_in__)

paths = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)['paths']

for k in ['root', 'pathc']:
    print(u'{} -> {}'.format(k, paths[k]))

인쇄 할 것 :

root -> /path/to/root/
pathc -> /path/to/root/c

확장은 즉석에서 이루어지고 중첩 된 정의를 처리하지만 무한 재귀를 호출하지 않도록주의해야합니다.

Dumper를 지정하면 비행 비행 확장으로 인해로드 된 데이터에서 원래 Yaml을 버릴 수 있습니다.

dumper = yaml.RoundTripDumper
dumper.add_representer(Paths, Paths.__yaml_out__)
print(yaml.dump(paths, Dumper=dumper, allow_unicode=True))

매핑 키 순서가 변경됩니다. 그것이 문제라면 당신은해야합니다 self.dCommentedMap (수입 ruamel.yaml.comments.py)

저는 다음과 같은 계층 구조를 가진 디렉터리에서 로드되는 변수를 확장하기 위해 Python에 자체 라이브러리를 작성했습니다.

/root
 |
 +- /proj1
     |
     +- config.yaml
     |
     +- /proj2
         |
         +- config.yaml
         |
         ... and so on ...

여기서 중요한 차이점은 확장은 모든 작업이 끝난 후에만 적용되어야 한다는 것입니다. config.yaml 파일이 로드되고 다음 파일의 변수가 이전 파일의 변수를 재정의할 수 있으므로 의사코드는 다음과 같아야 합니다.

env = YamlEnv()
env.load('/root/proj1/config.yaml')
env.load('/root/proj1/proj2/config.yaml')
...
env.expand()

추가 옵션으로는 xonsh 스크립트는 결과 변수를 환경 변수로 내보낼 수 있습니다(참조: yaml_update_global_vars 기능).

스크립트:

https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/cmdoplib.yaml.py https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/cmdoplib.yaml.xsh

장점:

  • 단순하며 재귀 및 중첩 변수를 지원하지 않습니다.
  • 정의되지 않은 변수를 자리 표시자로 바꿀 수 있습니다(${MYUNDEFINEDVAR} -> *$/{MYUNDEFINEDVAR})
  • 환경 변수에서 참조를 확장할 수 있습니다(${env:MYVAR})
  • 모두 대체할 수 있다 \\ 에게 / 경로 변수(${env:MYVAR:path})

단점:

  • 중첩된 변수를 지원하지 않으므로 중첩된 사전의 값을 확장할 수 없습니다(예: ${MYSCOPE.MYVAR} 구현되지 않음)
  • 자리 표시자를 넣은 후의 재귀를 포함하여 확장 재귀를 감지하지 않습니다.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top