| 1 | <?php |
| 2 | /************************************************************* |
| 3 | # 076 License |
| 4 | |
| 5 | Copyright (c) テクニカル諏訪子 |
| 6 | |
| 7 | Permission is hereby granted to any person obtaining a copy of the software |
| 8 | Little Beast (the "Software") to use, modify, merge, copy, publish, distribute, |
| 9 | sublicense, and/or sell copies of the Software, subject to the following conditions: |
| 10 | |
| 11 | 1. **Origin Attribution**: |
| 12 | - You must not misrepresent the origin of the Software; you must not claim |
| 13 | you created the original Software. |
| 14 | - If the Software is used in a product, you must either: |
| 15 | a. Provide clear attribution in the product's documentation, user interface, |
| 16 | or other visible areas, **OR** |
| 17 | b. Pay the original developers a fee they specify in writing. |
| 18 | 2. **Usage Restriction**: |
| 19 | - The Software, or any derivative works, dependencies, or libraries |
| 20 | incorporating it, must not be used for censorship or to suppress freedom of |
| 21 | speech, expression, or creativity. Prohibited uses include, but are not |
| 22 | limited to: |
| 23 | - Censorship of so-called "hate speech", visuals, non-mainstream opinions, |
| 24 | ideas, or objective reality. |
| 25 | - Tools or systems designed to restrict access to information or |
| 26 | artistic works. |
| 27 | 3. **Notice Preservation**: |
| 28 | - This license and the above copyright notice must remain intact in all copies |
| 29 | of the source code. |
| 30 | |
| 31 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, |
| 32 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A |
| 33 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT |
| 34 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 35 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE |
| 36 | OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 37 | */ |
| 38 | namespace Std\Lib\Git; |
| 39 | |
| 40 | /** |
| 41 | * Gitの設定ファイル(config) |
| 42 | * |
| 43 | * 「[section]」「[section "subsection"]」と「key = value」。名前はsection.subsection.key |
| 44 | * (sectionとkeyは小文字、subsectionは大文字・小文字を区別する)。書く時はコメントを残さない。 |
| 45 | */ |
| 46 | final class Config { |
| 47 | /** @var array 名前 => 値の配列(同じ名前が複数有り得る) */ |
| 48 | private array $values = []; |
| 49 | |
| 50 | public function __construct(private ?string $file = null) { |
| 51 | if ($file !== null && is_file($file)) $this->parse((string)file_get_contents($file)); |
| 52 | } |
| 53 | |
| 54 | public static function fromString(string $text): self { |
| 55 | $c = new self(); |
| 56 | $c->parse($text); |
| 57 | return $c; |
| 58 | } |
| 59 | |
| 60 | private function parse(string $text): void { |
| 61 | $section = ''; |
| 62 | $lines = preg_split('/\r?\n/', $text); |
| 63 | for ($i = 0; $i < count($lines); $i++) { |
| 64 | $line = $lines[$i]; |
| 65 | $t = ltrim($line); |
| 66 | if ($t === '' || $t[0] === '#' || $t[0] === ';') continue; |
| 67 | if ($t[0] === '[') { |
| 68 | if (!preg_match('/^\[\s*([A-Za-z0-9.-]+)(?:\s+"((?:[^"\\\\]|\\\\.)*)")?\s*\](.*)$/', $t, $m)) throw new GitException("不正な設定の行:{$line}"); |
| 69 | $section = strtolower($m[1]); |
| 70 | if (isset($m[2]) && $m[2] !== '') $section .= '.'.preg_replace('/\\\\(.)/', '$1', $m[2]); |
| 71 | $t = ltrim($m[3]); |
| 72 | if ($t === '' || $t[0] === '#' || $t[0] === ';') continue; |
| 73 | } |
| 74 | if (!preg_match('/^([A-Za-z][A-Za-z0-9-]*)\s*(=\s*(.*))?$/s', $t, $m)) throw new GitException("不正な設定の行:{$line}"); |
| 75 | $key = $section.'.'.strtolower($m[1]); |
| 76 | if (!isset($m[2]) || $m[2] === '') { |
| 77 | $this->values[$key][] = 'true'; |
| 78 | continue; |
| 79 | } |
| 80 | $raw = $m[3]; |
| 81 | // 行の最後の「\」で次の行に続く |
| 82 | while (preg_match('/(?<!\\\\)(\\\\\\\\)*\\\\$/', $raw) && $i + 1 < count($lines)) $raw = substr($raw, 0, -1).$lines[++$i]; |
| 83 | $this->values[$key][] = self::unquote($raw); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | private static function unquote(string $raw): string { |
| 88 | $out = ''; |
| 89 | $quoted = false; |
| 90 | $len = strlen($raw); |
| 91 | $pendingSpace = ''; |
| 92 | for ($i = 0; $i < $len; $i++) { |
| 93 | $c = $raw[$i]; |
| 94 | if (!$quoted && ($c === '#' || $c === ';')) break; |
| 95 | if ($c === '"') { |
| 96 | $quoted = !$quoted; |
| 97 | continue; |
| 98 | } |
| 99 | if ($c === '\\' && $i + 1 < $len) { |
| 100 | $n = $raw[++$i]; |
| 101 | $out .= $pendingSpace.match ($n) { 'n' => "\n", 't' => "\t", 'b' => "\x08", default => $n }; |
| 102 | $pendingSpace = ''; |
| 103 | continue; |
| 104 | } |
| 105 | if (!$quoted && ($c === ' ' || $c === "\t")) { |
| 106 | // 引用符の外の空白は1つにまとめ、最後の空白は消す |
| 107 | if ($out !== '' || $pendingSpace !== '') $pendingSpace = ' '; |
| 108 | continue; |
| 109 | } |
| 110 | $out .= $pendingSpace.$c; |
| 111 | $pendingSpace = ''; |
| 112 | } |
| 113 | return $out; |
| 114 | } |
| 115 | |
| 116 | /** 最後の値 */ |
| 117 | public function get(string $name, ?string $default = null): ?string { |
| 118 | $k = $this->key($name); |
| 119 | return isset($this->values[$k]) ? end($this->values[$k]) : $default; |
| 120 | } |
| 121 | |
| 122 | /** 全部の値 */ |
| 123 | public function getAll(string $name): array { |
| 124 | return $this->values[$this->key($name)] ?? []; |
| 125 | } |
| 126 | |
| 127 | public function getBool(string $name, bool $default = false): bool { |
| 128 | $v = $this->get($name); |
| 129 | if ($v === null) return $default; |
| 130 | return in_array(strtolower($v), ['true', 'yes', 'on', '1'], true); |
| 131 | } |
| 132 | |
| 133 | public function getInt(string $name, int $default = 0): int { |
| 134 | $v = $this->get($name); |
| 135 | if ($v === null || !preg_match('/^(-?\d+)([kmg]?)$/i', trim($v), $m)) return $default; |
| 136 | return (int)$m[1] * match (strtolower($m[2])) { 'k' => 1024, 'm' => 1048576, 'g' => 1073741824, default => 1 }; |
| 137 | } |
| 138 | |
| 139 | public function set(string $name, ?string $value): void { |
| 140 | $k = $this->key($name); |
| 141 | if ($value === null) unset($this->values[$k]); |
| 142 | else $this->values[$k] = [$value]; |
| 143 | } |
| 144 | |
| 145 | /** 全部(名前 => 最後の値) */ |
| 146 | public function all(): array { |
| 147 | return array_map(fn($v) => end($v), $this->values); |
| 148 | } |
| 149 | |
| 150 | public function toString(): string { |
| 151 | $sections = []; |
| 152 | foreach ($this->values as $k => $vals) { |
| 153 | $p = strrpos($k, '.'); |
| 154 | $sections[substr($k, 0, $p)][substr($k, $p + 1)] = $vals; |
| 155 | } |
| 156 | $out = ''; |
| 157 | foreach ($sections as $sec => $keys) { |
| 158 | $dot = strpos($sec, '.'); |
| 159 | $out .= $dot === false ? "[{$sec}]\n" : '['.substr($sec, 0, $dot).' "'.addcslashes(substr($sec, $dot + 1), '"\\')."\"]\n"; |
| 160 | foreach ($keys as $key => $vals) { |
| 161 | foreach ($vals as $v) { |
| 162 | $q = preg_match('/^\s|\s$|[#;"\\\\\n\t]/', $v) ? '"'.str_replace(['\\', '"', "\n", "\t"], ['\\\\', '\\"', '\\n', '\\t'], $v).'"' : $v; |
| 163 | $out .= "\t{$key} = {$q}\n"; |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | return $out; |
| 168 | } |
| 169 | |
| 170 | public function save(?string $file = null): void { |
| 171 | $file ??= $this->file; |
| 172 | if ($file === null) throw new GitException('設定ファイルが有りません。'); |
| 173 | $tmp = $file.'.lock'; |
| 174 | if (@file_put_contents($tmp, $this->toString()) === false || !@rename($tmp, $file)) { |
| 175 | @unlink($tmp); |
| 176 | throw new GitException("設定ファイルに書けません:{$file}"); |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | private function key(string $name): string { |
| 181 | $first = strpos($name, '.'); |
| 182 | $last = strrpos($name, '.'); |
| 183 | if ($first === false) throw new GitException("不正な設定の名前:{$name}"); |
| 184 | if ($first === $last) return strtolower($name); |
| 185 | return strtolower(substr($name, 0, $first)).substr($name, $first, $last - $first).'.'.strtolower(substr($name, $last + 1)); |
| 186 | } |
| 187 | } |