Skip to content

Commit

Permalink
sha256sum,md5sum: return string instead of char, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
scivision committed Jan 31, 2022
1 parent 0bd08fa commit 9d91f97
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 13 deletions.
9 changes: 3 additions & 6 deletions +stdlib/+fileio/md5sum.m
Expand Up @@ -9,23 +9,20 @@
file = expanduser(file);
assert(isfile(file), '%s not found', file)

hash = string.empty;

if ismac
[stat,hash] = system("md5 -r " + file);
elseif isunix
[stat,hash] = system("md5sum " + file);
elseif ispc
[stat,hash] = system("CertUtil -hashfile " + file + " MD5");
else
return
error("no sha256sum method for your OS")
end

if stat ~= 0
return
end
assert(stat == 0, hash)

hash = regexp(hash,'^\w{32}','match','once','lineanchors');
hash = string(hash);

assert(strlength(hash)==32, 'md5 hash is 32 characters')

Expand Down
9 changes: 3 additions & 6 deletions +stdlib/+fileio/sha256sum.m
Expand Up @@ -9,23 +9,20 @@
file = expanduser(file);
assert(isfile(file), '%s not found', file)

hash = string.empty;

if ismac
[stat,hash] = system("shasum --algorithm 256 --binary " + file);
elseif isunix
[stat,hash] = system("sha256sum --binary " + file);
elseif ispc
[stat,hash] = system("CertUtil -hashfile " + file + " SHA256");
else
return
error("no md5sum method for your OS")
end

if stat ~= 0
return
end
assert(stat == 0, hash)

hash = regexp(hash,'^\w{64}','match','once','lineanchors');
hash = string(hash);

assert(strlength(hash)==64, 'SHA256 hash is 64 characters')

Expand Down
15 changes: 15 additions & 0 deletions +stdlib/TestFileio.m
Expand Up @@ -142,6 +142,21 @@ function test_copyfile(tc)
tc.verifyThat(fullfile(tempdir, name), IsFile)
end

function test_hash(tc)
import matlab.unittest.constraints.IsFile

fn = tempname;
fid = fopen(fn, "w");
tc.assumeGreaterThan(fid, 0);
fprintf(fid, "hello");
fclose(fid);
tc.assumeThat(fn, IsFile)

tc.verifyEqual(stdlib.fileio.md5sum(fn), "5d41402abc4b2a76b9719d911017c592")
tc.verifyEqual(stdlib.fileio.sha256sum(fn), "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824")

delete(fn)
end

end
end
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Expand Up @@ -8,7 +8,8 @@ on:


jobs:
linux:

matlab:
timeout-minutes: 15
runs-on: ${{ matrix.os }}

Expand Down

0 comments on commit 9d91f97

Please sign in to comment.