From ea75cc1bfe2205bd30911d2b49426430e42ac07b Mon Sep 17 00:00:00 2001 From: utahta Date: Mon, 20 Jul 2026 11:09:09 +0900 Subject: [PATCH] Polish README style and remove obsolete gitbook2md tool MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Unify notation (v1/v2 casing, APIキー, politeness level, sentence endings) and align example date/code formats in README - Clarify the intro: "easy" now refers to the client library, and the API key / subscription plan requirement is stated upfront - Remove cmd/gitbook2md since the official docs now serve Markdown directly (e.g. https://jpx-jquants.com/ja/spec/eq-bars-daily.md) - Point doc references to the new official spec URL --- .gitignore | 1 - CLAUDE.md | 2 +- README.md | 48 +-- cmd/gitbook2md/main.go | 740 ----------------------------------------- 4 files changed, 17 insertions(+), 774 deletions(-) delete mode 100644 cmd/gitbook2md/main.go diff --git a/.gitignore b/.gitignore index 5caba47..013dfc4 100644 --- a/.gitignore +++ b/.gitignore @@ -24,7 +24,6 @@ go.work.sum # Project specific tmp/ -cmd/gitbook2md/gitbook2md # IDE specific files .idea/ diff --git a/CLAUDE.md b/CLAUDE.md index 88ef6a3..2a3a36f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,7 +11,7 @@ J-Quants API v2(日本の株式市場データを提供するAPI)のGoクラ **重要**: J-Quants APIの仕様を確認する際は、以下の順序で参照してください: 1. **最初に必ず`docs/v2/`ディレクトリを確認** - このリポジトリ内のv2 APIドキュメント -2. **不明な点がある場合のみ**: https://jpx.gitbook.io/j-quants-ja/api-reference - 公式APIリファレンス +2. **不明な点がある場合のみ**: https://jpx-jquants.com/ja/spec/ - 公式APIリファレンス(各ページはURL末尾に`.md`を付けるとMarkdownで直接取得可能。例: https://jpx-jquants.com/ja/spec/eq-bars-daily.md ) ## 開発コマンド diff --git a/README.md b/README.md index 58fcb0f..7ab858c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # J-Quants Go Client -J-Quants API v2のGo言語クライアントライブラリです。日本の株式市場データに簡単にアクセスできます。 +J-Quants API v2のGo言語クライアントライブラリです。株価・財務情報など日本の株式市場データを扱うAPIをGoから簡単に利用できます。 + +利用には[J-Quants](https://jpx-jquants.com/)のAPIキーが必要です(取得できるデータは契約プランに応じます)。 ## 特徴 @@ -8,8 +10,6 @@ J-Quants API v2のGo言語クライアントライブラリです。日本の株 - 🔐 APIキーによるシンプルな認証 - 📄 ページネーション対応 - 🚀 セッション単位のキャッシュ機能(オプション) -- 🧪 充実したテストカバレッジ -- 📝 詳細なドキュメント ## インストール @@ -93,12 +93,12 @@ size := httpClient.CacheSize() - キャッシュはGETリクエストのみに適用されます - キャッシュキーはリクエストパス(クエリパラメータ含む)で区別されます - 同時リクエストの重複排除(singleflight)により効率的に動作します -- 重複排除の待機中にコンテキストをキャンセルした場合、その呼び出し元だけが即座にエラーで戻り、進行中のリクエスト自体は完了してキャッシュに保存されます +- 待機中にコンテキストをキャンセルした呼び出し元は即座にエラーで戻ります(進行中のリクエストは完了してキャッシュされます) - キャッシュはクライアントインスタンスの生存期間のみ有効です ## 利用可能なAPI -このライブラリでアクセスできるAPIエンドポイント: +このライブラリでは以下のAPIエンドポイントにアクセスできます。 | カテゴリ | サービス | 説明 | |---------|---------|------| @@ -122,7 +122,7 @@ size := httpClient.CacheSize() | **空売り** | ShortSelling | 業種別空売り比率 | | **空売り** | ShortSellingPositions | 空売り残高報告 | -※各APIの利用可能なプランについては、[J-Quants公式サイト](https://jpx-jquants.com/)でご確認ください。 +※各APIの利用可能なプランについては、[J-Quants公式サイト](https://jpx-jquants.com/)で確認してください。 ## 使用例 @@ -192,10 +192,10 @@ for _, stmt := range statements { ```go // 銘柄コードで取得 -data, err := jq.DailyMarginInterest.GetDailyMarginInterestByCode(ctx, "13260") +data, err := jq.DailyMarginInterest.GetDailyMarginInterestByCode(ctx, "1326") // 公表日で取得 -data, err := jq.DailyMarginInterest.GetDailyMarginInterestByDate(ctx, "20240208") +data, err := jq.DailyMarginInterest.GetDailyMarginInterestByDate(ctx, "2024-02-08") // 公表理由の確認 for _, d := range data { @@ -207,7 +207,7 @@ for _, d := range data { ### ページネーション対応 -大量のデータを扱うAPIではページネーションがサポートされています: +大量のデータを扱うAPIではページネーションがサポートされています。 ```go params := jquants.DailyQuotesParams{ @@ -251,7 +251,7 @@ make test-cover # リントチェック make lint -# E2Eテスト(API Keyが必要) +# E2Eテスト(APIキーが必要) make test-e2e ``` @@ -264,19 +264,17 @@ jquants/ ├── docs/ # APIドキュメント │ └── v2/ # v2 APIドキュメント ├── test/e2e/ # E2Eテスト -├── cmd/ # コマンドラインツール -│ └── gitbook2md/ # GitBook→Markdown変換ツール ├── *.go # 各APIサービス実装 └── Makefile # ビルドタスク ``` -## V1からV2への移行 +## v1からv2への移行 -J-Quants API v2では以下の変更があります: +J-Quants API v2では以下の変更があります。 ### 認証方式の変更 -| 項目 | V1 | V2 | +| 項目 | v1 | v2 | |------|-----|-----| | 認証方式 | トークン方式(ID Token/Refresh Token) | APIキー方式(x-api-key) | | 認証パッケージ | `auth/` パッケージを使用 | `client` パッケージに統合 | @@ -290,29 +288,15 @@ J-Quants API v2では以下の変更があります: ### コード例 ```go -// V1 +// v1 quote.Open, quote.High, quote.Low, quote.Close -// V2 +// v2 quote.O, quote.H, quote.L, quote.C ``` 詳細は `docs/v2/migration-v1-v2.md` を参照してください。 -## ツール - -### gitbook2md - -GitBookのドキュメントをMarkdown形式に変換するツールです。 - -```bash -# ビルド -cd cmd/gitbook2md && go build - -# URLから直接変換 -./gitbook2md --url https://jpx.gitbook.io/j-quants-ja/api-reference/statements --output statements.md -``` - ## エラーハンドリング ```go @@ -330,7 +314,7 @@ if err != nil { - J-Quants APIの利用には適切なサブスクリプションが必要です - プランごとにレートリミットが設定されています(Free: 5/分, Light: 60/分, Standard: 120/分, Premium: 500/分) - 営業日以外はデータが取得できない場合があります -- 詳細なAPI仕様は[公式ドキュメント](https://jpx.gitbook.io/j-quants-ja/api-reference)を参照してください +- 詳細なAPI仕様は[公式ドキュメント](https://jpx-jquants.com/ja/spec/)を参照してください ## ライセンス diff --git a/cmd/gitbook2md/main.go b/cmd/gitbook2md/main.go deleted file mode 100644 index 5d75ad9..0000000 --- a/cmd/gitbook2md/main.go +++ /dev/null @@ -1,740 +0,0 @@ -// gitbook2md is a tool to convert GitBook HTML pages to Markdown format. -// This tool is used for documentation purposes only and is not part of the main library. -package main - -import ( - "flag" - "fmt" - "io" - "log" - "net/http" - "os" - "path/filepath" - "regexp" - "strings" - - "golang.org/x/net/html" -) - -// GitBookParser is a specialized parser for GitBook HTML pages -type GitBookParser struct { - debug bool -} - -// NewGitBookParser creates a new GitBook parser -func NewGitBookParser(debug bool) *GitBookParser { - return &GitBookParser{debug: debug} -} - -// ParseFile parses a GitBook HTML file and returns Markdown -func (p *GitBookParser) ParseFile(filename string) (string, error) { - file, err := os.Open(filename) // #nosec G304 - if err != nil { - return "", err - } - defer func() { _ = file.Close() }() - - doc, err := html.Parse(file) - if err != nil { - return "", err - } - - // Extract metadata - title := p.extractTitle(doc) - description := p.extractDescription(doc) - - // Find main content - content := p.extractMainContent(doc) - - // Build markdown - var markdown strings.Builder - - if title != "" { - markdown.WriteString("# " + title + "\n\n") - } - - if description != "" { - markdown.WriteString("> " + description + "\n\n") - } - - if content != "" { - markdown.WriteString(content) - } - - return markdown.String(), nil -} - -// extractTitle extracts the page title -func (p *GitBookParser) extractTitle(n *html.Node) string { - if n.Type == html.ElementNode && n.Data == "title" { - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == html.TextNode { - title := strings.TrimSpace(c.Data) - // Remove " | J-Quants API" suffix - if idx := strings.Index(title, " | "); idx > 0 { - title = title[:idx] - } - return title - } - } - } - - for c := n.FirstChild; c != nil; c = c.NextSibling { - if title := p.extractTitle(c); title != "" { - return title - } - } - - return "" -} - -// extractDescription extracts meta description -func (p *GitBookParser) extractDescription(n *html.Node) string { - if n.Type == html.ElementNode && n.Data == "meta" { - var name, content string - for _, attr := range n.Attr { - if attr.Key == "name" && attr.Val == "description" { - name = attr.Val - } - if attr.Key == "content" { - content = attr.Val - } - } - if name == "description" && content != "" { - return content - } - } - - for c := n.FirstChild; c != nil; c = c.NextSibling { - if desc := p.extractDescription(c); desc != "" { - return desc - } - } - - return "" -} - -// extractMainContent extracts the main content area -func (p *GitBookParser) extractMainContent(n *html.Node) string { - // Strategy: Look for specific patterns in the HTML - // 1. Find script tags with id="__NEXT_DATA__" which contains JSON data - // 2. Look for main content divs - // 3. Extract text content from specific areas - - var content strings.Builder - - // Look for JSON data in script tags - jsonData := p.extractJSONData(n) - if jsonData != "" { - // Parse JSON and extract relevant content - content.WriteString(p.parseJSONContent(jsonData)) - } - - // Look for structured content - p.extractStructuredContent(n, &content) - - return content.String() -} - -// extractJSONData looks for __NEXT_DATA__ script tag -func (p *GitBookParser) extractJSONData(n *html.Node) string { - if n.Type == html.ElementNode && n.Data == "script" { - for _, attr := range n.Attr { - if attr.Key == "id" && attr.Val == "__NEXT_DATA__" { - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == html.TextNode { - return c.Data - } - } - } - } - } - - for c := n.FirstChild; c != nil; c = c.NextSibling { - if data := p.extractJSONData(c); data != "" { - return data - } - } - - return "" -} - -// parseJSONContent extracts content from JSON data -func (p *GitBookParser) parseJSONContent(jsonStr string) string { - // This is a simplified extraction - // In a real implementation, you'd parse the JSON properly - - var content strings.Builder - - // Look for common patterns in the JSON - // Extract request/response examples - if strings.Contains(jsonStr, "```") { - // Extract code blocks - re := regexp.MustCompile("```[^`]*```") - matches := re.FindAllString(jsonStr, -1) - for _, match := range matches { - content.WriteString(match + "\n\n") - } - } - - return content.String() -} - -// extractStructuredContent extracts content from HTML structure -func (p *GitBookParser) extractStructuredContent(n *html.Node, content *strings.Builder) { - // Skip script and style tags - if n.Type == html.ElementNode && (n.Data == "script" || n.Data == "style" || n.Data == "noscript") { - return - } - - // Look for content patterns - if n.Type == html.ElementNode { - class := p.getAttr(n, "class") - - // Look for code blocks - if n.Data == "pre" || strings.Contains(class, "code") { - p.extractCodeBlock(n, content) - return - } - - // Look for tables - if n.Data == "table" { - p.extractTable(n, content) - return - } - - // Look for div-based tables - if n.Data == "div" && p.getAttr(n, "role") == "table" { - p.extractTable(n, content) - return - } - - // Look for headings - if n.Data == "h1" || n.Data == "h2" || n.Data == "h3" || n.Data == "h4" { - p.extractHeading(n, content) - return - } - - // Look for paragraphs with actual content - if n.Data == "p" { - text := p.extractText(n) - if len(text) > 20 && !strings.Contains(text, "mask-image") { - content.WriteString(text + "\n\n") - } - return - } - - // Look for lists - if n.Data == "ul" || n.Data == "ol" { - p.extractList(n, content, n.Data == "ol") - return - } - - // Look for definition lists (used for API parameters and response fields) - if n.Data == "dl" { - p.extractDefinitionList(n, content) - return - } - } - - // Process children - for c := n.FirstChild; c != nil; c = c.NextSibling { - p.extractStructuredContent(c, content) - } -} - -// extractCodeBlock extracts code blocks -func (p *GitBookParser) extractCodeBlock(n *html.Node, content *strings.Builder) { - code := p.extractText(n) - if code != "" && !strings.Contains(code, "function") && !strings.Contains(code, "var ") { - content.WriteString("```\n") - content.WriteString(code) - content.WriteString("\n```\n\n") - } -} - -// extractTable extracts and converts tables -func (p *GitBookParser) extractTable(n *html.Node, content *strings.Builder) { - // Simple table extraction - var headers []string - var rows [][]string - - // Find headers - p.findTableHeaders(n, &headers) - - // Find rows - p.findTableRows(n, &rows) - - // Also check for div-based tables with role attributes - if len(headers) == 0 && len(rows) == 0 { - p.findDivTableContent(n, &headers, &rows) - } - - if len(headers) > 0 { - // Write headers - content.WriteString("| ") - for _, h := range headers { - content.WriteString(h + " | ") - } - content.WriteString("\n|") - for range headers { - content.WriteString("------|") - } - content.WriteString("\n") - - // Write rows - for _, row := range rows { - if len(row) > 0 { - content.WriteString("| ") - for _, cell := range row { - content.WriteString(cell + " | ") - } - content.WriteString("\n") - } - } - content.WriteString("\n") - } -} - -// extractHeading extracts headings -func (p *GitBookParser) extractHeading(n *html.Node, content *strings.Builder) { - level := n.Data[1] - '0' - text := p.extractText(n) - if text != "" { - content.WriteString(strings.Repeat("#", int(level)) + " " + text + "\n\n") - } -} - -// extractList extracts lists -func (p *GitBookParser) extractList(n *html.Node, content *strings.Builder, ordered bool) { - counter := 1 - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == html.ElementNode && c.Data == "li" { - text := p.extractText(c) - if text != "" { - if ordered { - fmt.Fprintf(content, "%d. %s\n", counter, text) - counter++ - } else { - content.WriteString("- " + text + "\n") - } - } - } - } - content.WriteString("\n") -} - -// extractDefinitionList extracts definition lists (dl/dt/dd) used for API parameters -func (p *GitBookParser) extractDefinitionList(n *html.Node, content *strings.Builder) { - // Find all definition items (can be wrapped in div or directly as dt/dd pairs) - p.extractDefinitionItems(n, content) - content.WriteString("\n") -} - -// extractDefinitionItems recursively finds and extracts dt/dd pairs -func (p *GitBookParser) extractDefinitionItems(n *html.Node, content *strings.Builder) { - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == html.ElementNode { - if c.Data == "div" { - // Definition item wrapped in div - p.extractSingleDefinition(c, content) - } else if c.Data == "dt" { - // Direct dt element - find the next dd - term := p.extractDefinitionTerm(c) - desc := "" - // Look for the next dd sibling - for dd := c.NextSibling; dd != nil; dd = dd.NextSibling { - if dd.Type == html.ElementNode && dd.Data == "dd" { - desc = p.extractText(dd) - break - } - } - if term != "" { - content.WriteString(term) - if desc != "" { - content.WriteString("\n " + desc) - } - content.WriteString("\n\n") - } - } - } - } -} - -// extractSingleDefinition extracts a single dt/dd pair from a container div -func (p *GitBookParser) extractSingleDefinition(n *html.Node, content *strings.Builder) { - var term, desc string - - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == html.ElementNode { - switch c.Data { - case "dt": - term = p.extractDefinitionTerm(c) - case "dd": - desc = p.extractText(c) - } - } - } - - if term != "" { - content.WriteString(term) - if desc != "" { - content.WriteString("\n " + desc) - } - content.WriteString("\n\n") - } -} - -// extractDefinitionTerm extracts the term from a dt element -// Format: **name** (type, required/optional) -func (p *GitBookParser) extractDefinitionTerm(n *html.Node) string { - var name, typeStr, requiredStr string - - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == html.ElementNode && c.Data == "span" { - text := p.extractText(c) - class := p.getAttr(c, "class") - - if strings.Contains(class, "font-semibold") { - name = text - } else if strings.Contains(class, "text-gray") || strings.Contains(class, "bg-gray") { - if typeStr == "" && isTypeText(text) { - typeStr = text - } else if text == "optional" { - requiredStr = text - } - } else if strings.Contains(class, "text-red") || strings.Contains(class, "bg-red") { - if text == "required" { - requiredStr = text - } - } else if strings.Contains(class, "text-blue") || strings.Contains(class, "bg-blue") { - if text == "optional" { - requiredStr = text - } - } - } - } - - if name == "" { - return "" - } - - result := "**" + name + "**" - if typeStr != "" || requiredStr != "" { - result += " (" - if typeStr != "" { - result += typeStr - } - if requiredStr != "" { - if typeStr != "" { - result += ", " - } - result += requiredStr - } - result += ")" - } - - return result -} - -// Helper methods - -// isTypeText checks if the text represents a type annotation -// Supports both simple types (string, number) and compound types (number | string) -func isTypeText(text string) bool { - types := []string{"string", "number", "boolean", "array", "object"} - for _, t := range types { - if strings.Contains(text, t) { - return true - } - } - return false -} - -func (p *GitBookParser) getAttr(n *html.Node, key string) string { - for _, attr := range n.Attr { - if attr.Key == key { - return attr.Val - } - } - return "" -} - -func (p *GitBookParser) extractText(n *html.Node) string { - var text strings.Builder - p.extractTextRecursive(n, &text) - return strings.TrimSpace(text.String()) -} - -func (p *GitBookParser) extractTextRecursive(n *html.Node, text *strings.Builder) { - if n.Type == html.TextNode { - text.WriteString(n.Data) - } - - // Handle checkbox input elements - if n.Type == html.ElementNode && n.Data == "input" { - inputType := p.getAttr(n, "type") - if inputType == "checkbox" { - // Check if the checkbox is checked - isChecked := false - for _, attr := range n.Attr { - if attr.Key == "checked" { - isChecked = true - break - } - } - if isChecked { - text.WriteString("✓") - } else { - text.WriteString("✗") - } - return - } - } - - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type != html.ElementNode || (c.Data != "script" && c.Data != "style") { - p.extractTextRecursive(c, text) - } - } -} - -func (p *GitBookParser) findTableHeaders(n *html.Node, headers *[]string) { - if n.Type == html.ElementNode { - if n.Data == "th" { - *headers = append(*headers, p.extractText(n)) - return - } - if n.Data == "thead" { - // Process only thead - for c := n.FirstChild; c != nil; c = c.NextSibling { - p.findTableHeaders(c, headers) - } - return - } - } - - for c := n.FirstChild; c != nil; c = c.NextSibling { - p.findTableHeaders(c, headers) - } -} - -func (p *GitBookParser) findTableRows(n *html.Node, rows *[][]string) { - if n.Type == html.ElementNode && n.Data == "tbody" { - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == html.ElementNode && c.Data == "tr" { - var row []string - for td := c.FirstChild; td != nil; td = td.NextSibling { - if td.Type == html.ElementNode && td.Data == "td" { - row = append(row, p.extractText(td)) - } - } - if len(row) > 0 { - *rows = append(*rows, row) - } - } - } - return - } - - for c := n.FirstChild; c != nil; c = c.NextSibling { - p.findTableRows(c, rows) - } -} - -// findDivTableContent looks for div-based tables with role attributes -func (p *GitBookParser) findDivTableContent(n *html.Node, headers *[]string, rows *[][]string) { - // Look for role="table" - if n.Type == html.ElementNode && p.getAttr(n, "role") == "table" { - p.extractDivTable(n, headers, rows) - return - } - - // Also check if we're looking at a data table section - if n.Type == html.ElementNode && n.Data == "div" { - // Check for headers with role="columnheader" - p.findDivHeaders(n, headers) - - // Check for rows with role="row" - p.findDivRows(n, rows) - } - - for c := n.FirstChild; c != nil; c = c.NextSibling { - if len(*headers) == 0 && len(*rows) == 0 { - p.findDivTableContent(c, headers, rows) - } - } -} - -// extractDivTable extracts content from div-based tables -func (p *GitBookParser) extractDivTable(n *html.Node, headers *[]string, rows *[][]string) { - // Find all elements with role="columnheader" for headers - p.findDivHeaders(n, headers) - - // Find all elements with role="row" for data rows - p.findDivRows(n, rows) -} - -// findDivHeaders finds div elements with role="columnheader" -func (p *GitBookParser) findDivHeaders(n *html.Node, headers *[]string) { - if n.Type == html.ElementNode && p.getAttr(n, "role") == "columnheader" { - *headers = append(*headers, p.extractText(n)) - return - } - - // Look for rowgroup containing headers - if n.Type == html.ElementNode && p.getAttr(n, "role") == "rowgroup" { - // Check if this is a header rowgroup - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == html.ElementNode && p.getAttr(c, "role") == "row" { - // Check if this row contains columnheaders - hasHeaders := false - for gc := c.FirstChild; gc != nil; gc = gc.NextSibling { - if gc.Type == html.ElementNode && p.getAttr(gc, "role") == "columnheader" { - hasHeaders = true - break - } - } - if hasHeaders { - // Extract headers from this row - for gc := c.FirstChild; gc != nil; gc = gc.NextSibling { - if gc.Type == html.ElementNode && p.getAttr(gc, "role") == "columnheader" { - *headers = append(*headers, p.extractText(gc)) - } - } - return - } - } - } - } - - for c := n.FirstChild; c != nil; c = c.NextSibling { - if len(*headers) == 0 { - p.findDivHeaders(c, headers) - } - } -} - -// findDivRows finds div elements with role="row" containing data cells -func (p *GitBookParser) findDivRows(n *html.Node, rows *[][]string) { - if n.Type == html.ElementNode && p.getAttr(n, "role") == "rowgroup" { - // Skip header rowgroup - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == html.ElementNode && p.getAttr(c, "role") == "row" { - // Check if this row contains cells (not headers) - var row []string - hasCells := false - for gc := c.FirstChild; gc != nil; gc = gc.NextSibling { - if gc.Type == html.ElementNode && p.getAttr(gc, "role") == "cell" { - hasCells = true - row = append(row, p.extractText(gc)) - } - } - if hasCells && len(row) > 0 { - *rows = append(*rows, row) - } - } - } - return - } - - for c := n.FirstChild; c != nil; c = c.NextSibling { - p.findDivRows(c, rows) - } -} - -func main() { - var ( - url = flag.String("url", "", "URL to fetch and convert") - output = flag.String("output", "", "Output file path") - debug = flag.Bool("debug", false, "Enable debug mode") - ) - flag.Parse() - - // Check if using old style arguments - if flag.NArg() > 0 && *url == "" { - // Old style: gitbook2md [output.md] - inputFile := flag.Arg(0) - outputFile := "" - if flag.NArg() > 1 { - outputFile = flag.Arg(1) - } - - parser := NewGitBookParser(*debug || os.Getenv("DEBUG") == "true") - markdown, err := parser.ParseFile(inputFile) - if err != nil { - log.Fatal(err) - } - - if outputFile != "" { - err = os.WriteFile(outputFile, []byte(markdown), 0644) // #nosec G306 G703 -- 出力先はCLI利用者が意図して指定するパス - if err != nil { - log.Fatal(err) - } - fmt.Printf("Wrote %s\n", outputFile) - } else { - fmt.Print(markdown) - } - return - } - - // New style with URL - if *url == "" { - fmt.Println("Usage:") - fmt.Println(" gitbook2md [output.md]") - fmt.Println(" gitbook2md --url [--output ]") - flag.PrintDefaults() - os.Exit(1) - } - - // Download the HTML content - resp, err := http.Get(*url) - if err != nil { - log.Fatal("Failed to fetch URL:", err) - } - defer func() { _ = resp.Body.Close() }() - - if resp.StatusCode != http.StatusOK { - log.Fatal("HTTP error:", resp.StatusCode) - } - - // Create temporary file - tmpFile, err := os.CreateTemp("", "gitbook2md-*.html") // #nosec G303 - if err != nil { - log.Fatal("Failed to create temp file:", err) - } - defer func() { _ = os.Remove(tmpFile.Name()) }() - defer func() { _ = tmpFile.Close() }() - - // Copy content to temp file - _, err = io.Copy(tmpFile, resp.Body) - if err != nil { - log.Fatal("Failed to save HTML:", err) - } - _ = tmpFile.Close() // #nosec G104 - - // Parse the file - parser := NewGitBookParser(*debug) - markdown, err := parser.ParseFile(tmpFile.Name()) - if err != nil { - log.Fatal(err) - } - - // Output - if *output != "" { - // Create directory if needed - dir := filepath.Dir(*output) - // #nosec G301 -- Documentation directory needs to be readable - if err := os.MkdirAll(dir, 0755); err != nil { - log.Fatal("Failed to create directory:", err) - } - - err = os.WriteFile(*output, []byte(markdown), 0644) // #nosec G306 - if err != nil { - log.Fatal(err) - } - fmt.Printf("Wrote %s\n", *output) - } else { - fmt.Print(markdown) - } -} \ No newline at end of file