Can copy/move files from Hugo?

The need for this is a little complicated to explain, but is there any way to copy or move files that live under the Hugo site directory from template code?

The very short version is that I’m iterating over image files in a directory with readDir and creating an image gallery from them, and since there seems to be no way to control the sort order that readDir works with, I use an external process to sort the files the way I need to by prefixing a sequence # in front of each filename. But when these image files make it to the live site, I want remove the sequence # prefix from the filenames. Thus, I’m hoping there’s a way to rename the image files from inside the readDir loop. Can I do this? Or is there some kind of workaround?

Thanks!

There is no function for renaming files in Hugo.

Files are sorted in alphanumeric order.

Why use readDir to build a gallery when there are Page Bundles and the Image Page Resource?

With Page Resources there are methods like GetMatch that can be used with pattern matching to get or exclude what you need.

But doesn’t readDir return a slice of os.FileInfos? And can that slice not be sorted by any field then?

I haven’t tried the above @nekr0z

I just did, out of curiosity, and it works. For example, this little snippet:

{{ $files := sort (readDir "test_pictures/") "ModTime" "desc" }}
{{ range $files -}}
{{ .Name }}
{{ end -}}

prints a list of filenames in test_pictures directory, sorted from oldest to newest.

@mrverdantgreen I don’t know how complicated the sorting criteria you have in mind are, but if os.FileInfo contains enough information, maybe you can do without all the renaming mess?

3 Likes

Thanks @nekr0z, this works well!

I initially didn’t like this approach because I need to sort images in an ad hoc way (based on how someone thinks they should flow) and there didn’t seem to be any way to match this to the available fields in os.FileInfo. But then I realized that I don’t care about the modified time on the files. So I created shell script that I invoke (via Automator on Mac) from a photo browser like Photo Mechanic or Adobe Bridge. This assigns incrementing modified times to each photo in the correct order so that I can then use the code you provided, and now I can process photos and display them in any order I need in Hugo.

Thanks again!