Hi

I really like (when I save little data files) to have a simple versioning.
For example for my game collection I have
Games.1.ston
Games.2.ston
...
and I like that this is managed for me by the system.

I harvested this functionality from squeak long time ago.
I rewrote it fast and dirty in Pharo. I find this two methods super
handy and they provide cheap versioning for little files.



lastNameFor: baseFileName extension: extension
   "Assumes a file name includes a version number encoded as '.'
followed by digits
   preceding the file extension, e.g., games.22.ston
   Answer the file name with the largest number.
   If a version number is not found, raises an error"

   "FileSystem workingDirectory lastNameFor: 'games' extension: 'ston'"

    | files |
    files := self childrenMatching: baseFileName , '.*.' , extension.
    files ifEmpty: [ ^ self error: 'No file with number pattern' ].
    ^ (files asSortedCollection: [ :a :b | a basename < b basename ]) last

nextNameFor: baseFileName extension: extension
   "Assumes a file name includes a version number encoded as '.'
followed by digits
   preceding the file extension, e.g., games.22.ston
   Increment the version number (of the largest one) and answer the
new file name, e.g., games23.ston
   If a version number is not found, set the version to 1 and answer a
new file name"

    "FileSystem workingDirectory nextNameFor: 'games' extension: 'ston'"

    | files splits version |
    files := self childrenMatching: baseFileName , '.*.' , extension.
    files ifEmpty: [ ^ baseFileName , '.1.' , extension ].
    splits := files
         collect: [ :filename | filename basename splitOn: $. ]
         thenSelect: [ :split | (split at: 1) = baseFileName and: [
split size = 3 ] ].
     splits := splits asSortedCollection: [ :a :b | (a at: 2) < (b at: 2) ].
     version := splits isEmpty
        ifTrue: [ 1 ]
        ifFalse: [ (splits last at: 2) asNumber + 1 ].
     ^ baseFileName , '.' , version asString , '.' , extension

I think that these to methods can be a valuable addition to
fileReference (the methods can be better implemented).

Let me know what you think.

https://pharo.fogbugz.com/f/cases/20324/Handy-file-automatic-numbering

Stef

Reply via email to