メインコンテンツへスキップ
見出し画像

OpenApiのYAMLを読み込んで、シミュレーターに自動設定させてみよう ③

    続きの始まり

    ようやく、RESTfulパラメータの対応が終わったので、読み込みを再開。前回のパーサーでは、配列定義のあたり " - url: https://api.example.com/v1"こんな感じの列が上手く読めなかったので、改修しました。

            public static Dictionary<string, string> ParseByIndent(string text)
            {
                var result = new Dictionary<string, string>();
                if (string.IsNullOrEmpty(text)) return result;
    
                var lines = new List<string>();
                using (var sr = new StringReader(text.Replace("\r\n", "\n")))
                {
                    string? l;
                    while ((l = sr.ReadLine()) != null) lines.Add(l);
                }
    
                int n = lines.Count;
                // find first non-empty line index
                int firstNonEmpty = -1;
                for (int i = 0; i < n; i++)
                {
                    if (!string.IsNullOrWhiteSpace(lines[i]))
                    {
                        firstNonEmpty = i;
                        break;
                    }
                }
                if (firstNonEmpty == -1) return result;
    
                var listItemRegex = new Regex(@"^(\s*)-\s*([^:]+):(?:\s*(.*))?$", RegexOptions.Compiled);
    
                for (int i = firstNonEmpty + 1; i < n; i++)
                {
                    var line = lines[i];
                    if (string.IsNullOrWhiteSpace(line)) continue;
    
                    var trimmedRight = line.TrimEnd();
    
                    // 1) リスト項目パターンの検出 (例: "  - url: https://..." または "  - url:")
                    var m = listItemRegex.Match(line);
                    if (m.Success)
                    {
                        int listIndent = m.Groups[1].Value.Length;
                        string rawKey = m.Groups[2].Value.Trim();
                        string key = rawKey;
                        string inlineValue = m.Groups[3].Success ? m.Groups[3].Value : null;
    
                        var blockLines = new List<string>();
    
                        // list 項目は「項目内の値」を先頭に入れる(inlineValue があればそれを、そのまま1行として)
                        if (!string.IsNullOrEmpty(inlineValue))
                        {
                            blockLines.Add(inlineValue);
                        }
                        else
                        {
                            // inlineValue がない場合は空行を追加せず、続行行を取りに行く
                        }
    
                        int j = i + 1;
                        for (; j < n; j++)
                        {
                            var nextLine = lines[j];
                            if (string.IsNullOrWhiteSpace(nextLine))
                            {
                                // 空行は値の一部として保持(元コードと同様)
                                blockLines.Add(string.Empty);
                                continue;
                            }
    
                            // 次行のインデント
                            int nextIndent = LeadingSpaces(nextLine);
    
                            // 次のリスト項目(同じ listIndent で先頭に '-' がある)に到達したらこの項目の終了
                            var nextMatch = listItemRegex.Match(nextLine);
                            if (nextMatch.Success && nextMatch.Groups[1].Value.Length == listIndent)
                            {
                                break;
                            }
    
                            // 次行が listIndent 以下なら、このリスト項目の値終了(YAML のリストの次要素または上位要素)
                            if (nextIndent <= listIndent)
                            {
                                break;
                            }
    
                            // 値行として取り込み。listIndent 分だけ左に詰めて正規化する
                            int remove = Math.Min(listIndent, nextLine.Length);
                            blockLines.Add(nextLine.Substring(remove));
                        }
    
                        // 値を連結(複数の url リスト項目がある場合は既存値に追記)
                        var sb = new StringBuilder();
                        foreach (var bl in blockLines) sb.AppendLine(bl);
                        var value = sb.ToString().TrimEnd('\r', '\n');
    
                        if (result.ContainsKey(key))
                        {
                            // 既に同キーがある場合は改行で結合(空でないなら区切り)
                            if (!string.IsNullOrEmpty(result[key]) && !string.IsNullOrEmpty(value))
                                result[key] = result[key] + "\n" + value;
                            else if (string.IsNullOrEmpty(result[key]))
                                result[key] = value;
                            // 両方空なら何もしない
                        }
                        else
                        {
                            result[key] = value;
                        }
    
                        i = j - 1;
                        continue;
                    }
    
                    // 2) 既存の「末尾が ':' の行をキーにする」処理(そのまま維持)
                    if (!trimmedRight.EndsWith(":")) continue;
    
                    int keyIndent = LeadingSpaces(line);
                    string rawKey2 = trimmedRight.Trim();
                    string key2 = rawKey2.EndsWith(":") ? rawKey2.Substring(0, rawKey2.Length - 1) : rawKey2;
    
                    var blockLines2 = new List<string>();
                    int removeForKey = Math.Min(keyIndent, line.Length);
                    blockLines2.Add(line.Substring(removeForKey));
    
                    int j2 = i + 1;
                    for (; j2 < n; j2++)
                    {
                        var nextLine = lines[j2];
                        if (string.IsNullOrWhiteSpace(nextLine))
                        {
                            blockLines2.Add(nextLine);
                            continue;
                        }
    
                        int nextIndent = LeadingSpaces(nextLine);
                        if (nextIndent <= keyIndent)
                        {
                            break;
                        }
    
                        int remove = Math.Min(keyIndent, nextLine.Length);
                        blockLines2.Add(nextLine.Substring(remove));
                    }
    
                    var sb2 = new StringBuilder();
                    foreach (var bl in blockLines2) sb2.AppendLine(bl);
                    var value2 = sb2.ToString().TrimEnd('\r', '\n');
    
                    result[key2] = value2;
    
                    i = j2 - 1;
                }
    
                return result;
            }
    

    めちゃくちゃ長くなった orz
    まあ、同じ関数で取れるから、良いでしょう。
    順当に読み込んで、APIのアクション名とRESTfulパラメータ、メソッドの取得が出来ました。あとはパラメータの初期値とかを読み取って設定していくだけ・・・先は長いなぁ。

    入出力の定義を構築

    components:というブロックがあって、そこに出入りのフォーマットが定義されています。
    つ~ことで、これを先にJsonに定義する部分を先に作っておこうかと♪
    $ref: '#/components/schemas/Pet
    読込側では、これで、実際のオブジェクトを定義してる先を決めてます。
    なので、"components" ブロックをExtractYamlBlock()メソッドで取り込んで、先ほどの改良版ParseByIndent()に放り込みます。
    すると、ディクショナリに、定義されている情報がオブジェクト毎に入ります。ラクチンだねぇ。
    まぁ、この後で自動解析部分を作らないといけないんだけどね。

    構築にトライ

    components:
      schemas:
        Payload:
          type: object
          properties:
            headers:
              type: object
              properties:
                id:
                  type: integer
                name:
                  type: string
              required:
                - id
                - name
            body:
              type: object
              properties:
                weight:
                  type: integer
                  example:20
                height:
                  type: integer
                  example:60
              required:
                - weight
                - height
          required:
            - headers
            - body

    この定義を、Jsonに定義しなおすんだ。

    {
        "headers": {
          "id": 100,
          "name": "Pepper"
      },
        "body": {
          "weight": 20,
          "height": 60
      }
    }

    こんな感じかな。自動化出来るかねぇ。値は今のところ乱数か、example:の値を使うのよ。
    一応最終形態がこの変換ですね。ネストすると大変なんで、とりあえず平文で作ってみることにします。

    つーことで、走らせてみたら、パーサーが最初の行のアイテムを取得できてないことが判明。パーサーの修正が先になりました。残念 orz

    あなたへのおすすめ