diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3b45c77 --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +# Binaries for programs and plugins +web-to-markdown +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories +vendor/ + +# Environment-specific files +.env +.idea/ +.vscode/ +*.swp diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f76e58b --- /dev/null +++ b/go.mod @@ -0,0 +1,19 @@ +module web-to-markdown + +go 1.25.0 + +require ( + codeberg.org/readeck/go-readability/v2 v2.1.1 + github.com/JohannesKaufmann/html-to-markdown v1.6.0 + github.com/PuerkitoBio/goquery v1.12.0 + golang.org/x/sync v0.20.0 +) + +require ( + github.com/andybalholm/cascadia v1.3.3 // indirect + github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de // indirect + github.com/go-shiori/dom v0.0.0-20230515143342-73569d674e1c // indirect + github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f // indirect + golang.org/x/net v0.52.0 // indirect + golang.org/x/text v0.35.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..4d9ef0d --- /dev/null +++ b/go.sum @@ -0,0 +1,128 @@ +codeberg.org/readeck/go-readability/v2 v2.1.1 h1:1tEwxFuUqDRP5JABzDHXGWRx5p9S7TElS3U8qQwXC5Y= +codeberg.org/readeck/go-readability/v2 v2.1.1/go.mod h1:x3WG9GpWWnkRb7ajP1NmOKSHbafxNUb736lrDZXeXrs= +github.com/JohannesKaufmann/html-to-markdown v1.6.0 h1:04VXMiE50YYfCfLboJCLcgqF5x+rHJnb1ssNmqpLH/k= +github.com/JohannesKaufmann/html-to-markdown v1.6.0/go.mod h1:NUI78lGg/a7vpEJTz/0uOcYMaibytE4BUOQS8k78yPQ= +github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk= +github.com/PuerkitoBio/goquery v1.12.0 h1:pAcL4g3WRXekcB9AU/y1mbKez2dbY2AajVhtkO8RIBo= +github.com/PuerkitoBio/goquery v1.12.0/go.mod h1:802ej+gV2y7bbIhOIoPY5sT183ZW0YFofScC4q/hIpQ= +github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU= +github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM= +github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA= +github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de h1:FxWPpzIjnTlhPwqqXc4/vE0f7GvRjuAsbW+HOIe8KnA= +github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de/go.mod h1:DCaWoUhZrYW9p1lxo/cm8EmUOOzAPSEZNGF2DK1dJgw= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-shiori/dom v0.0.0-20230515143342-73569d674e1c h1:wpkoddUomPfHiOziHZixGO5ZBS73cKqVzZipfrLmO1w= +github.com/go-shiori/dom v0.0.0-20230515143342-73569d674e1c/go.mod h1:oVDCh3qjJMLVUSILBRwrm+Bc6RNXGZYtoh9xdvf1ffM= +github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f h1:3BSP1Tbs2djlpprl7wCLuiqMaUh5SJkkzI2gDs+FgLs= +github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/scylladb/termtables v0.0.0-20191203121021-c4c0b6d42ff4/go.mod h1:C1a7PQSMz9NShzorzCiG2fk9+xuCgLkPeCvMHYR2OWg= +github.com/sebdah/goldie/v2 v2.5.3 h1:9ES/mNN+HNUbNWpVAlrzuZ7jE+Nrczbj8uFRjM7624Y= +github.com/sebdah/goldie/v2 v2.5.3/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= +github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= +github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/goldmark v1.7.1 h1:3bajkSilaCbjdKVsKdZjZCLBNPL9pYzrCakKaf4U49U= +github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk= +golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= +golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go new file mode 100644 index 0000000..591809f --- /dev/null +++ b/main.go @@ -0,0 +1,307 @@ +// Package main provides a CLI utility to download HTML articles and convert them to Markdown with localized images. +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "flag" + "fmt" + "io" + "net/http" + "net/url" + "os" + "os/signal" + "path/filepath" + "regexp" + "strings" + "syscall" + "time" + + "codeberg.org/readeck/go-readability/v2" + md "github.com/JohannesKaufmann/html-to-markdown" + "github.com/PuerkitoBio/goquery" + "golang.org/x/sync/errgroup" +) + +const ( + dirPerms = 0755 + filePerms = 0644 +) + +var ( + // slugRegex compiled once at package level for performance. + slugRegex = regexp.MustCompile("[^a-z0-9]+") +) + +// ImageJob represents a single image to be downloaded concurrently. +type ImageJob struct { + URL string + LocalPath string +} + +func main() { + var titleOverride string + var outDirBase string + + flag.StringVar(&titleOverride, "title", "", "Override the article title and folder name") + flag.StringVar(&outDirBase, "out", ".", "Base directory to download the article folder into") + flag.Parse() + + if flag.NArg() < 1 { + fmt.Fprintf(os.Stderr, "Usage: %s [options] \nOptions:\n", os.Args[0]) + flag.PrintDefaults() + os.Exit(1) + } + + rawURL := flag.Arg(0) + + // Handle graceful shutdown via signals. + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + client := &http.Client{Timeout: 30 * time.Second} + + if err := run(ctx, client, rawURL, titleOverride, outDirBase); err != nil { + fmt.Fprintf(os.Stderr, "error: %v\n", err) + os.Exit(1) + } +} + +// run orchestrates the fetching, parsing, and downloading process. +func run(ctx context.Context, client *http.Client, rawURL, titleOverride, outDirBase string) error { + targetURL, err := url.Parse(rawURL) + if err != nil { + return fmt.Errorf("failed to parse target URL %q: %w", rawURL, err) + } + + fmt.Printf("Fetching: %s\n", rawURL) + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return fmt.Errorf("failed to create request: %w", err) + } + + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("failed to fetch URL: %w", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("failed to fetch URL: status code %d", resp.StatusCode) + } + + article, err := readability.FromReader(resp.Body, targetURL) + if err != nil { + return fmt.Errorf("failed to parse article: %w", err) + } + + finalTitle := article.Title() + if titleOverride != "" { + finalTitle = titleOverride + } + + slug := generateSlug(finalTitle) + if slug == "" { + slug = "article" + } + + outDir := filepath.Join(outDirBase, slug) + if err := os.MkdirAll(outDir, dirPerms); err != nil { + return fmt.Errorf("failed to create directory %s: %w", outDir, err) + } + + var buf bytes.Buffer + if err := article.RenderHTML(&buf); err != nil { + return fmt.Errorf("failed to render article HTML: %w", err) + } + + modifiedHTML, imageJobs, err := processHTML(buf.String(), targetURL, outDir) + if err != nil { + return fmt.Errorf("failed to process HTML: %w", err) + } + + converter := md.NewConverter("", true, nil) + markdownContent, err := converter.ConvertString(modifiedHTML) + if err != nil { + return fmt.Errorf("failed to convert to markdown: %w", err) + } + + frontmatter := fmt.Sprintf("---\ntitle: \"%s\"\nsource: \"%s\"\n---\n\n", finalTitle, rawURL) + markdownContent = frontmatter + markdownContent + + if len(imageJobs) > 0 { + fmt.Printf("Downloading %d images concurrently...\n", len(imageJobs)) + + g, gCtx := errgroup.WithContext(ctx) + for _, job := range imageJobs { + g.Go(func() error { + return downloadImage(gCtx, client, job.URL, job.LocalPath) + }) + } + + if err := g.Wait(); err != nil { + fmt.Fprintf(os.Stderr, "warning: one or more images failed to download: %v\n", err) + } + } + + mdPath := filepath.Join(outDir, "index.md") + if err := os.WriteFile(mdPath, []byte(markdownContent), filePerms); err != nil { + return fmt.Errorf("failed to write markdown file: %w", err) + } + + fmt.Printf("Successfully saved article to: %s\n", mdPath) + return nil +} + +// processHTML extracts images, rewrites their src attributes for a flat structure, +// and returns the modified HTML string and a slice of ImageJobs to be downloaded. +func processHTML(htmlContent string, targetURL *url.URL, outDir string) (string, []ImageJob, error) { + doc, err := goquery.NewDocumentFromReader(strings.NewReader(htmlContent)) + if err != nil { + return "", nil, err + } + + var imageJobs []ImageJob + + doc.Find("img").Each(func(i int, s *goquery.Selection) { + src, exists := s.Attr("src") + if !exists || src == "" { + return + } + + imgURL, err := targetURL.Parse(src) + if err != nil { + fmt.Fprintf(os.Stderr, "warning: failed to parse image URL %s: %v\n", src, err) + return + } + + altText, _ := s.Attr("alt") + titleText, _ := s.Attr("title") + figCaption := s.ParentsFiltered("figure").Find("figcaption").Text() + + // Traverse up DOM to find nearest preceding section header + var headerText string + curr := s + for curr.Length() > 0 && !curr.Is("body") { + h := curr.PrevAllFiltered("h1, h2, h3, h4, h5, h6").First() + if h.Length() > 0 { + headerText = h.Text() + break + } + curr = curr.Parent() + } + + rawName := "" + if altText != "" { + rawName = altText + } else if titleText != "" { + rawName = titleText + } else if figCaption != "" { + rawName = figCaption + } + + baseName := "" + if rawName != "" { + s.SetAttr("alt", strings.TrimSpace(rawName)) // set for markdown converter + baseName = generateSlug(rawName) + if len(baseName) > 40 { + baseName = baseName[:40] + baseName = strings.TrimRight(baseName, "-") + } + } + + if baseName == "" || baseName == "-" { + baseNameStr := strings.TrimSuffix(filepath.Base(imgURL.Path), filepath.Ext(imgURL.Path)) + baseName = generateSlug(baseNameStr) + + // Fallback if filename is CDN hash (long) or empty + if len(baseName) >= 20 || baseName == "" || baseName == "-" || baseName == "image" { + if headerText != "" { + baseName = generateSlug(headerText) + s.SetAttr("alt", strings.TrimSpace(headerText)) + } else { + baseName = fmt.Sprintf("section-image-%d", i+1) + s.SetAttr("alt", fmt.Sprintf("Section Image %d", i+1)) + } + } else { + s.SetAttr("alt", strings.ReplaceAll(baseNameStr, "-", " ")) + } + } + + hash := sha256.Sum256([]byte(imgURL.String())) + hashStr := hex.EncodeToString(hash[:])[:6] + + ext := filepath.Ext(imgURL.Path) + if ext == "" { + ext = ".jpg" + } + ext = strings.Split(ext, "?")[0] + + // Format output like `capo-notation-a1b2c3.jpg` (using standard url-safe slugs) + filename := fmt.Sprintf("%s-%s%s", baseName, hashStr, ext) + localAbsPath := filepath.Join(outDir, filename) + + s.SetAttr("src", filename) + + imageJobs = append(imageJobs, ImageJob{ + URL: imgURL.String(), + LocalPath: localAbsPath, + }) + }) + + modifiedHTML, err := doc.Find("body").Html() + if err != nil { + return "", nil, fmt.Errorf("failed to render modified HTML: %w", err) + } + + return modifiedHTML, imageJobs, nil +} + +// downloadImage fetches the image from the given URL and saves it to localPath. +func downloadImage(ctx context.Context, client *http.Client, urlStr, localPath string) (err error) { + req, reqErr := http.NewRequestWithContext(ctx, http.MethodGet, urlStr, nil) + if reqErr != nil { + return fmt.Errorf("create request for %s: %w", urlStr, reqErr) + } + + resp, doErr := client.Do(req) + if doErr != nil { + return fmt.Errorf("get %s: %w", urlStr, doErr) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("bad status %d for %s", resp.StatusCode, urlStr) + } + + out, createErr := os.Create(localPath) + if createErr != nil { + return fmt.Errorf("create file %s: %w", localPath, createErr) + } + defer func() { + closeErr := out.Close() + if err == nil { + err = closeErr + } + }() + + if _, err = io.Copy(out, resp.Body); err != nil { + return fmt.Errorf("write file %s: %w", localPath, err) + } + + return nil +} + +// generateSlug truncates the string to 5 words and converts it to a safe filesystem slug. +func generateSlug(s string) string { + words := strings.Fields(s) + if len(words) > 5 { + words = words[:5] + } + s = strings.Join(words, " ") + + return strings.Trim(slugRegex.ReplaceAllString(strings.ToLower(s), "-"), "-") +} diff --git a/main_test.go b/main_test.go new file mode 100644 index 0000000..d56eb10 --- /dev/null +++ b/main_test.go @@ -0,0 +1,120 @@ +package main + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestGenerateSlug(t *testing.T) { + tests := []struct { + name string + input string + expected string + }{ + {"Normal title", "The Ultimate Guide to Go", "the-ultimate-guide-to-go"}, + {"Long title truncation", "This is a very long title that should be cut off", "this-is-a-very-long"}, + {"Punctuation removal", "Wow! This is: awesome (really).", "wow-this-is-awesome-really"}, + {"Multiple spaces", "Title with spaces", "title-with-spaces"}, + {"Empty string", "", ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := generateSlug(tt.input) + if got != tt.expected { + t.Errorf("generateSlug(%q) = %q; want %q", tt.input, got, tt.expected) + } + }) + } +} + +func TestProcessHTML(t *testing.T) { + inputHTML := ` + + +

Capo Notation

+

Here is an image:

+ + + + + ` + + targetURL, _ := url.Parse("https://example.com/blog/post") + outDir := "/tmp/output" + + modifiedHTML, jobs, err := processHTML(inputHTML, targetURL, outDir) + if err != nil { + t.Fatalf("processHTML failed: %v", err) + } + + if len(jobs) != 2 { + t.Fatalf("expected 2 image jobs, got %d", len(jobs)) + } + + // Test first image (CDN hash fallback to nearest preceding heading) + job1 := jobs[0] + if !strings.HasPrefix(filepath.Base(job1.LocalPath), "capo-notation-") { + t.Errorf("expected job1 filename to fallback to 'capo-notation-', got %q", filepath.Base(job1.LocalPath)) + } + + // Test second image (Original filename) + job2 := jobs[1] + if !strings.HasPrefix(filepath.Base(job2.LocalPath), "cat-") { + t.Errorf("expected job2 filename to fallback to 'cat-', got %q", filepath.Base(job2.LocalPath)) + } + + // Ensure modified HTML has rewritten srcs and alts. + if !strings.Contains(modifiedHTML, `alt="Capo Notation"`) { + t.Errorf("modified HTML missing injected fallback alt text for job1.") + } +} + +func TestDownloadImage(t *testing.T) { + expectedContent := []byte("fake image content") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/notfound.jpg" { + http.NotFound(w, r) + return + } + w.Write(expectedContent) + })) + defer server.Close() + + tmpFile, err := os.CreateTemp("", "test_img_*.jpg") + if err != nil { + t.Fatalf("failed to create temp file: %v", err) + } + tmpPath := tmpFile.Name() + tmpFile.Close() + defer os.Remove(tmpPath) + + ctx := context.Background() + client := server.Client() + + err = downloadImage(ctx, client, server.URL+"/test.jpg", tmpPath) + if err != nil { + t.Fatalf("downloadImage failed on valid URL: %v", err) + } + + content, err := os.ReadFile(tmpPath) + if err != nil { + t.Fatalf("failed to read written file: %v", err) + } + if string(content) != string(expectedContent) { + t.Errorf("expected content %q, got %q", expectedContent, content) + } + + err = downloadImage(ctx, client, server.URL+"/notfound.jpg", tmpPath) + if err == nil { + t.Errorf("expected error on 404 response, got nil") + } else if !strings.Contains(err.Error(), "bad status 404") { + t.Errorf("expected 404 error message, got %q", err) + } +}