main 7b4bf98ed142 cached
12 files
30.5 KB
7.9k tokens
1 requests
Download .txt
Repository: eamonnsullivan/backup-scripts
Branch: main
Commit: 7b4bf98ed142
Files: 12
Total size: 30.5 KB

Directory structure:
gitextract_rdf3vcgg/

├── .gitignore
├── LICENSE
├── LaunchAgent/
│   ├── README.md
│   └── backup.workmac.plist
├── README.md
├── anacron/
│   ├── README.md
│   └── backup
├── server/
│   ├── README.md
│   └── backup-thinkpad.sh
├── src/
│   └── eamonnsullivan/
│       └── backup.clj
├── test/
│   └── eamonnsullivan/
│       └── backup_test.clj
└── test_runner.clj

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
.cider-repl-history
.clj-kondo/
.cpcache/


================================================
FILE: LICENSE
================================================
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM
CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.

1. DEFINITIONS

"Contribution" means:

a) in the case of the initial Contributor, the initial code and
documentation distributed under this Agreement, and

b) in the case of each subsequent Contributor:

i) changes to the Program, and

ii) additions to the Program;

where such changes and/or additions to the Program originate from and are
distributed by that particular Contributor. A Contribution 'originates' from
a Contributor if it was added to the Program by such Contributor itself or
anyone acting on such Contributor's behalf. Contributions do not include
additions to the Program which: (i) are separate modules of software
distributed in conjunction with the Program under their own license
agreement, and (ii) are not derivative works of the Program.

"Contributor" means any person or entity that distributes the Program.

"Licensed Patents" mean patent claims licensable by a Contributor which are
necessarily infringed by the use or sale of its Contribution alone or when
combined with the Program.

"Program" means the Contributions distributed in accordance with this
Agreement.

"Recipient" means anyone who receives the Program under this Agreement,
including all Contributors.

2. GRANT OF RIGHTS

a) Subject to the terms of this Agreement, each Contributor hereby grants
Recipient a non-exclusive, worldwide, royalty-free copyright license to
reproduce, prepare derivative works of, publicly display, publicly perform,
distribute and sublicense the Contribution of such Contributor, if any, and
such derivative works, in source code and object code form.

b) Subject to the terms of this Agreement, each Contributor hereby grants
Recipient a non-exclusive, worldwide, royalty-free patent license under
Licensed Patents to make, use, sell, offer to sell, import and otherwise
transfer the Contribution of such Contributor, if any, in source code and
object code form.  This patent license shall apply to the combination of the
Contribution and the Program if, at the time the Contribution is added by the
Contributor, such addition of the Contribution causes such combination to be
covered by the Licensed Patents. The patent license shall not apply to any
other combinations which include the Contribution. No hardware per se is
licensed hereunder.

c) Recipient understands that although each Contributor grants the licenses
to its Contributions set forth herein, no assurances are provided by any
Contributor that the Program does not infringe the patent or other
intellectual property rights of any other entity. Each Contributor disclaims
any liability to Recipient for claims brought by any other entity based on
infringement of intellectual property rights or otherwise. As a condition to
exercising the rights and licenses granted hereunder, each Recipient hereby
assumes sole responsibility to secure any other intellectual property rights
needed, if any. For example, if a third party patent license is required to
allow Recipient to distribute the Program, it is Recipient's responsibility
to acquire that license before distributing the Program.

d) Each Contributor represents that to its knowledge it has sufficient
copyright rights in its Contribution, if any, to grant the copyright license
set forth in this Agreement.

3. REQUIREMENTS

A Contributor may choose to distribute the Program in object code form under
its own license agreement, provided that:

a) it complies with the terms and conditions of this Agreement; and

b) its license agreement:

i) effectively disclaims on behalf of all Contributors all warranties and
conditions, express and implied, including warranties or conditions of title
and non-infringement, and implied warranties or conditions of merchantability
and fitness for a particular purpose;

ii) effectively excludes on behalf of all Contributors all liability for
damages, including direct, indirect, special, incidental and consequential
damages, such as lost profits;

iii) states that any provisions which differ from this Agreement are offered
by that Contributor alone and not by any other party; and

iv) states that source code for the Program is available from such
Contributor, and informs licensees how to obtain it in a reasonable manner on
or through a medium customarily used for software exchange.

When the Program is made available in source code form:

a) it must be made available under this Agreement; and

b) a copy of this Agreement must be included with each copy of the Program.

Contributors may not remove or alter any copyright notices contained within
the Program.

Each Contributor must identify itself as the originator of its Contribution,
if any, in a manner that reasonably allows subsequent Recipients to identify
the originator of the Contribution.

4. COMMERCIAL DISTRIBUTION

Commercial distributors of software may accept certain responsibilities with
respect to end users, business partners and the like. While this license is
intended to facilitate the commercial use of the Program, the Contributor who
includes the Program in a commercial product offering should do so in a
manner which does not create potential liability for other Contributors.
Therefore, if a Contributor includes the Program in a commercial product
offering, such Contributor ("Commercial Contributor") hereby agrees to defend
and indemnify every other Contributor ("Indemnified Contributor") against any
losses, damages and costs (collectively "Losses") arising from claims,
lawsuits and other legal actions brought by a third party against the
Indemnified Contributor to the extent caused by the acts or omissions of such
Commercial Contributor in connection with its distribution of the Program in
a commercial product offering.  The obligations in this section do not apply
to any claims or Losses relating to any actual or alleged intellectual
property infringement. In order to qualify, an Indemnified Contributor must:
a) promptly notify the Commercial Contributor in writing of such claim, and
b) allow the Commercial Contributor tocontrol, and cooperate with the
Commercial Contributor in, the defense and any related settlement
negotiations. The Indemnified Contributor may participate in any such claim
at its own expense.

For example, a Contributor might include the Program in a commercial product
offering, Product X. That Contributor is then a Commercial Contributor. If
that Commercial Contributor then makes performance claims, or offers
warranties related to Product X, those performance claims and warranties are
such Commercial Contributor's responsibility alone. Under this section, the
Commercial Contributor would have to defend claims against the other
Contributors related to those performance claims and warranties, and if a
court requires any other Contributor to pay any damages as a result, the
Commercial Contributor must pay those damages.

5. NO WARRANTY

EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON
AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A
PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the
appropriateness of using and distributing the Program and assumes all risks
associated with its exercise of rights under this Agreement , including but
not limited to the risks and costs of program errors, compliance with
applicable laws, damage to or loss of data, programs or equipment, and
unavailability or interruption of operations.

6. DISCLAIMER OF LIABILITY

EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY
CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGES.

7. GENERAL

If any provision of this Agreement is invalid or unenforceable under
applicable law, it shall not affect the validity or enforceability of the
remainder of the terms of this Agreement, and without further action by the
parties hereto, such provision shall be reformed to the minimum extent
necessary to make such provision valid and enforceable.

If Recipient institutes patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Program itself
(excluding combinations of the Program with other software or hardware)
infringes such Recipient's patent(s), then such Recipient's rights granted
under Section 2(b) shall terminate as of the date such litigation is filed.

All Recipient's rights under this Agreement shall terminate if it fails to
comply with any of the material terms or conditions of this Agreement and
does not cure such failure in a reasonable period of time after becoming
aware of such noncompliance. If all Recipient's rights under this Agreement
terminate, Recipient agrees to cease use and distribution of the Program as
soon as reasonably practicable. However, Recipient's obligations under this
Agreement and any licenses granted by Recipient relating to the Program shall
continue and survive.

Everyone is permitted to copy and distribute copies of this Agreement, but in
order to avoid inconsistency the Agreement is copyrighted and may only be
modified in the following manner. The Agreement Steward reserves the right to
publish new versions (including revisions) of this Agreement from time to
time. No one other than the Agreement Steward has the right to modify this
Agreement. The Eclipse Foundation is the initial Agreement Steward. The
Eclipse Foundation may assign the responsibility to serve as the Agreement
Steward to a suitable separate entity. Each new version of the Agreement will
be given a distinguishing version number. The Program (including
Contributions) may always be distributed subject to the version of the
Agreement under which it was received. In addition, after a new version of
the Agreement is published, Contributor may elect to distribute the Program
(including its Contributions) under the new version. Except as expressly
stated in Sections 2(a) and 2(b) above, Recipient receives no rights or
licenses to the intellectual property of any Contributor under this
Agreement, whether expressly, by implication, estoppel or otherwise. All
rights in the Program not expressly granted under this Agreement are
reserved.

This Agreement is governed by the laws of the State of New York and the
intellectual property laws of the United States of America. No party to this
Agreement will bring a legal action under this Agreement more than one year
after the cause of action arose. Each party waives its rights to a jury trial
in any resulting litigation.


================================================
FILE: LaunchAgent/README.md
================================================
# Example launchd.plist

This is an example of a configuration file that goes in `~/Library/LaunchAgents/` on the Mac. See the main page for `launchd.plist` for more about the format.


================================================
FILE: LaunchAgent/backup.workmac.plist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>backup.workmac</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/ssh</string>
        <string>einstein.local</string>
        <string>/media/backup/backup-workmac.sh</string>
    </array>
    <key>KeepAlive</key>
    <dict>
      <key>SuccessfulExit</key>
      <false/>
    </dict>
    <key>ThrottleInterval</key>
    <integer>60</integer>
    <key>StartCalendarInterval</key>
    <dict>
      <key>Minute</key>
      <integer>0</integer>
      <key>Hour</key>
      <integer>11</integer>
    </dict>
    <key>StandardOutPath</key>
    <string>/usr/local/var/log/backup-workmac.log</string>
    <key>StandardErrorPath</key>
    <string>/usr/local/var/log/backup-workmac.log</string>
</dict>
</plist>


================================================
FILE: README.md
================================================
# My backup scripts

These are my current scripts for backing up three laptops around the house to a desktop PC. It is also a small experiment in using [babashka](https://github.com/babashka/babashka), a scripting flavour of the Clojure language.

I had never used babaskha, so this is very unlikely to be a good example for anyone else. For much better information and examples, see babashka's [online book](https://book.babashka.org/#introduction).

## Main goals and outcomes

The main reason I was revisiting my home backup scripts it that we've transitioned over the years from a household of two or three standard PCs, to one with three laptops.

I used to mirror my family's home directories to an external drive. I used Time Machine on the Mac and [cron](http://manpages.ubuntu.com/manpages/focal/en/man3/cron.3tcl.html) and [rsync](http://manpages.ubuntu.com/manpages/focal/man1/rsync.1.html) on Linux. That mostly just worked.

Laptops are a new challenge, though. You can't just go around with an external drive hanging off them. They're often sleeping, with the lid down, on a sofa somewhere and (unless it's the work laptop) used intermittently.

My solution, at the moment, is to back up centrally (using the [server-side script](src/eamonnsullivan/backup.clj) that is the main focus of this repo), but have the laptops initiate the process by running small shell scripts over ssh. I'm using [anacron](http://manpages.ubuntu.com/manpages/focal/man8/anacron.8.html) on Ubuntu and launchctl/launchd on the Mac to configure the laptops to back themselves up once a day.

### Why do I still need backups?

That's a question worth considering. Why not just use Dropbox, Google Drive or whatever Apple's pushing these days? I do actually already use these things, plus Github for all of my source code.

But these aren't back up systems. If I accidentally delete an important file, for example, it's very shortly gone from these systems as well.

Also, my wife (who doesn't use Dropbox or anything like it) keeps her entire digital life (word processing documents, presentation, spreadsheets, etc.) on a Thinkpad running Ubuntu. She counts on me to keep those safe. (Well, actually, she just assumes they are safe... I'm the IT Guy in the house and it's my job to worry about such things.)

Mostly, though, I like having control over my own data and I want to understand how it is being stored and moved around. I will probably extend this system to the cloud in the future -- periodically sending monthly backups offsite -- but I will likely use S3 on my own AWS account for that, keeping it under my understanding and control.

## Prerequisites

You'll need a PC that's either always on or reliably turned on when it's needed. It will need plenty of disk storage. A Raspberry Pi 4 with an attached USB disk is what I use at the moment. I installed the ARM port of Ubuntu server on it, and babashka now has ARM support as well.

I use a 1TB SSD USB disk, mounted permanently at /media/backup. Here's [one random guide](https://www.techrepublic.com/article/how-to-properly-automount-a-drive-in-ubuntu-linux/) on how to mount an external disk automatically on boot.

You will also need to set up password-less SSH access, both from the back up PC to the devices, and from the devices to the back up PC. This will allow the back up PC to run rsync to the devices, and also allow to the devices to kick off the process by running a small shell script via SSH. There are a lot of guides on the Internet for this, such as [this one](https://linuxize.com/post/how-to-setup-passwordless-ssh-login/).

I don't use Windows at the moment and don't really mount network drives, either. That might be a good alternative to consider.

## Back up approach

I used to just mirror everyone's home directory on another device. Just periodically run rsync and sync all of the files to the external hard drive. This works, but it has a couple of disadvantages. One important disadvantage is that if you delete a file on Tuesday and discover on Thursday that you really actually needed that file, it's probably now gone from the back up, as well.

So, instead I took a cue from Apple's Time Machine and take advantage of hard links, a relatively underused facility in most Unix based file systems. Basically, it just gives the file another name, somewhere else. If you delete one of the names, the same file still lives under the other name. And hard links don't take up any extra space (or hardly any).

I also mitigate against creeping bad sectors (which happen even on SSDs) by periodically starting over again with a fresh, full back up.

The basic algorithm:

 1. Run rsync to sync the files from one place to another.
 1. Make a hard link of all of the files to another location on the file system, under a directory with the date in the name.
 1. Check the remaining free space on the back up device and compare it with the last full back I just did. If free space is less than twice the size of the last backup, I start removing the oldest backups (the ones created in the last step) until I have that much remaining.
 1. Once a month, I start a new full back up from scratch. This is to guard against bad sectors in the disk, which can make older files become unreadable, and you would never know until you tried to restore it.

## Example scripts

 * [LaunchAgent on the Mac laptop](LaunchAgent/)
 * [Anacron script for the Ubuntu laptops](anacron/)
 * [Starter script on the server](server/)
 * [Main back up script](src/eamonnsullivan/backup.clj)

## License

Copyright © 2021 Eamonn Sullivan

Distributed under the Eclipse Public License version 1.0.


================================================
FILE: anacron/README.md
================================================
# Example Anacron script

This is an example of a script you would place in `/etc/cron.daily` to initiate the back up. The laptop will try running this script once a day, when it wakes up.

For this to work, you will need password-less access to the back up PC over ssh.


================================================
FILE: anacron/backup
================================================
#!/bin/sh

/usr/bin/ssh einstein.local /media/backup/backup-thinkpad.sh
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t backup "ALERT exited abnormally with [$EXITVALUE]"
fi
exit $EXITVALUE


================================================
FILE: server/README.md
================================================
# Sample Start script for the service

This is an example of a very short bash script that sits on the service. It's only real purpose is to make the ssh command from the laptop simpler. The laptops just call a script like this, which in turn calls the main back up script.


================================================
FILE: server/backup-thinkpad.sh
================================================
#!/usr/bin/env bash

/media/backup/backup.clj root@thinkpad.local:/home thinkpad >>/var/log/backups/backup_thinkpad.log 2>&1


================================================
FILE: src/eamonnsullivan/backup.clj
================================================
#!/usr/bin/env bb

(ns eamonnsullivan.backup
  "A wrapper around rsync that manages multiple backups of multiple
  hosts. After each backup, it creates a hard link (effectively
  creating a snapshot of the current difference since the previous
  backup) and checks the free space available on the storage
  device. If free space is less than double the size of the most
  recent backup, we remove older backups.

  At the start of a new month, we begin a fresh backup. This is to
  avoid any potential issues with bad sectors.

  Usage: <backup-from> <name-of-backup>

  Examples: backup.clj root@thinkpad.local:/home thinkpad
            backup.clj sullie09@mc-s105910.local:~ workmac"
  {:author "Eamonn Sullivan"}
  (:import (java.time.format DateTimeFormatter)
           (java.time LocalDateTime))
  (:require [clojure.java.io :as io]
            [clojure.java.shell :refer [sh]]
            [clojure.string :as string]
            [babashka.fs :as fs]))

(def ^:dynamic *base-path* "/media/backup")
(def ^:dynamic *rsync-command* ["rsync" "-avzpH" "--partial" "--delete" "--exclude-from=/etc/rsync-backup-excludes.txt"])

(def month-formatter (DateTimeFormatter/ofPattern "yyyy-MM"))
(def date-time-formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd_HH-mm-s"))

(defn retry
  "Retry function f, n times and check whether it succeeded with the
  predicate success?"
  ([f success? num-retries]
   (retry f success? num-retries 30000))
  ([f success? num-retries wait-time]
  (if (zero? num-retries)
    (f)
    (let [result (f)]
      (if (not (success? result))
        (do
          (println (format "Function failed with error [%s], retrying" (:err result)))
          (Thread/sleep wait-time)
          (retry f success? (dec num-retries) wait-time))
        result)))))

(defn get-current-month
  "Get a string that includes the year and month."
  []
  (.format (LocalDateTime/now) month-formatter))

(defn link
  "Create a hard link from path to target."
  [path target]
  (sh "cp" "-al" path target))

(defn write-check-month-file
  "Write out the current year and month into a backup-specific file that
  we can compare against. Used so that we can more easily tell when
  we've changed months since the last backup."
  [content backup]
  (spit (format "%s/checkMonth_%s.txt" *base-path* backup) content))

(defn new-month?
  "Predicate: Given the contents of this backup's checkMonth file, are
  we creating the first back up of this month?"
  [last]
  (let [now (get-current-month)]
    (not= now last)))

(defn delete-backup
  "Remove the current named backup. This is normally done when we are
  starting the first backup of the month."
  [backup]
  (let [target (format "%s/%s" *base-path* backup)]
    (println "Removing: " target)
    (fs/delete-tree target)))

(defn get-backup-usage
  "How much disk space is this backup using?"
  [backup]
  (let [path (format "%s/%s" *base-path* backup)
        fsize (sh "du" "-sb" path)
        outsize (first (string/split (:out fsize) #"\s"))]
    (println "Size of current backup: " outsize)
    (bigint (string/trim outsize))))

(defn check-month
  "Check whether we've started a new month. If we have, create a new
  backup from scratch."
  [backup]
  (let [check (io/as-file (format "%s/checkMonth_%s.txt" *base-path* backup))
        last (if (.exists check) (slurp check) nil)]
    (when (new-month? last)
      (println (format "Starting a new monthly backup set for %s" (format "%s/%s" *base-path* backup)))
      (let [backupdir (io/as-file (format "%s/%s" *base-path* backup))]
        (when (.exists backupdir)
          (println "Existing backup found, so removing..."  )
          (delete-backup backup))
        (io/make-parents (format "%s/.keep" (.getPath backupdir))))
      (write-check-month-file (get-current-month) backup))))

(defn make-hard-link
  "Make a hard link of the current back up."
  [backup bdir]
  (let [linkto (format "%s/old/%s" *base-path* bdir)
        linkfrom (format "%s/%s/" *base-path* backup)]
    (io/make-parents (io/as-file linkto))
    (link linkfrom linkto)))

(defn oldest-dir
  "Find the oldest (least most recently modified) directory in parent."
  [parent]
  (let [dirs (.listFiles (io/as-file parent))
        sorted (sort-by #(.lastModified %) dirs)]
    (first sorted)))

(defn delete-oldest-backup
  "Find the oldest backup hard linked in <base-path>/old and remove it."
  []
  (let [dir (.getName (oldest-dir (format "%s/old" *base-path*)))]
    (println "Oldest backup: " dir)
    (if (not (nil? dir))
      (sh "bash" "-c" (format "rm -rf %s/old/%s" *base-path* dir))
      (throw (ex-info "Could not remove any more old backups!" {:base-path *base-path*})))))

(defn check-free
  "Check the free space on the backup device. If it isn't at
  least twice the size of the last (current) backup, delete the oldest
  backup and try again. Repeat until enough space."
  [backup]
  (let [curr-used (get-backup-usage backup)
        est-need (* curr-used 2)]
    (println "The current back up is using " curr-used)
    (println "We're estimating that we need: " est-need)
    (loop [curr-free (.getFreeSpace (io/as-file *base-path*))]
      (println "Current free space on this device: " curr-free)
      (if (> curr-free est-need)
        true
        (do
          (println "Not enough disk space available, so removing the oldest backup.")
          (delete-oldest-backup)
          (recur (.getFreeSpace (io/as-file *base-path*))))))))

(defn rsync!
  "The actual rsync of files from somewhere, to somewhere else. This
  returns a map of the :exit code, standard output (:out) and any :err
  output."
  [backup-from backup-to]
  (let [rsync-command (into [] (conj *rsync-command* backup-from (format "%s/%s" *base-path* backup-to)))]
    (println "Starting rsync: " (string/join " " rsync-command))
    (apply sh rsync-command)))

(defn -main
  []
  (let [[backup-from backup-to] *command-line-args*]
    (when (or (not backup-from) (not backup-to))
      (println "Usage: <user@hostname.local:/home> <backup-name>")
      (System/exit 1))
    (println (format "Starting backup of %s to %s on %s" backup-from backup-to (.toString (LocalDateTime/now))))
    (check-month backup-to)
    (let [result (retry #(rsync! backup-from backup-to) #(= 0 (:exit %)) 3)]
      (if (= 0 (:exit result))
        (do
          (println (:out result))
          (make-hard-link backup-to (format "%s-%s" (.format (LocalDateTime/now) date-time-formatter) backup-to))
          (check-free backup-to)
          (println (format "Successfully finished backup of %s at %s" backup-from (.toString (LocalDateTime/now)))))
        (do
          (println (format "The backup of %s ended in an error: %s" backup-from (:err result)))
          (println "Not making a hard link or checking free space.")))
      (System/exit (:exit result)))))

(when (= *file* (System/getProperty "babashka.file"))
  (-main))


(comment
  (import (java.time.format DateTimeFormatter))
  (import (java.time LocalDateTime))
  (require '[clojure.java.io :as io])
  (require '[clojure.java.shell :refer [sh]])
  (def *base-path* "/home/eamonn/backup-test")
  )


================================================
FILE: test/eamonnsullivan/backup_test.clj
================================================
#!/usr/bin/env bb

(ns eamonnsullivan.backup-test
  {:author "Eamonn Sullivan"}
  (:import (java.time LocalDateTime))
  (:require [eamonnsullivan.backup :as sut]
            [babashka.fs :as fs]
            [clojure.java.io :as io]
            [clojure.test :as t :refer [deftest testing is]]))

(def cwd (fs/real-path "."))

(defn temp-dir []
  (-> (fs/create-temp-dir)
      (fs/delete-on-exit)))

(deftest test-new-month?
  (with-redefs [sut/get-current-month (fn [] "2020-01")]
    (testing "compares the year and month"
      (is (= false
             (sut/new-month? "2020-01"))))))

(deftest retry-test
  (testing "should retry the specified number of times"
    (is (= 4 ;; first, then three retries.
           (let [attempts-count (volatile! 0)
                 _ (sut/retry #(vswap! attempts-count inc) :continue 3 100)]
             @attempts-count))))
  (testing "should stop retrying when predicate returns true"
    (is (= 3
           (let [attempts-count (volatile! 0)
                 _ (sut/retry #(vswap! attempts-count inc) (fn [_] (< 2 @attempts-count)) 5 100)]
             @attempts-count)))))

(deftest test-link
  (let [tmp-dir (temp-dir)
        dir (str (fs/create-dir (fs/path tmp-dir "foo")))
        _ (spit (fs/file tmp-dir "foo/" "dudette.txt") "some content")
        linkto (str tmp-dir "/bar")
        _ (sut/link dir linkto)]
    (is (.exists (fs/file tmp-dir "foo")))
    (is (.exists (fs/file tmp-dir "bar")))
    (is (.exists (fs/file tmp-dir "bar/" "dudette.txt")))
    (is (= (slurp (fs/file tmp-dir "foo/" "dudette.txt"))
           (slurp (fs/file tmp-dir "bar/" "dudette.txt"))))
    (is (= 2 (fs/get-attribute (fs/file tmp-dir "bar/" "dudette.txt")
                               "unix:nlink")))))

(deftest test-delete-backup
  (let [tmp-dir (temp-dir)
        _ (fs/create-dir (fs/path tmp-dir "foo"))
        _ (fs/create-dir (fs/path tmp-dir "bar"))
        _ (spit (fs/file tmp-dir "bar/" "something.txt") "with content")
        _ (spit (fs/file tmp-dir "foo/" "dude.txt") "some content")]
    (binding [sut/*base-path* tmp-dir]
      (sut/delete-backup "foo")
      (is (.exists (fs/file tmp-dir "bar")))
      (is (not (.exists (fs/file tmp-dir "foo")))))))

(deftest test-get-backup-usage
  (let [tmp-dir (temp-dir)
        _ (fs/create-dir (fs/path tmp-dir "foo"))
        _ (spit (fs/file tmp-dir "foo/" "content.txt") "123\n")]
    (binding [sut/*base-path* tmp-dir]
      (is (= 4100
             (sut/get-backup-usage "foo"))))))

(deftest test-check-month
  (let [tmp-dir (temp-dir)
        _ (fs/create-dir (fs/path tmp-dir "foo"))
        _ (spit (fs/file tmp-dir "foo/" "content.txt") "123")
        _ (spit (fs/file tmp-dir "checkMonth_foo.txt") "456")]
    (binding [sut/*base-path* tmp-dir]
      (with-redefs [sut/new-month? (fn [_] false)]
        (testing "does not delete current backup if the month hasn't changed"
          (sut/check-month "foo")
          (is (.exists (fs/file tmp-dir "foo")))))
      (with-redefs [sut/new-month? (fn [_] true)
                    sut/get-current-month (fn [] "789")]
        (testing "removes current backup and writes new checkMonth file when month changes"
          (sut/check-month "foo")
          (is (not (.exists (fs/file tmp-dir "foo/" "content.txt"))))
          (is (= "789"
                 (slurp (fs/file tmp-dir "checkMonth_foo.txt")))))))))

(deftest test-make-hard-link
  (let [tmp-dir (temp-dir)
        _ (fs/create-dir (fs/path tmp-dir "foo"))
        _ (spit (fs/file tmp-dir "foo/" "content.txt") "123")]
    (binding [sut/*base-path* tmp-dir]
      (testing "makes a hard-link under /old of the current backup"
        (sut/make-hard-link "foo" "foo-123")
        (is (.exists (fs/file tmp-dir "old/foo-123/" "content.txt")))))))

(deftest test-oldest-dir
  ;; My slower Linux system seems to need the sleeps...
  (let [tmp-dir (temp-dir)
        _ (fs/create-dir (fs/path tmp-dir "one"))
        _ (Thread/sleep 10)
        _ (fs/create-dir (fs/path tmp-dir "two"))
        _ (Thread/sleep 10)
        _ (fs/create-dir (fs/path tmp-dir "three"))]
    (testing "should find oldest directory by last modified"
      (is (= (fs/path tmp-dir "one")
             (fs/path (sut/oldest-dir (str tmp-dir))))))))

(deftest test-delete-oldest-backup
  (let [tmp-dir (temp-dir)
        _ (fs/create-dir (fs/path tmp-dir "old"))
        _ (fs/create-dir (fs/path tmp-dir "old/" "one"))
        _ (Thread/sleep 10)
        _ (fs/create-dir (fs/path tmp-dir "old/" "two"))
        _ (Thread/sleep 10)
        _ (fs/create-dir (fs/path tmp-dir "old/" "three"))]
    (testing "should remove the old directory under /old"
      (binding [sut/*base-path* tmp-dir]
        (sut/delete-oldest-backup)
        (is (not (.exists (fs/file tmp-dir "old/" "one"))))
        (is (.exists (fs/file tmp-dir "old/" "two")))
        (is (.exists (fs/file tmp-dir "old/" "three")))))))


================================================
FILE: test_runner.clj
================================================
#!/usr/bin/env bb

(require '[clojure.test :as t]
         '[babashka.classpath :as cp])

(cp/add-classpath "src:test")

(require 'eamonnsullivan.backup-test)

(def test-results
  (t/run-tests 'eamonnsullivan.backup-test))

(def failures-and-errors
  (let [{:keys [:fail :error]} test-results]
    (+ fail error)))

(System/exit failures-and-errors)
Download .txt
gitextract_rdf3vcgg/

├── .gitignore
├── LICENSE
├── LaunchAgent/
│   ├── README.md
│   └── backup.workmac.plist
├── README.md
├── anacron/
│   ├── README.md
│   └── backup
├── server/
│   ├── README.md
│   └── backup-thinkpad.sh
├── src/
│   └── eamonnsullivan/
│       └── backup.clj
├── test/
│   └── eamonnsullivan/
│       └── backup_test.clj
└── test_runner.clj
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (33K chars).
[
  {
    "path": ".gitignore",
    "chars": 42,
    "preview": ".cider-repl-history\n.clj-kondo/\n.cpcache/\n"
  },
  {
    "path": "LICENSE",
    "chars": 11218,
    "preview": "THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC\nLICENSE (\"AGREEMENT\"). ANY USE, REPRODUCTION"
  },
  {
    "path": "LaunchAgent/README.md",
    "chars": 184,
    "preview": "# Example launchd.plist\n\nThis is an example of a configuration file that goes in `~/Library/LaunchAgents/` on the Mac. S"
  },
  {
    "path": "LaunchAgent/backup.workmac.plist",
    "chars": 933,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
  },
  {
    "path": "README.md",
    "chars": 5652,
    "preview": "# My backup scripts\n\nThese are my current scripts for backing up three laptops around the house to a desktop PC. It is a"
  },
  {
    "path": "anacron/README.md",
    "chars": 271,
    "preview": "# Example Anacron script\n\nThis is an example of a script you would place in `/etc/cron.daily` to initiate the back up. T"
  },
  {
    "path": "anacron/backup",
    "chars": 207,
    "preview": "#!/bin/sh\n\n/usr/bin/ssh einstein.local /media/backup/backup-thinkpad.sh\nEXITVALUE=$?\nif [ $EXITVALUE != 0 ]; then\n    /u"
  },
  {
    "path": "server/README.md",
    "chars": 274,
    "preview": "# Sample Start script for the service\n\nThis is an example of a very short bash script that sits on the service. It's onl"
  },
  {
    "path": "server/backup-thinkpad.sh",
    "chars": 125,
    "preview": "#!/usr/bin/env bash\n\n/media/backup/backup.clj root@thinkpad.local:/home thinkpad >>/var/log/backups/backup_thinkpad.log "
  },
  {
    "path": "src/eamonnsullivan/backup.clj",
    "chars": 7131,
    "preview": "#!/usr/bin/env bb\n\n(ns eamonnsullivan.backup\n  \"A wrapper around rsync that manages multiple backups of multiple\n  hosts"
  },
  {
    "path": "test/eamonnsullivan/backup_test.clj",
    "chars": 4890,
    "preview": "#!/usr/bin/env bb\n\n(ns eamonnsullivan.backup-test\n  {:author \"Eamonn Sullivan\"}\n  (:import (java.time LocalDateTime))\n  "
  },
  {
    "path": "test_runner.clj",
    "chars": 350,
    "preview": "#!/usr/bin/env bb\n\n(require '[clojure.test :as t]\n         '[babashka.classpath :as cp])\n\n(cp/add-classpath \"src:test\")\n"
  }
]

About this extraction

This page contains the full source code of the eamonnsullivan/backup-scripts GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (30.5 KB), approximately 7.9k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!