Skip to content
Merged
19 changes: 19 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,25 @@ jobs:
sw provider auto
tools/deploy-test/provider.sh provider auto
tools/deploy-test/check.sh agents
- name: Turn on pruning (already on, then on a job set up without it)
shell: zsh -e -o pipefail {0}
run: |
p=~/Library/LaunchAgents/com.archivis.index.plist
args() { plutil -extract ProgramArguments json -o - "$p" | python3 -c 'import json,sys; print(" ".join(json.load(sys.stdin)))'; }
check() {
a=$(args)
[ "$(grep -o -- ' --prune ' <<<" $a " | wc -l | tr -d ' ')" = 1 ] || { echo "::error::want one --prune: $a"; exit 1; }
case "$a" in *" index "*"--prune"*) ;; *) echo "::error::--prune not after index: $a"; exit 1 ;; esac
launchctl print gui/$(id -u)/com.archivis.index >/dev/null || { echo "::error::the index agent is not loaded"; exit 1; }
echo "prune: ok ($a)"
}
tools/deploy-test/block.sh prune-on | zsh # the agent from step 7 has it: nothing changes
check
i=$(plutil -extract ProgramArguments json -o - "$p" | python3 -c 'import json,sys; print(json.load(sys.stdin).index("--prune"))')
/usr/libexec/PlistBuddy -c "Delete :ProgramArguments:$i" "$p" # as set up before --prune
case "$(args)" in *--prune*) echo "::error::--prune not deleted"; exit 1 ;; esac
tools/deploy-test/block.sh prune-on | zsh
check
- name: Move to system services
shell: zsh {0}
run: |
Expand Down
49 changes: 48 additions & 1 deletion DEPLOY.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ cat > ~/Library/LaunchAgents/com.archivis.index.plist <<EOF
<string>/usr/bin/caffeinate</string><string>-i</string>
<string>/usr/local/bin/archivis</string>
<string>index</string>
<string>--prune</string>
<string>/Volumes/Archive1</string>
<string>/Volumes/Archive2</string>
</array>
Expand All @@ -202,6 +203,39 @@ Edit the `/Volumes/...` lines to match your drives. A drive that isn't
plugged in is skipped with a warning; the others are still indexed. If the
Mac is asleep at 2:30, launchd runs the job when it wakes.

`--prune` removes photos you deleted from these folders from the catalogue,
after each complete run (so moved files are found first). It does that only
when every folder is there and not empty, before the run and after it (an
unmounted drive, or several after a restart, would look like deleted
photos), and the run read every folder and recorded every change. Otherwise
the log has an `error: not removing deleted photos` line with each reason,
nothing is removed, and the next run that sees everything catches up. A
missing copy that Photos or another photo app made is kept if you named
faces on it, rated it or starred it (nothing else holds those);
`archivis prune` removes it. A deleted photo's names, ratings and stars
move to an identical photo still catalogued, if there is one. To turn it on for a service set up without it:

<!-- ci: prune-on (run as written by the deploy job in .github/workflows/ci.yml) -->
```sh
d=~/Library/LaunchAgents; dom=gui/$(id -u); s= # agents
# d=/Library/LaunchDaemons; dom=system; s=sudo # services started at boot
p=$d/com.archivis.index.plist
args=$($s /usr/libexec/PlistBuddy -c "Print :ProgramArguments" "$p")
if [ -n "$args" ] && ! grep -qxE ' *--?prune' <<<"$args"; then
$s /usr/libexec/PlistBuddy -c "Add :ProgramArguments:4 string --prune" "$p" # after "index"
$s launchctl bootout $dom/com.archivis.index
while $s launchctl print $dom/com.archivis.index >/dev/null 2>&1; do sleep 1; done
$s launchctl bootstrap $dom "$p"
fi
```

Run it while the index isn't running (`launchctl print
$dom/com.archivis.index | grep state` doesn't say `running`): reloading stops
a run in progress, which picks up where it left off at 2:30. For services
started at boot ([Start at boot, with nobody
logged in](#start-at-boot-with-nobody-logged-in)), swap the comment marks on
the first two lines.

### Managing the services

```sh
Expand Down Expand Up @@ -435,7 +469,7 @@ User=$(id -un)
Environment=ARCHIVIS_DATA=$HOME/.archivis
Nice=10
IOSchedulingClass=idle
ExecStart=/usr/local/bin/archivis index /mnt/archive1 /mnt/archive2
ExecStart=/usr/local/bin/archivis index --prune /mnt/archive1 /mnt/archive2
EOF

sudo tee /etc/systemd/system/archivis-index.timer >/dev/null <<EOF
Expand All @@ -459,6 +493,19 @@ first index runs in the background and survives logging out; if it is still
running at 2:30 the timer does not start a second copy. A drive that isn't
mounted is skipped with a warning.

`--prune` removes photos you deleted from these folders from the catalogue,
but only when every folder is there and not empty (an unmounted drive's
mount point is empty), before the run and after it, and the run read every
folder and recorded every change; otherwise the log says why, nothing is
removed, and the next run that sees everything catches up. To add it to a
service set up without it:

```sh
grep -q 'archivis index --prune' /etc/systemd/system/archivis-index.service ||
sudo sed -i 's|archivis index |archivis index --prune |' /etc/systemd/system/archivis-index.service
sudo systemctl daemon-reload
```

### Managing the services

```sh
Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@ everything runs locally, nothing leaves your machine.
RW2, PEF, …); HEIC via `sips` on macOS (or libheif/ImageMagick/libvips).
`prune` keeps entries on drives that look offline: a folder whose
catalogued files are all missing and that is itself gone or empty is held
back unless you pass `--all-missing`.
back unless you pass `--all-missing`. A removed photo's hand-given names,
ratings and stars move to an identical photo still catalogued, if any. `index --prune` prunes after each
complete run, and only when every folder it indexes is there and not
empty, before and after the run, and the run read and recorded
everything; otherwise it logs why and prunes nothing (not with `--force`,
which doesn't recognise moved photos).

Your original files are only ever read, never modified.

Expand Down Expand Up @@ -108,6 +113,7 @@ archivis aesthetic train # learn your taste from ratings given in the web UI
archivis aesthetic models # every aesthetic model used, and the current blend
archivis retag # after editing ~/.archivis/categories.txt
archivis prune /Volumes/Archive1 # forget files deleted from that drive
archivis index --prune /Volumes/Archive1 /Volumes/Archive2 # index, then forget deleted files if both drives are there
archivis stats ; archivis errors
archivis inspect --previews ~/Desktop/check /Volumes/Card/DCIM # what Archivis reads from your camera's files
```
Expand Down
35 changes: 15 additions & 20 deletions cmd/archivis/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -354,16 +354,24 @@ func runIndex(g *globals, args []string) error {
noFaces := fs.Bool("no-faces", false, "skip face detection")
noMatch := fs.Bool("no-match", false, "don't auto-label people after indexing")
minBytes := fs.Int64("min-bytes", 4096, "skip files smaller than this many bytes (icons, tiny thumbnails)")
prune := fs.Bool("prune", false, "afterwards, remove photos deleted from these folders from the catalogue; only when every folder is there and not empty (an unmounted drive's is not) before and after the run, and the run read and recorded everything; else an error says why and nothing is removed")
g.register(fs)
roots := parseInterleaved(fs, args)
if *prune && *force {
return fmt.Errorf("--prune can't be used with --force: re-analysing every photo doesn't recognise moved ones, so pruning would drop their old records with their names and ratings; run --force without --prune, and --prune on a later run")
}
if len(roots) == 0 {
return fmt.Errorf("give at least one folder to index")
}
fmt.Fprintf(os.Stderr, "%s %s: indexing %s\n", time.Now().Format("2006-01-02 15:04:05"), versionInfo(), strings.Join(roots, ", "))
// A drive that isn't mounted shouldn't stop the others from being
// indexed (e.g. a nightly job over several archive drives).
var avail []string
notReady := map[string]string{} // for --prune: why a folder can't show deletions, as indexing starts
for _, r := range roots {
if p := folderProblem(r); p != "" {
notReady[r] = p
}
if st, err := os.Stat(r); err != nil || !st.IsDir() {
fmt.Fprintf(os.Stderr, "warning: skipping %s: not a folder (drive not mounted?)\n", r)
continue
Expand Down Expand Up @@ -409,27 +417,11 @@ func runIndex(g *globals, args []string) error {
return runErr
}
if ctx.Err() == nil {
// Apple's copies catalogued from inside Photos libraries by older
// versions: removed once their originals are in (names moved first),
// before auto-labelling so moved names count as examples.
res, err := cat.Store.CleanPhotosLibraries(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "warning: cleaning up Photos library copies: %v (retried on the next run)\n", err)
}
if res.Removed > 0 || res.Kept > 0 {
fmt.Fprintf(os.Stderr, "Photos libraries: removed %d of Apple's copies (moved %d face names, %d ratings to the originals); kept %d with no original catalogued\n",
res.Removed, res.LabelsMoved, res.FeedbackMoved, res.Kept)
}
// then any app copies left: Photos copies with a twin elsewhere,
// iPhoto, Aperture and Capture One caches
cres, err := cat.Store.CleanAppCaches(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "warning: cleaning up photo apps' copies: %v (retried on the next run)\n", err)
}
if cres.Removed > 0 || cres.Kept > 0 {
fmt.Fprintf(os.Stderr, "app copies: removed %d thumbnails and previews of photo apps (moved %d face names, %d ratings to the photos they copy); kept %d (no other copy, or hand-named faces or ratings on them)\n",
cres.Removed, cres.LabelsMoved, cres.FeedbackMoved, cres.Kept)
var pj *pruneJob
if *prune && runErr == nil {
pj = &pruneJob{folders: asked, notReady: notReady, gaps: ix.Stats.Gaps.Load()}
Comment thread
sgoggins marked this conversation as resolved.
Resolved
}
cleanUpAfterIndex(ctx, cat.Store, pj, os.Stderr)
}
if !*noMatch && ctx.Err() == nil {
// The photos are indexed either way; a failure here only means named
Expand Down Expand Up @@ -991,6 +983,9 @@ func runPrune(g *globals, args []string) error {
verb = "would remove"
}
fmt.Fprintf(os.Stderr, "%s %d entries\n", verb, len(res.Gone))
if m := movedToTwins(res); m != "" {
fmt.Fprintln(os.Stderr, m)
}
if len(res.Held) > 0 {
fmt.Fprintf(os.Stderr, "kept %d folder(s) whose files are all missing and that are gone or empty — an offline drive looks the same:\n", len(res.Held))
for _, d := range res.Held {
Expand Down
141 changes: 141 additions & 0 deletions cmd/archivis/prune.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package main

import (
"context"
"fmt"
"io"
"os"
"strings"

"github.com/auteursoft/archivis/internal/store"
)

// folderProblem says why a folder to index can't be trusted to show which
// of its files were deleted, or "" if it can. A drive that isn't mounted
// leaves its folder gone, or an empty mount point; one the service may not
// read (no Full Disk Access) can't be listed. A folder that is a link is
// judged by the folder it points to, which the indexer walks.
func folderProblem(dir string) string {
st, err := os.Stat(dir)
switch {
case err != nil && os.IsNotExist(err):
return "is not there (drive not mounted?)"
case err != nil:
return fmt.Sprintf("can't be read: %v", err)
case !st.IsDir():
return "is not a folder"
}
f, err := os.Open(dir)
if err != nil {
return fmt.Sprintf("can't be read: %v (Full Disk Access?)", err)
}
defer f.Close()
names, err := f.Readdirnames(1)
if len(names) == 0 {
if err != nil && err != io.EOF {
return fmt.Sprintf("can't be read: %v (Full Disk Access?)", err)
}
return "is empty (drive not mounted?)"
}
return ""
}

// pruneAfterIndex (index --prune) removes the catalogue entries of files
// deleted from the folders just indexed. It runs after a complete index and
// its clean-ups, so moved and renamed files already have their new paths
// and copies' names and ratings are on their originals, and only when the
// run saw everything: every folder the job names was ready when it started
// (atStart holds those that weren't, with why) and still is, and the run
// read and recorded every file (gaps is 0). Otherwise it logs an error with
// each reason and prunes nothing, keeping those photos until a run that
// sees everything (after a restart, several drives can be late). Prune
// itself also keeps any folder whose files are all gone and that is itself
// gone or empty.
func pruneAfterIndex(st *store.Store, folders []string, atStart map[string]string, gaps int64, w io.Writer, also ...string) (store.PruneResult, bool) {
reasons := append([]string{}, also...)
for _, f := range folders {
if p, ok := atStart[f]; ok {
reasons = append(reasons, fmt.Sprintf("%s: when indexing started, it %s", f, p))
} else if p := folderProblem(f); p != "" {
reasons = append(reasons, fmt.Sprintf("%s %s", f, p))
}
}
if gaps > 0 {
reasons = append(reasons, fmt.Sprintf("this run could not read or record %d folders or files (see the warnings and errors above)", gaps))
}
if len(reasons) > 0 {
fmt.Fprintf(w, "error: not removing deleted photos, because this run may not have seen them all:\n %s\n Their photos stay in the catalogue; deleted ones are removed after a run that finds every folder and reads every file.\n",
strings.Join(reasons, "\n "))
Comment thread
sgoggins marked this conversation as resolved.
Resolved
return store.PruneResult{}, false
}
res, err := st.PruneSparingCopies(folders)
if err != nil {
fmt.Fprintf(w, "error: removing deleted photos: %v (retried on the next run)\n", err)
return res, false
}
fmt.Fprintf(w, "pruned: removed %d deleted photos from the catalogue", len(res.Gone))
if m := movedToTwins(res); m != "" {
fmt.Fprintf(w, "; %s", m)
}
if len(res.Spared) > 0 {
fmt.Fprintf(w, "; kept %d copies photo apps made, whose hand-given names, ratings or stars would go with them (archivis prune removes them)", len(res.Spared))
}
if len(res.Held) > 0 {
fmt.Fprintf(w, "; kept %d folders whose files are all missing and that are gone or empty, as an offline drive looks (archivis prune --all-missing removes them): %s",
len(res.Held), strings.Join(res.Held, ", "))
}
fmt.Fprintln(w)
return res, true
}

// pruneJob is what index --prune needs once the run is over.
type pruneJob struct {
folders []string // the folders the job names
notReady map[string]string // those not ready as indexing started, and why
gaps int64 // what the run could not read or record
}

// cleanUpAfterIndex removes the copies photo apps keep (moving their face
// names and ratings to the photos they copy), then, for index --prune
// (pj not nil), the photos deleted from the folders indexed. In that
// order: a copy whose file is gone, among others still there, would lose
// its names and ratings if pruned first. Before auto-labelling, so moved
// names count as examples and deleted photos' faces don't.
func cleanUpAfterIndex(ctx context.Context, st *store.Store, pj *pruneJob, w io.Writer) {
// Apple's copies catalogued from inside Photos libraries by older
// versions: removed once their originals are in (names moved first)
var failed []string // a copy whose names and ratings weren't moved must not be pruned
res, err := st.CleanPhotosLibraries(ctx)
if err != nil {
fmt.Fprintf(w, "warning: cleaning up Photos library copies: %v (retried on the next run)\n", err)
failed = append(failed, "the clean-up of Photos library copies failed (see the warning above); their names and ratings must be moved before pruning")
}
if res.Removed > 0 || res.Kept > 0 {
fmt.Fprintf(w, "Photos libraries: removed %d of Apple's copies (moved %d face names, %d ratings to the originals); kept %d with no original catalogued\n",
res.Removed, res.LabelsMoved, res.FeedbackMoved, res.Kept)
}
// then any app copies left: Photos copies with a twin elsewhere,
// iPhoto, Aperture and Capture One caches
cres, err := st.CleanAppCaches(ctx)
if err != nil {
fmt.Fprintf(w, "warning: cleaning up photo apps' copies: %v (retried on the next run)\n", err)
failed = append(failed, "the clean-up of photo apps' copies failed (see the warning above); their names and ratings must be moved before pruning")
}
if cres.Removed > 0 || cres.Kept > 0 {
fmt.Fprintf(w, "app copies: removed %d thumbnails and previews of photo apps (moved %d face names, %d ratings to the photos they copy); kept %d (no other copy, or hand-named faces or ratings on them)\n",
cres.Removed, cres.LabelsMoved, cres.FeedbackMoved, cres.Kept)
}
if pj != nil && ctx.Err() == nil {
pruneAfterIndex(st, pj.folders, pj.notReady, pj.gaps, w, failed...)
Comment thread
sgoggins marked this conversation as resolved.
Resolved
}
}

// movedToTwins says what prune handed from removed photos to identical
// photos still there, or "" if nothing.
func movedToTwins(res store.PruneResult) string {
if res.LabelsMoved+res.RatingsMoved+res.StarsMoved == 0 {
return ""
}
return fmt.Sprintf("moved %d face names, %d ratings and %d stars to identical photos still there",
res.LabelsMoved, res.RatingsMoved, res.StarsMoved)
}
Loading
Loading