This commit is contained in:
2026-09-13 13:30:21 +08:00
commit a6bbd520cf
2744 changed files with 1598795 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
add_executable(yaml-cpp-sandbox sandbox.cpp)
add_executable(yaml-cpp-parse parse.cpp)
add_executable(yaml-cpp-read read.cpp)
target_link_libraries(yaml-cpp-sandbox PRIVATE yaml-cpp)
target_link_libraries(yaml-cpp-parse PRIVATE yaml-cpp)
target_link_libraries(yaml-cpp-read PRIVATE yaml-cpp)
set_property(TARGET yaml-cpp-sandbox PROPERTY OUTPUT_NAME sandbox)
set_property(TARGET yaml-cpp-parse PROPERTY OUTPUT_NAME parse)
set_property(TARGET yaml-cpp-read PROPERTY OUTPUT_NAME read)
set_target_properties(yaml-cpp-sandbox
PROPERTIES
CXX_STANDARD_REQUIRED ON
OUTPUT_NAME sandbox)
set_target_properties(yaml-cpp-parse
PROPERTIES
CXX_STANDARD_REQUIRED ON
OUTPUT_NAME parse)
set_target_properties(yaml-cpp-read
PROPERTIES
CXX_STANDARD_REQUIRED ON
OUTPUT_NAME read)
if (NOT DEFINED CMAKE_CXX_STANDARD)
set_target_properties(yaml-cpp-sandbox yaml-cpp-parse yaml-cpp-read
PROPERTIES
CXX_STANDARD 11)
endif()
+137
View File
@@ -0,0 +1,137 @@
// a sketch of what the new API might look like
#include "yaml-cpp/yaml.h"
#include <iostream>
int main() {
{
// test.yaml
// - foo
// - primes: [2, 3, 5, 7, 11]
// odds: [1, 3, 5, 7, 9, 11]
// - [x, y]
// move-like semantics
YAML::Value root = YAML::Parse("test.yaml");
std::cout << root[0].as<std::string>(); // "foo"
std::cout << str(root[0]); // "foo", shorthand?
std::cout << root[1]["primes"][3].as<int>(); // "7"
std::cout << root[1]["odds"][6].as<int>(); // throws?
root[2].push_back(5);
root[3] = "Hello, World";
root[0].reset();
root[0]["key"] = "value";
std::cout << root;
// # not sure about formatting
// - {key: value}
// - primes: [2, 3, 5, 7, 11]
// odds: [1, 3, 5, 7, 9, 11]
// - [x, y, 5]
// - Hello, World
}
{
// for all copy-like commands, think of python's "name/value" semantics
YAML::Value root = "Hello"; // Hello
root = YAML::Sequence(); // []
root[0] = 0; // [0]
root[2] = "two"; // [0, ~, two] # forces root[1] to be initialized to null
YAML::Value other = root; // both point to the same thing
other[0] = 5; // now root[0] is 5 also
other.push_back(root); // &1 [5, ~, two, *1]
other[3][0] = 0; // &1 [0, ~, two, *1] # since it's a true alias
other.push_back(Copy(root)); // &1 [0, ~, two, *1, &2 [0, ~, two, *2]]
other[4][0] = 5; // &1 [0, ~, two, *1, &2 [5, ~, two, *2]] # they're
// really different
}
{
YAML::Value node; // ~
node[0] = 1; // [1] # auto-construct a sequence
node["key"] = 5; // {0: 1, key: 5} # auto-turn it into a map
node.push_back(10); // error, can't turn a map into a sequence
node.erase("key"); // {0: 1} # still a map, even if we remove the key that
// caused the problem
node = "Hello"; // Hello # assignment overwrites everything, so it's now
// just a plain scalar
}
{
YAML::Value map; // ~
map[3] = 1; // {3: 1} # auto-constructs a map, *not* a sequence
YAML::Value seq; // ~
seq = YAML::Sequence(); // []
seq[3] = 1; // [~, ~, ~, 1]
}
{
YAML::Value node; // ~
node[0] = node; // &1 [*1] # fun stuff
}
{
YAML::Value node;
YAML::Value subnode =
node["key"]; // 'subnode' is not instantiated ('node' is still null)
subnode = "value"; // {key: value} # now it is
YAML::Value subnode2 = node["key2"];
node["key3"] = subnode2; // subnode2 is still not instantiated, but
// node["key3"] is "pseudo" aliased to it
subnode2 = "monkey"; // {key: value, key2: &1 monkey, key3: *1} # bam! it
// instantiates both
}
{
YAML::Value seq = YAML::Sequence();
seq[0] = "zero"; // [zero]
seq[1] = seq[0]; // [&1 zero, *1]
seq[0] = seq[1]; // [&1 zero, *1] # no-op (they both alias the same thing,
// so setting them equal is nothing)
Is(seq[0], seq[1]); // true
seq[1] = "one"; // [&1 one, *1]
UnAlias(seq[1]); // [one, one]
Is(seq[0], seq[1]); // false
}
{
YAML::Value root;
root.push_back("zero");
root.push_back("one");
root.push_back("two");
YAML::Value two = root[2];
root = "scalar"; // 'two' is still "two", even though 'root' is "scalar"
// (the sequence effectively no longer exists)
// Note: in all likelihood, the memory for nodes "zero" and "one" is still
// allocated. How can it go away? Weak pointers?
}
{
YAML::Value root; // ~
root[0] = root; // &1 [*1]
root[0] = 5; // [5]
}
{
YAML::Value root;
YAML::Value key;
key["key"] = "value";
root[key] = key; // &1 {key: value}: *1
}
{
YAML::Value root;
root[0] = "hi";
root[1][0] = "bye";
root[1][1] = root; // &1 [hi, [bye, *1]] # root
YAML::Value sub = root[1]; // &1 [bye, [hi, *1]] # sub
root = "gone"; // [bye, gone] # sub
}
return 0;
}
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""Check LF whitespace invariants for maintained, tracked text files."""
from __future__ import annotations
import argparse
import logging
import re
import subprocess
from dataclasses import dataclass
from pathlib import Path
LOGGER = logging.getLogger(__name__)
EXCLUDED_PREFIXES = ("test/googletest-1.16.0/",)
TRAILING_WHITESPACE = re.compile(rb"[ \t]+(?=\r?\n|\r|$)")
@dataclass(frozen=True)
class Violation:
path: str
line: int | str
message: str
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Check whitespace in tracked maintained text files."
)
parser.add_argument(
"--root",
type=Path,
help="repository root (defaults to the root containing this script)",
)
return parser.parse_args()
def repository_root(argument: Path | None) -> Path:
if argument is not None:
return argument.resolve()
return Path(__file__).resolve().parents[1]
def tracked_paths(root: Path) -> tuple[str, ...]:
result = subprocess.run(
("git", "-C", root, "ls-files", "-z"),
check=True,
stdout=subprocess.PIPE,
)
return tuple(
path.decode("utf-8")
for path in result.stdout.split(b"\0")
if path
)
def is_excluded(path: str) -> bool:
return any(
path == prefix.rstrip("/") or path.startswith(prefix)
for prefix in EXCLUDED_PREFIXES
)
def is_binary(content: bytes) -> bool:
return b"\0" in content
def line_number(content: bytes, position: int) -> int:
return content.count(b"\n", 0, position) + 1
def check_content(path: str, content: bytes) -> tuple[Violation, ...]:
violations: list[Violation] = []
for match in TRAILING_WHITESPACE.finditer(content):
violations.append(
Violation(
path,
line_number(content, match.start()),
"trailing whitespace",
)
)
if b"\r" in content:
violations.append(
Violation(
path,
"EOL",
"carriage return found; use LF line endings",
)
)
if content:
if not content.endswith(b"\n"):
violations.append(Violation(path, "EOF", "missing final newline"))
elif content[:-1].endswith(b"\n"):
violations.append(
Violation(path, "EOF", "multiple final newlines")
)
return tuple(violations)
def check_file(root: Path, path: str) -> tuple[Violation, ...]:
if is_excluded(path):
return ()
file_path = root / path
if not file_path.is_file():
return ()
content = file_path.read_bytes()
if is_binary(content):
return ()
return check_content(path, content)
def main() -> int:
arguments = parse_arguments()
root = repository_root(arguments.root)
violations: list[Violation] = []
try:
paths = tracked_paths(root)
except (OSError, subprocess.CalledProcessError) as error:
LOGGER.error("unable to list tracked files in %s: %s", root, error)
return 2
for path in paths:
violations.extend(check_file(root, path))
for violation in violations:
LOGGER.error(
"%s:%s: %s",
violation.path,
violation.line,
violation.message,
)
if violations:
LOGGER.error("%d whitespace violation(s) found", len(violations))
return 1
LOGGER.info("Whitespace check passed")
return 0
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
raise SystemExit(main())
+46
View File
@@ -0,0 +1,46 @@
#include <fstream>
#include <iostream>
#include <vector>
#include "yaml-cpp/eventhandler.h"
#include "yaml-cpp/yaml.h" // IWYU pragma: keep
class NullEventHandler : public YAML::EventHandler {
public:
void OnDocumentStart(const YAML::Mark&) override {}
void OnDocumentEnd() override {}
void OnNull(const YAML::Mark&, YAML::anchor_t) override {}
void OnAlias(const YAML::Mark&, YAML::anchor_t) override {}
void OnScalar(const YAML::Mark&, const std::string&, YAML::anchor_t,
const std::string&) override {}
void OnSequenceStart(const YAML::Mark&, const std::string&, YAML::anchor_t,
YAML::EmitterStyle::value) override {}
void OnSequenceEnd() override {}
void OnMapStart(const YAML::Mark&, const std::string&, YAML::anchor_t,
YAML::EmitterStyle::value) override {}
void OnMapEnd() override {}
};
void parse(std::istream& input) {
try {
YAML::Node doc = YAML::Load(input);
std::cout << doc << "\n";
} catch (const YAML::Exception& e) {
std::cerr << e.what() << "\n";
}
}
int main(int argc, char** argv) {
if (argc > 1) {
std::ifstream fin;
fin.open(argv[1]);
parse(fin);
} else {
parse(std::cin);
}
return 0;
}
+103
View File
@@ -0,0 +1,103 @@
#include "yaml-cpp/emitterstyle.h"
#include "yaml-cpp/eventhandler.h"
#include "yaml-cpp/yaml.h" // IWYU pragma: keep
#include <cstdlib>
#include <fstream>
#include <iostream>
class NullEventHandler : public YAML::EventHandler {
public:
using Mark = YAML::Mark;
using anchor_t = YAML::anchor_t;
NullEventHandler() = default;
void OnDocumentStart(const Mark&) override {}
void OnDocumentEnd() override {}
void OnNull(const Mark&, anchor_t) override {}
void OnAlias(const Mark&, anchor_t) override {}
void OnScalar(const Mark&, const std::string&, anchor_t,
const std::string&) override {}
void OnSequenceStart(const Mark&, const std::string&, anchor_t,
YAML::EmitterStyle::value) override {}
void OnSequenceEnd() override {}
void OnMapStart(const Mark&, const std::string&, anchor_t,
YAML::EmitterStyle::value) override {}
void OnMapEnd() override {}
};
void run(std::istream& in) {
YAML::Parser parser(in);
NullEventHandler handler;
parser.HandleNextDocument(handler);
}
void usage() { std::cerr << "Usage: read [-n N] [-c, --cache] [filename]\n"; }
std::string read_stream(std::istream& in) {
return std::string((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
}
int main(int argc, char** argv) {
int N = 1;
bool cache = false;
std::string filename;
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg == "-n") {
i++;
if (i >= argc) {
usage();
return -1;
}
N = std::atoi(argv[i]);
if (N <= 0) {
usage();
return -1;
}
} else if (arg == "-c" || arg == "--cache") {
cache = true;
} else {
filename = argv[i];
if (i + 1 != argc) {
usage();
return -1;
}
}
}
if (N > 1 && !cache && filename.empty()) {
usage();
return -1;
}
if (cache) {
std::string input;
if (!filename.empty()) {
std::ifstream in(filename);
input = read_stream(in);
} else {
input = read_stream(std::cin);
}
std::istringstream in(input);
for (int i = 0; i < N; i++) {
in.seekg(std::ios_base::beg);
run(in);
}
} else {
if (!filename.empty()) {
std::ifstream in(filename);
for (int i = 0; i < N; i++) {
in.seekg(std::ios_base::beg);
run(in);
}
} else {
for (int i = 0; i < N; i++) {
run(std::cin);
}
}
}
return 0;
}
+36
View File
@@ -0,0 +1,36 @@
#include <iostream>
#include "yaml-cpp/emitterstyle.h"
#include "yaml-cpp/eventhandler.h"
#include "yaml-cpp/yaml.h" // IWYU pragma: keep
class NullEventHandler : public YAML::EventHandler {
public:
using Mark = YAML::Mark;
using anchor_t = YAML::anchor_t;
NullEventHandler() = default;
void OnDocumentStart(const Mark&) override {}
void OnDocumentEnd() override {}
void OnNull(const Mark&, anchor_t) override {}
void OnAlias(const Mark&, anchor_t) override {}
void OnScalar(const Mark&, const std::string&, anchor_t,
const std::string&) override {}
void OnSequenceStart(const Mark&, const std::string&, anchor_t,
YAML::EmitterStyle::value) override {}
void OnSequenceEnd() override {}
void OnMapStart(const Mark&, const std::string&, anchor_t,
YAML::EmitterStyle::value) override {}
void OnMapEnd() override {}
};
int main() {
YAML::Node root;
for (;;) {
YAML::Node node;
root = node;
}
return 0;
}