fix(cookies): 保存时创建缺失的父目录 (#791)

COOKIES_PATH 指向尚不存在的目录时,保存会直接失败。

Thanks to @wzy31124513 for reporting (#422).

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
zy
2026-08-02 16:09:10 +08:00
committed by GitHub
parent d7f176a66f
commit 347428476d
2 changed files with 23 additions and 0 deletions
+6
View File
@@ -106,6 +106,12 @@ func (c *localCookie) write(cks []byte, seed int) error {
return errors.Wrap(err, "marshal session file failed")
}
if dir := filepath.Dir(c.path); dir != "" && dir != "." {
if err := os.MkdirAll(dir, 0755); err != nil {
return errors.Wrap(err, "create cookies dir failed")
}
}
return os.WriteFile(c.path, data, 0644)
}
+17
View File
@@ -155,3 +155,20 @@ func decodeJSON(t *testing.T, data []byte) any {
assert.NoError(t, json.Unmarshal(data, &v))
return v
}
// TestSaveCookies_CreatesParentDir 保存时父目录不存在也应能落盘。
//
// COOKIES_PATH 指向一个还没创建的目录时,原先会直接写失败。
func TestSaveCookies_CreatesParentDir(t *testing.T) {
path := filepath.Join(t.TempDir(), "nested", "deeper", "cookies.json")
c := NewLoadCookie(path)
assert.NoError(t, c.SaveCookies([]byte(`[{"name":"a","value":"b"}]`)))
got, err := c.LoadCookies()
assert.NoError(t, err)
var cks []map[string]string
assert.NoError(t, json.Unmarshal(got, &cks))
assert.Equal(t, "a", cks[0]["name"])
}