Merge branch 'main' into fix_stat_redirect

This commit is contained in:
Jan Scheer
2022-05-12 19:13:47 +02:00
35 changed files with 1027 additions and 297 deletions
+9
View File
@@ -9,3 +9,12 @@ rustflags = [
"-Wclippy::single_char_pattern",
"-Wclippy::explicit_iter_loop",
]
[build]
# See https://github.com/time-rs/time/issues/293#issuecomment-1005002386. The
# unsoundness here is not in the `time` library, but in the Rust stdlib, and as
# such it needs to be fixed there.
rustflags = "--cfg unsound_local_offset"
[target.'cfg(target_os = "linux")']
rustflags = ["--cfg", "unsound_local_offset"]
+5
View File
@@ -5,3 +5,8 @@ updates:
schedule:
interval: "daily"
open-pull-requests-limit: 5
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 5
+23 -23
View File
@@ -24,7 +24,7 @@ jobs:
name: Style/cargo-deny
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: EmbarkStudios/cargo-deny-action@v1
style_deps:
@@ -43,7 +43,7 @@ jobs:
- { os: macos-latest , features: "feat_Tier1,feat_require_unix,feat_require_unix_utmpx" }
- { os: windows-latest , features: feat_os_windows }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Initialize workflow variables
id: vars
@@ -101,7 +101,7 @@ jobs:
job:
- { os: ubuntu-latest , features: feat_os_unix }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Initialize workflow variables
id: vars
@@ -165,7 +165,7 @@ jobs:
- { os: macos-latest , features: feat_os_macos }
- { os: windows-latest , features: feat_os_windows }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Initialize workflow variables
id: vars
@@ -223,7 +223,7 @@ jobs:
job:
- { os: ubuntu-latest , features: feat_os_unix }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Initialize workflow variables
id: vars
@@ -275,7 +275,7 @@ jobs:
# - { os: macos-latest , features: feat_os_macos }
# - { os: windows-latest , features: feat_os_windows }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Initialize workflow variables
id: vars
@@ -320,7 +320,7 @@ jobs:
job:
- { os: ubuntu-latest , features: feat_os_unix }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Initialize workflow variables
id: vars
@@ -384,9 +384,9 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: test
args: ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }} -p uucore -p coreutils
args: -v ${{ steps.vars.outputs.CARGO_FEATURES_OPTION }} -p uucore -p coreutils
env:
RUSTFLAGS: "-Awarnings"
RUSTFLAGS: "-Awarnings --cfg unsound_local_offset"
deps:
name: Dependencies
@@ -397,7 +397,7 @@ jobs:
job:
- { os: ubuntu-latest , features: feat_os_unix }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Install `rust` toolchain
uses: actions-rs/toolchain@v1
@@ -422,7 +422,7 @@ jobs:
job:
- { os: ubuntu-latest , features: feat_os_unix }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Install `rust` toolchain
uses: actions-rs/toolchain@v1
@@ -452,7 +452,7 @@ jobs:
- { os: macos-latest , features: feat_os_macos }
- { os: windows-latest , features: feat_os_windows }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Install `rust` toolchain
uses: actions-rs/toolchain@v1
@@ -478,7 +478,7 @@ jobs:
- { os: macos-latest , features: feat_os_macos }
- { os: windows-latest , features: feat_os_windows }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Install `rust` toolchain
uses: actions-rs/toolchain@v1
@@ -502,7 +502,7 @@ jobs:
job:
- { os: ubuntu-latest , features: feat_os_unix }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Install dependencies
shell: bash
@@ -534,7 +534,7 @@ jobs:
--arg size "$SIZE" \
--arg multisize "$SIZEMULTI" \
'{($date): { sha: $sha, size: $size, multisize: $multisize, }}' > size-result.json
- uses: actions/upload-artifact@v2
- uses: actions/upload-artifact@v3
with:
name: size-result
path: size-result.json
@@ -568,7 +568,7 @@ jobs:
- { os: windows-latest , target: x86_64-pc-windows-gnu , features: feat_os_windows } ## note: requires rust >= 1.43.0 to link correctly
- { os: windows-latest , target: x86_64-pc-windows-msvc , features: feat_os_windows }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Initialize workflow variables
id: vars
@@ -762,7 +762,7 @@ jobs:
args: --target=${{ matrix.job.target }} ${{ steps.vars.outputs.CARGO_TEST_OPTIONS}} ${{ matrix.job.cargo-options }} ${{ steps.dep_vars.outputs.CARGO_UTILITY_LIST_OPTIONS }}
toolchain: ${{ env.RUST_MIN_SRV }}
- name: Archive executable artifacts
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v3
with:
name: ${{ env.PROJECT_NAME }}-${{ matrix.job.target }}
path: target/${{ matrix.job.target }}/release/${{ env.PROJECT_NAME }}${{ steps.vars.outputs.EXE_suffix }}
@@ -820,7 +820,7 @@ jobs:
job:
- { os: ubuntu-latest }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Install/setup prerequisites
shell: bash
@@ -857,9 +857,9 @@ jobs:
env:
TERMUX: v0.118.0
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: AVD cache
uses: actions/cache@v2
uses: actions/cache@v3
id: avd-cache
with:
path: |
@@ -911,7 +911,7 @@ jobs:
env:
mem: 2048
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Prepare, build and test
## spell-checker:ignore (ToDO) sshfs usesh vmactions
@@ -979,7 +979,7 @@ jobs:
- { os: macos-latest , features: macos }
- { os: windows-latest , features: windows }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
# - name: Reattach HEAD ## may be needed for accurate code coverage info
# run: git checkout ${{ github.head_ref }}
@@ -1100,7 +1100,7 @@ jobs:
grcov . --output-type lcov --output-path "${COVERAGE_REPORT_FILE}" --branch --ignore build.rs --ignore "vendor/*" --ignore "/*" --ignore "[a-zA-Z]:/*" --excl-br-line "^\s*((debug_)?assert(_eq|_ne)?!|#\[derive\()"
echo ::set-output name=report::${COVERAGE_REPORT_FILE}
- name: Upload coverage results (to Codecov.io)
uses: codecov/codecov-action@v1
uses: codecov/codecov-action@v3
# if: steps.vars.outputs.HAS_CODECOV_TOKEN
with:
# token: ${{ secrets.CODECOV_TOKEN }}
+4 -4
View File
@@ -28,7 +28,7 @@ jobs:
job:
- { os: ubuntu-latest , features: feat_os_unix }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Initialize job variables
id: vars
@@ -80,7 +80,7 @@ jobs:
## * using the 'stable' toolchain is necessary to avoid "unexpected '--filter-platform'" errors
RUSTUP_TOOLCHAIN=stable cargo-tree tree --locked --all --no-dev-dependencies --no-indent --features ${{ matrix.job.features }} | grep -vE "$PWD" | sort --unique
- name: Commit any changes (to '${{ env.BRANCH_TARGET }}')
uses: EndBug/add-and-commit@v7
uses: EndBug/add-and-commit@v9
with:
branch: ${{ env.BRANCH_TARGET }}
default_author: github_actions
@@ -100,7 +100,7 @@ jobs:
job:
- { os: ubuntu-latest , features: feat_os_unix }
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v1
- name: Initialize job variables
id: vars
@@ -130,7 +130,7 @@ jobs:
# `cargo fmt` of tests
find tests -name "*.rs" -print0 | xargs -0 cargo fmt --
- name: Commit any changes (to '${{ env.BRANCH_TARGET }}')
uses: EndBug/add-and-commit@v7
uses: EndBug/add-and-commit@v9
with:
branch: ${{ env.BRANCH_TARGET }}
default_author: github_actions
+11 -11
View File
@@ -41,11 +41,11 @@ jobs:
TEST_FULL_SUMMARY_FILE='gnu-full-result.json'
outputs SUITE_LOG_FILE TEST_FILESET_PREFIX TEST_FILESET_SUFFIX TEST_LOGS_GLOB TEST_SUMMARY_FILE TEST_FULL_SUMMARY_FILE
- name: Checkout code (uutil)
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
path: '${{ steps.vars.outputs.path_UUTILS }}'
- name: Checkout code (GNU coreutils)
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
repository: 'coreutils/coreutils'
path: '${{ steps.vars.outputs.path_GNU }}'
@@ -146,22 +146,22 @@ jobs:
# Compress logs before upload (fails otherwise)
gzip ${{ steps.vars.outputs.TEST_LOGS_GLOB }}
- name: Reserve SHA1/ID of 'test-summary'
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v3
with:
name: "${{ steps.summary.outputs.HASH }}"
path: "${{ steps.vars.outputs.TEST_SUMMARY_FILE }}"
- name: Reserve test results summary
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v3
with:
name: test-summary
path: "${{ steps.vars.outputs.TEST_SUMMARY_FILE }}"
- name: Reserve test logs
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v3
with:
name: test-logs
path: "${{ steps.vars.outputs.TEST_LOGS_GLOB }}"
- name: Upload full json results
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v3
with:
name: gnu-full-result.json
path: ${{ steps.vars.outputs.TEST_FULL_SUMMARY_FILE }}
@@ -174,8 +174,8 @@ jobs:
REPO_DEFAULT_BRANCH='${{ steps.vars.outputs.repo_default_branch }}'
if test -f "${REF_LOG_FILE}"; then
echo "Reference SHA1/ID: $(sha1sum -- "${REF_SUMMARY_FILE}")"
REF_ERROR=$(sed -n "s/^FAIL: \([[:print:]]\+\).*/\1/p" "${REF_LOG_FILE}" | sort)
NEW_ERROR=$(sed -n "s/^FAIL: \([[:print:]]\+\).*/\1/p" '${{ steps.vars.outputs.path_GNU_tests }}/test-suite.log' | sort)
REF_ERROR=$(sed -n "s/^ERROR: \([[:print:]]\+\).*/\1/p" "${REF_LOG_FILE}" | sort)
NEW_ERROR=$(sed -n "s/^ERROR: \([[:print:]]\+\).*/\1/p" '${{ steps.vars.outputs.path_GNU_tests }}/test-suite.log' | sort)
REF_FAILING=$(sed -n "s/^FAIL: \([[:print:]]\+\).*/\1/p" "${REF_LOG_FILE}" | sort)
NEW_FAILING=$(sed -n "s/^FAIL: \([[:print:]]\+\).*/\1/p" '${{ steps.vars.outputs.path_GNU_tests }}/test-suite.log' | sort)
for LINE in ${REF_FAILING}
@@ -229,11 +229,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout code uutil
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
path: 'uutils'
- name: Checkout GNU coreutils
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
repository: 'coreutils/coreutils'
path: 'gnu'
@@ -293,7 +293,7 @@ jobs:
grcov . --output-type lcov --output-path "${COVERAGE_REPORT_FILE}" --branch --ignore build.rs --ignore "vendor/*" --ignore "/*" --ignore "[a-zA-Z]:/*" --excl-br-line "^\s*((debug_)?assert(_eq|_ne)?!|#\[derive\()"
echo ::set-output name=report::${COVERAGE_REPORT_FILE}
- name: Upload coverage results (to Codecov.io)
uses: codecov/codecov-action@v2
uses: codecov/codecov-action@v3
with:
file: ${{ steps.coverage.outputs.report }}
flags: gnutests
Generated
+52 -17
View File
@@ -224,7 +224,7 @@ dependencies = [
"libc",
"num-integer",
"num-traits",
"time",
"time 0.1.44",
"winapi 0.3.9",
]
@@ -273,9 +273,9 @@ dependencies = [
[[package]]
name = "clap_complete"
version = "3.1.3"
version = "3.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d7ca9141e27e6ebc52e3c378b0c07f3cea52db46ed1cc5861735fb697b56356"
checksum = "da92e6facd8d73c22745a5d3cbb59bdf8e46e3235c923e516527d8e81eec14a4"
dependencies = [
"clap 3.1.15",
]
@@ -335,7 +335,7 @@ dependencies = [
"sha1",
"tempfile",
"textwrap 0.15.0",
"time",
"time 0.3.9",
"unindent",
"unix_socket",
"users",
@@ -871,7 +871,7 @@ checksum = "418d37c8b1d42553c93648be529cb70f920d3baf8ef469b74b9638df426e0b4c"
dependencies = [
"cfg-if 1.0.0",
"libc",
"wasi 0.10.2+wasi-snapshot-preview1",
"wasi 0.10.0+wasi-snapshot-preview1",
]
[[package]]
@@ -985,6 +985,12 @@ dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
[[package]]
name = "keccak"
version = "0.1.0"
@@ -1196,9 +1202,9 @@ dependencies = [
[[package]]
name = "num-traits"
version = "0.2.14"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290"
checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"
dependencies = [
"autocfg",
]
@@ -1213,6 +1219,15 @@ dependencies = [
"libc",
]
[[package]]
name = "num_threads"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aba1801fb138d8e85e11d0fc70baf4fe1cdfffda7c6cd34a854905df588e5ed0"
dependencies = [
"libc",
]
[[package]]
name = "number_prefix"
version = "0.4.0"
@@ -1944,14 +1959,33 @@ dependencies = [
[[package]]
name = "time"
version = "0.1.43"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438"
checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255"
dependencies = [
"libc",
"wasi 0.10.0+wasi-snapshot-preview1",
"winapi 0.3.9",
]
[[package]]
name = "time"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2702e08a7a860f005826c6815dcac101b19b5eb330c27fe4a5928fec1d20ddd"
dependencies = [
"itoa",
"libc",
"num_threads",
"time-macros",
]
[[package]]
name = "time-macros"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42657b1a6f4d817cda8e7a0ace261fe0cc946cf3a80314390b22cc61ae080792"
[[package]]
name = "typenum"
version = "1.15.0"
@@ -1993,9 +2027,9 @@ checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
[[package]]
name = "unindent"
version = "0.1.8"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "514672a55d7380da379785a4d70ca8386c8883ff7eaae877be4d2081cebe73d8"
checksum = "52fee519a3e570f7df377a06a1a7775cdbfb7aa460be7e08de2b1f0e69973a44"
[[package]]
name = "unix_socket"
@@ -2400,6 +2434,7 @@ dependencies = [
"file_diff",
"filetime",
"libc",
"time 0.3.9",
"uucore",
]
@@ -2875,7 +2910,7 @@ version = "0.0.13"
dependencies = [
"clap 3.1.15",
"filetime",
"time",
"time 0.3.9",
"uucore",
"winapi 0.3.9",
]
@@ -3042,7 +3077,7 @@ dependencies = [
"once_cell",
"os_display",
"thiserror",
"time",
"time 0.3.9",
"uucore_procs",
"walkdir",
"wild",
@@ -3090,9 +3125,9 @@ dependencies = [
[[package]]
name = "wasi"
version = "0.10.2+wasi-snapshot-preview1"
version = "0.10.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]]
name = "wasi"
@@ -3208,9 +3243,9 @@ checksum = "504a2476202769977a040c6364301a3f65d0cc9e3fb08600b2bda150a0488316"
[[package]]
name = "xattr"
version = "0.2.2"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "244c3741f4240ef46274860397c7c74e50eb23624996930e484c16679633a54c"
checksum = "6d1526bbe5aaeb5eb06885f4d987bcdfa5e23187055de9b83fe00156a821fabc"
dependencies = [
"libc",
]
+1 -1
View File
@@ -391,7 +391,7 @@ rand = "0.8"
regex = "1.5"
sha1 = { version="0.10", features=["std"] }
tempfile = "3"
time = "0.1"
time = {version="0.3", features=["local-offset"]}
unindent = "0.1"
uucore = { version=">=0.0.11", package="uucore", path="src/uucore", features=["entries", "process"] }
walkdir = "2.2"
+5 -1
View File
@@ -11,6 +11,8 @@ unmaintained = "warn"
yanked = "warn"
notice = "warn"
ignore = [
"RUSTSEC-2020-0159",
"RUSTSEC-2020-0071",
#"RUSTSEC-0000-0000",
]
@@ -62,7 +64,7 @@ highlight = "all"
# spell-checker: disable
skip = [
# getrandom
{ name = "wasi", version="0.10.2+wasi-snapshot-preview1" },
{ name = "wasi", version="0.10.0+wasi-snapshot-preview1" },
# blake2d_simd
{ name = "arrayvec", version = "=0.7.2" },
# flimit/unix_socket
@@ -84,6 +86,8 @@ skip = [
{ name = "memchr", version = "=1.0.2" },
{ name = "quote", version = "=0.3.15" },
{ name = "unicode-xid", version = "=0.0.4" },
# chrono
{ name = "time", version = "=0.1.44" },
]
# spell-checker: enable
+1 -1
View File
@@ -34,7 +34,7 @@ ioctl-sys = "0.8"
winapi = { version="0.3", features=["fileapi"] }
[target.'cfg(unix)'.dependencies]
xattr="0.2.1"
xattr="0.2.3"
exacl= { version = "0.8.0", optional=true }
[[bin]]
+46 -6
View File
@@ -5,9 +5,12 @@
//! Types for representing and displaying block sizes.
use crate::OPT_BLOCKSIZE;
use clap::ArgMatches;
use std::fmt;
use std::{env, fmt};
use uucore::parse_size::{parse_size, ParseSizeError};
use uucore::{
display::Quotable,
parse_size::{parse_size, ParseSizeError},
};
/// The first ten powers of 1024.
const IEC_BASES: [u128; 10] = [
@@ -73,7 +76,7 @@ fn to_magnitude_and_suffix_1024(n: u128) -> Result<String, ()> {
Err(())
}
/// Convert a number, except multiples of 1024, into a string like "12kB" or "34MB".
/// Convert a number into a string like "12kB" or "34MB".
///
/// Powers of 1000 become "1kB", "1MB", "1GB", etc.
///
@@ -110,7 +113,7 @@ fn to_magnitude_and_suffix_not_powers_of_1024(n: u128) -> Result<String, ()> {
///
/// If the number is too large to represent.
fn to_magnitude_and_suffix(n: u128) -> Result<String, ()> {
if n % 1024 == 0 {
if n % 1024 == 0 && n % 1000 != 0 {
to_magnitude_and_suffix_1024(n)
} else {
to_magnitude_and_suffix_not_powers_of_1024(n)
@@ -159,6 +162,7 @@ pub(crate) enum HumanReadable {
/// size.
///
/// The default variant is `Bytes(1024)`.
#[derive(Debug, PartialEq)]
pub(crate) enum BlockSize {
/// A fixed number of bytes.
///
@@ -166,16 +170,35 @@ pub(crate) enum BlockSize {
Bytes(u64),
}
impl BlockSize {
/// Returns the associated value
pub(crate) fn as_u64(&self) -> u64 {
match *self {
Self::Bytes(n) => n,
}
}
}
impl Default for BlockSize {
fn default() -> Self {
Self::Bytes(1024)
if env::var("POSIXLY_CORRECT").is_ok() {
Self::Bytes(512)
} else {
Self::Bytes(1024)
}
}
}
pub(crate) fn block_size_from_matches(matches: &ArgMatches) -> Result<BlockSize, ParseSizeError> {
if matches.is_present(OPT_BLOCKSIZE) {
let s = matches.value_of(OPT_BLOCKSIZE).unwrap();
Ok(BlockSize::Bytes(parse_size(s)?))
let bytes = parse_size(s)?;
if bytes > 0 {
Ok(BlockSize::Bytes(bytes))
} else {
Err(ParseSizeError::ParseFailure(format!("{}", s.quote())))
}
} else {
Ok(Default::default())
}
@@ -195,6 +218,8 @@ impl fmt::Display for BlockSize {
#[cfg(test)]
mod tests {
use std::env;
use crate::blocks::{to_magnitude_and_suffix, BlockSize};
#[test]
@@ -239,10 +264,25 @@ mod tests {
assert_eq!(to_magnitude_and_suffix(1_000_000_001).unwrap(), "1.1GB");
}
#[test]
fn test_to_magnitude_and_suffix_multiples_of_1000_and_1024() {
assert_eq!(to_magnitude_and_suffix(128_000).unwrap(), "128kB");
assert_eq!(to_magnitude_and_suffix(1000 * 1024).unwrap(), "1.1MB");
assert_eq!(to_magnitude_and_suffix(1_000_000_000_000).unwrap(), "1TB");
}
#[test]
fn test_block_size_display() {
assert_eq!(format!("{}", BlockSize::Bytes(1024)), "1K");
assert_eq!(format!("{}", BlockSize::Bytes(2 * 1024)), "2K");
assert_eq!(format!("{}", BlockSize::Bytes(3 * 1024 * 1024)), "3M");
}
#[test]
fn test_default_block_size() {
assert_eq!(BlockSize::Bytes(1024), BlockSize::default());
env::set_var("POSIXLY_CORRECT", "1");
assert_eq!(BlockSize::Bytes(512), BlockSize::default());
env::remove_var("POSIXLY_CORRECT");
}
}
+31 -1
View File
@@ -12,6 +12,7 @@ mod filesystem;
mod table;
use blocks::{HumanReadable, SizeFormat};
use table::HeaderMode;
use uucore::display::Quotable;
use uucore::error::{UError, UResult, USimpleError};
use uucore::fsext::{read_fs_list, MountInfo};
@@ -32,6 +33,13 @@ use crate::table::Table;
static ABOUT: &str = "Show information about the file system on which each FILE resides,\n\
or all file systems by default.";
const USAGE: &str = "{} [OPTION]... [FILE]...";
const LONG_HELP: &str = "Display values are in units of the first available SIZE from --block-size,
and the DF_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables.
Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set).
SIZE is an integer and optional unit (example: 10M is 10*1024*1024).
Units are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB,... (powers
of 1000).";
static OPT_HELP: &str = "help";
static OPT_ALL: &str = "all";
@@ -65,6 +73,7 @@ struct Options {
show_all_fs: bool,
size_format: SizeFormat,
block_size: BlockSize,
header_mode: HeaderMode,
/// Optional list of filesystem types to include in the output table.
///
@@ -92,6 +101,7 @@ impl Default for Options {
show_all_fs: Default::default(),
block_size: Default::default(),
size_format: Default::default(),
header_mode: Default::default(),
include: Default::default(),
exclude: Default::default(),
show_total: Default::default(),
@@ -169,6 +179,21 @@ impl Options {
),
ParseSizeError::ParseFailure(s) => OptionsError::InvalidBlockSize(s),
})?,
header_mode: {
if matches.is_present(OPT_HUMAN_READABLE_BINARY)
|| matches.is_present(OPT_HUMAN_READABLE_DECIMAL)
{
HeaderMode::HumanReadable
} else if matches.is_present(OPT_PORTABILITY) {
HeaderMode::PosixPortability
// is_present() doesn't work here, it always returns true because OPT_OUTPUT has
// default values and hence is always present
} else if matches.occurrences_of(OPT_OUTPUT) > 0 {
HeaderMode::Output
} else {
HeaderMode::Default
}
},
size_format: {
if matches.is_present(OPT_HUMAN_READABLE_BINARY) {
SizeFormat::HumanReadable(HumanReadable::Binary)
@@ -427,6 +452,7 @@ pub fn uu_app<'a>() -> Command<'a> {
.version(crate_version!())
.about(ABOUT)
.override_usage(format_usage(USAGE))
.after_help(LONG_HELP)
.infer_long_args(true)
.arg(
Arg::new(OPT_HELP)
@@ -445,6 +471,7 @@ pub fn uu_app<'a>() -> Command<'a> {
.short('B')
.long("block-size")
.takes_value(true)
.value_name("SIZE")
.overrides_with_all(&[OPT_KILO, OPT_BLOCKSIZE])
.help(
"scale sizes by SIZE before printing them; e.g.\
@@ -501,6 +528,7 @@ pub fn uu_app<'a>() -> Command<'a> {
Arg::new(OPT_OUTPUT)
.long("output")
.takes_value(true)
.value_name("FIELD_LIST")
.min_values(0)
.require_equals(true)
.use_value_delimiter(true)
@@ -510,7 +538,7 @@ pub fn uu_app<'a>() -> Command<'a> {
.default_values(&["source", "size", "used", "avail", "pcent", "target"])
.conflicts_with_all(&[OPT_INODES, OPT_PORTABILITY, OPT_PRINT_TYPE])
.help(
"use the output format defined by FIELD_LIST,\
"use the output format defined by FIELD_LIST, \
or print all fields if FIELD_LIST is omitted.",
),
)
@@ -533,6 +561,7 @@ pub fn uu_app<'a>() -> Command<'a> {
.long("type")
.allow_invalid_utf8(true)
.takes_value(true)
.value_name("TYPE")
.multiple_occurrences(true)
.help("limit listing to file systems of type TYPE"),
)
@@ -549,6 +578,7 @@ pub fn uu_app<'a>() -> Command<'a> {
.long("exclude-type")
.allow_invalid_utf8(true)
.takes_value(true)
.value_name("TYPE")
.use_value_delimiter(true)
.multiple_occurrences(true)
.help("limit listing to file systems not of type TYPE"),
+85 -94
View File
@@ -289,6 +289,23 @@ impl<'a> RowFormatter<'a> {
}
}
/// A HeaderMode defines what header labels should be shown.
pub(crate) enum HeaderMode {
Default,
// the user used -h or -H
HumanReadable,
// the user used -P
PosixPortability,
// the user used --output
Output,
}
impl Default for HeaderMode {
fn default() -> Self {
Self::Default
}
}
/// The data of the header row.
struct Header {}
@@ -302,15 +319,22 @@ impl Header {
for column in &options.columns {
let header = match column {
Column::Source => String::from("Filesystem"),
Column::Size => match options.size_format {
SizeFormat::HumanReadable(_) => String::from("Size"),
SizeFormat::StaticBlockSize => {
format!("{}-blocks", options.block_size)
Column::Size => match options.header_mode {
HeaderMode::HumanReadable => String::from("Size"),
HeaderMode::PosixPortability => {
format!("{}-blocks", options.block_size.as_u64())
}
_ => format!("{}-blocks", options.block_size),
},
Column::Used => String::from("Used"),
Column::Avail => String::from("Available"),
Column::Pcent => String::from("Use%"),
Column::Avail => match options.header_mode {
HeaderMode::HumanReadable | HeaderMode::Output => String::from("Avail"),
_ => String::from("Available"),
},
Column::Pcent => match options.header_mode {
HeaderMode::PosixPortability => String::from("Capacity"),
_ => String::from("Use%"),
},
Column::Target => String::from("Mounted on"),
Column::Itotal => String::from("Inodes"),
Column::Iused => String::from("IUsed"),
@@ -428,7 +452,7 @@ mod tests {
use crate::blocks::{HumanReadable, SizeFormat};
use crate::columns::Column;
use crate::table::{Header, Row, RowFormatter};
use crate::table::{Header, HeaderMode, Row, RowFormatter};
use crate::{BlockSize, Options};
const COLUMNS_WITH_FS_TYPE: [Column; 7] = [
@@ -449,6 +473,30 @@ mod tests {
Column::Target,
];
impl Default for Row {
fn default() -> Self {
Self {
file: Some("/path/to/file".to_string()),
fs_device: "my_device".to_string(),
fs_type: "my_type".to_string(),
fs_mount: "my_mount".to_string(),
bytes: 100,
bytes_used: 25,
bytes_avail: 75,
bytes_usage: Some(0.25),
#[cfg(target_os = "macos")]
bytes_capacity: Some(0.5),
inodes: 10,
inodes_used: 2,
inodes_free: 8,
inodes_usage: Some(0.2),
}
}
}
#[test]
fn test_default_header() {
let options = Default::default();
@@ -524,37 +572,49 @@ mod tests {
}
#[test]
fn test_header_with_human_readable_binary() {
fn test_human_readable_header() {
let options = Options {
size_format: SizeFormat::HumanReadable(HumanReadable::Binary),
header_mode: HeaderMode::HumanReadable,
..Default::default()
};
assert_eq!(
Header::get_headers(&options),
vec!("Filesystem", "Size", "Used", "Avail", "Use%", "Mounted on")
);
}
#[test]
fn test_posix_portability_header() {
let options = Options {
header_mode: HeaderMode::PosixPortability,
..Default::default()
};
assert_eq!(
Header::get_headers(&options),
vec!(
"Filesystem",
"Size",
"1024-blocks",
"Used",
"Available",
"Use%",
"Capacity",
"Mounted on"
)
);
}
#[test]
fn test_header_with_human_readable_si() {
fn test_output_header() {
let options = Options {
size_format: SizeFormat::HumanReadable(HumanReadable::Decimal),
header_mode: HeaderMode::Output,
..Default::default()
};
assert_eq!(
Header::get_headers(&options),
vec!(
"Filesystem",
"Size",
"1K-blocks",
"Used",
"Available",
"Avail",
"Use%",
"Mounted on"
)
@@ -568,9 +628,7 @@ mod tests {
..Default::default()
};
let row = Row {
file: Some("/path/to/file".to_string()),
fs_device: "my_device".to_string(),
fs_type: "my_type".to_string(),
fs_mount: "my_mount".to_string(),
bytes: 100,
@@ -578,13 +636,7 @@ mod tests {
bytes_avail: 75,
bytes_usage: Some(0.25),
#[cfg(target_os = "macos")]
bytes_capacity: Some(0.5),
inodes: 10,
inodes_used: 2,
inodes_free: 8,
inodes_usage: Some(0.2),
..Default::default()
};
let fmt = RowFormatter::new(&row, &options);
assert_eq!(
@@ -601,7 +653,6 @@ mod tests {
..Default::default()
};
let row = Row {
file: Some("/path/to/file".to_string()),
fs_device: "my_device".to_string(),
fs_type: "my_type".to_string(),
fs_mount: "my_mount".to_string(),
@@ -611,13 +662,7 @@ mod tests {
bytes_avail: 75,
bytes_usage: Some(0.25),
#[cfg(target_os = "macos")]
bytes_capacity: Some(0.5),
inodes: 10,
inodes_used: 2,
inodes_free: 8,
inodes_usage: Some(0.2),
..Default::default()
};
let fmt = RowFormatter::new(&row, &options);
assert_eq!(
@@ -634,23 +679,15 @@ mod tests {
..Default::default()
};
let row = Row {
file: Some("/path/to/file".to_string()),
fs_device: "my_device".to_string(),
fs_type: "my_type".to_string(),
fs_mount: "my_mount".to_string(),
bytes: 100,
bytes_used: 25,
bytes_avail: 75,
bytes_usage: Some(0.25),
#[cfg(target_os = "macos")]
bytes_capacity: Some(0.5),
inodes: 10,
inodes_used: 2,
inodes_free: 8,
inodes_usage: Some(0.2),
..Default::default()
};
let fmt = RowFormatter::new(&row, &options);
assert_eq!(
@@ -667,23 +704,9 @@ mod tests {
..Default::default()
};
let row = Row {
file: Some("/path/to/file".to_string()),
fs_device: "my_device".to_string(),
fs_type: "my_type".to_string(),
fs_mount: "my_mount".to_string(),
bytes: 100,
bytes_used: 25,
bytes_avail: 75,
bytes_usage: Some(0.25),
#[cfg(target_os = "macos")]
bytes_capacity: Some(0.5),
inodes: 10,
inodes_used: 2,
inodes_free: 8,
inodes_usage: Some(0.2),
..Default::default()
};
let fmt = RowFormatter::new(&row, &options);
assert_eq!(fmt.get_values(), vec!("1", "10"));
@@ -697,7 +720,6 @@ mod tests {
..Default::default()
};
let row = Row {
file: Some("/path/to/file".to_string()),
fs_device: "my_device".to_string(),
fs_type: "my_type".to_string(),
fs_mount: "my_mount".to_string(),
@@ -707,13 +729,7 @@ mod tests {
bytes_avail: 3000,
bytes_usage: Some(0.25),
#[cfg(target_os = "macos")]
bytes_capacity: Some(0.5),
inodes: 10,
inodes_used: 2,
inodes_free: 8,
inodes_usage: Some(0.2),
..Default::default()
};
let fmt = RowFormatter::new(&row, &options);
assert_eq!(
@@ -738,7 +754,6 @@ mod tests {
..Default::default()
};
let row = Row {
file: Some("/path/to/file".to_string()),
fs_device: "my_device".to_string(),
fs_type: "my_type".to_string(),
fs_mount: "my_mount".to_string(),
@@ -748,13 +763,7 @@ mod tests {
bytes_avail: 3072,
bytes_usage: Some(0.25),
#[cfg(target_os = "macos")]
bytes_capacity: Some(0.5),
inodes: 10,
inodes_used: 2,
inodes_free: 8,
inodes_usage: Some(0.2),
..Default::default()
};
let fmt = RowFormatter::new(&row, &options);
assert_eq!(
@@ -774,32 +783,14 @@ mod tests {
#[test]
fn test_row_formatter_with_round_up_usage() {
let options = Options {
block_size: BlockSize::Bytes(1),
columns: vec![Column::Pcent],
..Default::default()
};
let row = Row {
file: Some("/path/to/file".to_string()),
fs_device: "my_device".to_string(),
fs_type: "my_type".to_string(),
fs_mount: "my_mount".to_string(),
bytes: 100,
bytes_used: 25,
bytes_avail: 75,
bytes_usage: Some(0.251),
#[cfg(target_os = "macos")]
bytes_capacity: Some(0.5),
inodes: 10,
inodes_used: 2,
inodes_free: 8,
inodes_usage: Some(0.2),
..Default::default()
};
let fmt = RowFormatter::new(&row, &options);
assert_eq!(
fmt.get_values(),
vec!("my_device", "100", "25", "75", "26%", "my_mount")
);
assert_eq!(fmt.get_values(), vec!("26%"));
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ path = "src/expr.rs"
[dependencies]
clap = { version = "3.1", features = ["wrap_help", "cargo"] }
num-bigint = "0.4.0"
num-traits = "0.2.14"
num-traits = "0.2.15"
onig = { version = "~6.3", default-features = false }
uucore = { version=">=0.0.11", package="uucore", path="../../uucore" }
+2 -2
View File
@@ -12,12 +12,12 @@ categories = ["command-line-utilities"]
edition = "2021"
[build-dependencies]
num-traits = "0.2.13" # used in src/numerics.rs, which is included by build.rs
num-traits = "0.2.15" # used in src/numerics.rs, which is included by build.rs
[dependencies]
clap = { version = "3.1", features = ["wrap_help", "cargo"] }
coz = { version = "0.1.3", optional = true }
num-traits = "0.2.13" # Needs at least version 0.2.13 for "OverflowingAdd"
num-traits = "0.2.15" # Needs at least version 0.2.15 for "OverflowingAdd"
rand = { version = "0.8", features = ["small_rng"] }
smallvec = "1.7" # TODO(nicoo): Use `union` feature, requires Rust 1.49 or later.
uucore = { version = ">=0.0.8", package = "uucore", path = "../../uucore" }
+3
View File
@@ -24,6 +24,9 @@ file_diff = "1.0.0"
libc = ">= 0.2"
uucore = { version=">=0.0.11", package="uucore", path="../../uucore", features=["fs", "mode", "perms", "entries"] }
[dev-dependencies]
time = "0.3"
[[bin]]
name = "install"
path = "src/main.rs"
+78 -7
View File
@@ -41,7 +41,12 @@ enum MkTempError {
PersistError(PathBuf),
MustEndInX(String),
TooFewXs(String),
ContainsDirSeparator(String),
/// The template prefix contains a path separator (e.g. `"a/bXXX"`).
PrefixContainsDirSeparator(String),
/// The template suffix contains a path separator (e.g. `"XXXa/b"`).
SuffixContainsDirSeparator(String),
InvalidTemplate(String),
}
@@ -56,7 +61,14 @@ impl Display for MkTempError {
PersistError(p) => write!(f, "could not persist file {}", p.quote()),
MustEndInX(s) => write!(f, "with --suffix, template {} must end in X", s.quote()),
TooFewXs(s) => write!(f, "too few X's in template {}", s.quote()),
ContainsDirSeparator(s) => {
PrefixContainsDirSeparator(s) => {
write!(
f,
"invalid template, {}, contains directory separator",
s.quote()
)
}
SuffixContainsDirSeparator(s) => {
write!(
f,
"invalid suffix {}, contains directory separator",
@@ -205,20 +217,41 @@ pub fn uu_app<'a>() -> Command<'a> {
)
}
/// Parse a template string into prefix, suffix, and random components.
///
/// `temp` is the template string, with three or more consecutive `X`s
/// representing a placeholder for randomly generated characters (for
/// example, `"abc_XXX.txt"`). If `temp` ends in an `X`, then a suffix
/// can be specified by `suffix` instead.
///
/// # Errors
///
/// * If there are fewer than three consecutive `X`s in `temp`.
/// * If `suffix` is a [`Some`] object but `temp` does not end in `X`.
/// * If the suffix (specified either way) contains a path separator.
///
/// # Examples
///
/// ```rust,ignore
/// assert_eq!(parse_template("XXX", None).unwrap(), ("", 3, ""));
/// assert_eq!(parse_template("abcXXX", None).unwrap(), ("abc", 3, ""));
/// assert_eq!(parse_template("XXXdef", None).unwrap(), ("", 3, "def"));
/// assert_eq!(parse_template("abcXXXdef", None).unwrap(), ("abc", 3, "def"));
/// ```
fn parse_template<'a>(
temp: &'a str,
suffix: Option<&'a str>,
) -> UResult<(&'a str, usize, &'a str)> {
) -> Result<(&'a str, usize, &'a str), MkTempError> {
let right = match temp.rfind('X') {
Some(r) => r + 1,
None => return Err(MkTempError::TooFewXs(temp.into()).into()),
None => return Err(MkTempError::TooFewXs(temp.into())),
};
let left = temp[..right].rfind(|c| c != 'X').map_or(0, |i| i + 1);
let prefix = &temp[..left];
let rand = right - left;
if rand < 3 {
return Err(MkTempError::TooFewXs(temp.into()).into());
return Err(MkTempError::TooFewXs(temp.into()));
}
let mut suf = &temp[right..];
@@ -227,12 +260,16 @@ fn parse_template<'a>(
if suf.is_empty() {
suf = s;
} else {
return Err(MkTempError::MustEndInX(temp.into()).into());
return Err(MkTempError::MustEndInX(temp.into()));
}
};
if prefix.chars().any(is_separator) {
return Err(MkTempError::PrefixContainsDirSeparator(temp.into()));
}
if suf.chars().any(is_separator) {
return Err(MkTempError::ContainsDirSeparator(suf.into()).into());
return Err(MkTempError::SuffixContainsDirSeparator(suf.into()));
}
Ok((prefix, rand, suf))
@@ -304,3 +341,37 @@ fn exec(dir: &Path, prefix: &str, rand: usize, suffix: &str, make_dir: bool) ->
println_verbatim(path).map_err_context(|| "failed to print directory name".to_owned())
}
#[cfg(test)]
mod tests {
use crate::parse_template;
#[test]
fn test_parse_template_no_suffix() {
assert_eq!(parse_template("XXX", None).unwrap(), ("", 3, ""));
assert_eq!(parse_template("abcXXX", None).unwrap(), ("abc", 3, ""));
assert_eq!(parse_template("XXXdef", None).unwrap(), ("", 3, "def"));
assert_eq!(
parse_template("abcXXXdef", None).unwrap(),
("abc", 3, "def")
);
}
#[test]
fn test_parse_template_suffix() {
assert_eq!(parse_template("XXX", Some("def")).unwrap(), ("", 3, "def"));
assert_eq!(
parse_template("abcXXX", Some("def")).unwrap(),
("abc", 3, "def")
);
}
#[test]
fn test_parse_template_errors() {
assert!(parse_template("a/bXXX", None).is_err());
assert!(parse_template("XXXa/b", None).is_err());
assert!(parse_template("XX", None).is_err());
assert!(parse_template("XXXabc", Some("def")).is_err());
assert!(parse_template("XXX", Some("a/b")).is_err());
}
}
+7 -3
View File
@@ -221,10 +221,10 @@ impl Capitalize for str {
fn idle_string(when: i64) -> String {
thread_local! {
static NOW: time::Tm = time::now()
static NOW: time::OffsetDateTime = time::OffsetDateTime::now_local().unwrap();
}
NOW.with(|n| {
let duration = n.to_timespec().sec - when;
let duration = n.unix_timestamp() - when;
if duration < 60 {
// less than 1min
" ".to_owned()
@@ -242,7 +242,11 @@ fn idle_string(when: i64) -> String {
}
fn time_string(ut: &Utmpx) -> String {
time::strftime("%b %e %H:%M", &ut.login_time()).unwrap() // LC_ALL=C
// "%b %e %H:%M"
let time_format: Vec<time::format_description::FormatItem> =
time::format_description::parse("[month repr:short] [day padding:space] [hour]:[minute]")
.unwrap();
ut.login_time().format(&time_format).unwrap() // LC_ALL=C
}
fn gecos_to_fullname(pw: &Passwd) -> Option<String> {
+1 -1
View File
@@ -19,7 +19,7 @@ path = "src/seq.rs"
bigdecimal = "0.3"
clap = { version = "3.1", features = ["wrap_help", "cargo"] }
num-bigint = "0.4.0"
num-traits = "0.2.14"
num-traits = "0.2.15"
uucore = { version=">=0.0.11", package="uucore", path="../../uucore", features=["memo"] }
[[bin]]
+1 -1
View File
@@ -17,7 +17,7 @@ path = "src/touch.rs"
[dependencies]
filetime = "0.2.1"
clap = { version = "3.1", features = ["wrap_help", "cargo"] }
time = "0.1.40"
time = { version = "0.3", features = ["parsing", "formatting", "local-offset", "macros"] }
uucore = { version=">=0.0.11", package="uucore", path="../../uucore", features=["libc"] }
[target.'cfg(target_os = "windows")'.dependencies]
+179 -52
View File
@@ -6,8 +6,7 @@
// For the full copyright and license information, please view the LICENSE file
// that was distributed with this source code.
// spell-checker:ignore (ToDO) filetime strptime utcoff strs datetime MMDDhhmm clapv PWSTR lpszfilepath hresult
// spell-checker:ignore (ToDO) filetime strptime utcoff strs datetime MMDDhhmm clapv PWSTR lpszfilepath hresult mktime YYYYMMDDHHMM YYMMDDHHMM DATETIME YYYYMMDDHHMMS subsecond
pub extern crate filetime;
#[macro_use]
@@ -17,6 +16,8 @@ use clap::{crate_version, Arg, ArgGroup, Command};
use filetime::*;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use time::macros::{format_description, offset, time};
use time::Duration;
use uucore::display::Quotable;
use uucore::error::{FromIo, UError, UResult, USimpleError};
use uucore::format_usage;
@@ -41,14 +42,27 @@ pub mod options {
static ARG_FILES: &str = "files";
fn to_local(mut tm: time::Tm) -> time::Tm {
tm.tm_utcoff = time::now().tm_utcoff;
tm
// Convert a date/time to a date with a TZ offset
fn to_local(tm: time::PrimitiveDateTime) -> time::OffsetDateTime {
let offset = match time::OffsetDateTime::now_local() {
Ok(lo) => lo.offset(),
Err(e) => {
panic!("error: {}", e);
}
};
tm.assume_offset(offset)
}
fn local_tm_to_filetime(tm: time::Tm) -> FileTime {
let ts = tm.to_timespec();
FileTime::from_unix_time(ts.sec as i64, ts.nsec as u32)
// Convert a date/time with a TZ offset into a FileTime
fn local_dt_to_filetime(dt: time::OffsetDateTime) -> FileTime {
FileTime::from_unix_time(dt.unix_timestamp(), dt.nanosecond())
}
// Convert a date/time, considering that the input is in UTC time
// Used for touch -d 1970-01-01 18:43:33.023456789 for example
fn dt_to_filename(tm: time::PrimitiveDateTime) -> FileTime {
let dt = tm.assume_offset(offset!(UTC));
local_dt_to_filetime(dt)
}
#[uucore::main]
@@ -62,7 +76,6 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Try 'touch --help' for more information."##,
)
})?;
let (mut atime, mut mtime) =
if let Some(reference) = matches.value_of_os(options::sources::REFERENCE) {
stat(Path::new(reference), !matches.is_present(options::NO_DEREF))?
@@ -72,7 +85,7 @@ Try 'touch --help' for more information."##,
} else if let Some(current) = matches.value_of(options::sources::CURRENT) {
parse_timestamp(current)?
} else {
local_tm_to_filetime(time::now())
local_dt_to_filetime(time::OffsetDateTime::now_local().unwrap())
};
(timestamp, timestamp)
};
@@ -248,38 +261,129 @@ fn stat(path: &Path, follow: bool) -> UResult<(FileTime, FileTime)> {
))
}
fn parse_date(str: &str) -> UResult<FileTime> {
const POSIX_LOCALE_FORMAT: &[time::format_description::FormatItem] = format_description!(
"[weekday repr:short] [month repr:short] [day padding:space] \
[hour]:[minute]:[second] [year]"
);
const ISO_8601_FORMAT: &[time::format_description::FormatItem] =
format_description!("[year]-[month]-[day]");
// "%Y%m%d%H%M.%S" 15 chars
const YYYYMMDDHHMM_DOT_SS_FORMAT: &[time::format_description::FormatItem] = format_description!(
"[year repr:full][month repr:numerical padding:zero]\
[day][hour][minute].[second]"
);
// "%Y-%m-%d %H:%M:%S.%SS" 12 chars
const YYYYMMDDHHMMSS_FORMAT: &[time::format_description::FormatItem] = format_description!(
"[year repr:full]-[month repr:numerical padding:zero]-\
[day] [hour]:[minute]:[second].[subsecond]"
);
// "%Y-%m-%d %H:%M:%S" 12 chars
const YYYYMMDDHHMMS_FORMAT: &[time::format_description::FormatItem] = format_description!(
"[year repr:full]-[month repr:numerical padding:zero]-\
[day] [hour]:[minute]:[second]"
);
// "%Y-%m-%d %H:%M" 12 chars
// Used for example in tests/touch/no-rights.sh
const YYYY_MM_DD_HH_MM_FORMAT: &[time::format_description::FormatItem] = format_description!(
"[year repr:full]-[month repr:numerical padding:zero]-\
[day] [hour]:[minute]"
);
// "%Y%m%d%H%M" 12 chars
const YYYYMMDDHHMM_FORMAT: &[time::format_description::FormatItem] = format_description!(
"[year repr:full][month repr:numerical padding:zero]\
[day][hour][minute]"
);
// "%y%m%d%H%M.%S" 13 chars
const YYMMDDHHMM_DOT_SS_FORMAT: &[time::format_description::FormatItem] = format_description!(
"[year repr:last_two padding:none][month][day]\
[hour][minute].[second]"
);
// "%y%m%d%H%M" 10 chars
const YYMMDDHHMM_FORMAT: &[time::format_description::FormatItem] = format_description!(
"[year repr:last_two padding:none][month padding:zero][day padding:zero]\
[hour repr:24 padding:zero][minute padding:zero]"
);
// "%Y-%m-%d %H:%M +offset"
// Used for example in tests/touch/relative.sh
const YYYYMMDDHHMM_OFFSET_FORMAT: &[time::format_description::FormatItem] = format_description!(
"[year]-[month]-[day] [hour repr:24]:[minute] \
[offset_hour sign:mandatory][offset_minute]"
);
fn parse_date(s: &str) -> UResult<FileTime> {
// This isn't actually compatible with GNU touch, but there doesn't seem to
// be any simple specification for what format this parameter allows and I'm
// not about to implement GNU parse_datetime.
// http://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=blob_plain;f=lib/parse-datetime.y
let formats = vec!["%c", "%F"];
for f in formats {
if let Ok(tm) = time::strptime(str, f) {
return Ok(local_tm_to_filetime(to_local(tm)));
// TODO: match on char count?
// "The preferred date and time representation for the current locale."
// "(In the POSIX locale this is equivalent to %a %b %e %H:%M:%S %Y.)"
// time 0.1.43 parsed this as 'a b e T Y'
// which is equivalent to the POSIX locale: %a %b %e %H:%M:%S %Y
// Tue Dec 3 ...
// ("%c", POSIX_LOCALE_FORMAT),
//
if let Ok(parsed) = time::PrimitiveDateTime::parse(s, &POSIX_LOCALE_FORMAT) {
return Ok(local_dt_to_filetime(to_local(parsed)));
}
// Also support other formats found in the GNU tests like
// in tests/misc/stat-nanoseconds.sh
// or tests/touch/no-rights.sh
for fmt in [
YYYYMMDDHHMMS_FORMAT,
YYYYMMDDHHMMSS_FORMAT,
YYYY_MM_DD_HH_MM_FORMAT,
YYYYMMDDHHMM_OFFSET_FORMAT,
] {
if let Ok(parsed) = time::PrimitiveDateTime::parse(s, &fmt) {
return Ok(dt_to_filename(parsed));
}
}
if let Ok(tm) = time::strptime(str, "@%s") {
// Don't convert to local time in this case - seconds since epoch are not time-zone dependent
return Ok(local_tm_to_filetime(tm));
// "Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)"
// ("%F", ISO_8601_FORMAT),
if let Ok(parsed) = time::Date::parse(s, &ISO_8601_FORMAT) {
return Ok(local_dt_to_filetime(to_local(
time::PrimitiveDateTime::new(parsed, time!(00:00)),
)));
}
Err(USimpleError::new(
1,
format!("Unable to parse date: {}", str),
))
// "@%s" is "The number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). (TZ) (Calculated from mktime(tm).)"
if s.bytes().next() == Some(b'@') {
if let Ok(ts) = &s[1..].parse::<i64>() {
// Don't convert to local time in this case - seconds since epoch are not time-zone dependent
return Ok(local_dt_to_filetime(
time::OffsetDateTime::from_unix_timestamp(*ts).unwrap(),
));
}
}
Err(USimpleError::new(1, format!("Unable to parse date: {}", s)))
}
fn parse_timestamp(s: &str) -> UResult<FileTime> {
let now = time::now();
let (format, ts) = match s.chars().count() {
15 => ("%Y%m%d%H%M.%S", s.to_owned()),
12 => ("%Y%m%d%H%M", s.to_owned()),
13 => ("%y%m%d%H%M.%S", s.to_owned()),
10 => ("%y%m%d%H%M", s.to_owned()),
11 => ("%Y%m%d%H%M.%S", format!("{}{}", now.tm_year + 1900, s)),
8 => ("%Y%m%d%H%M", format!("{}{}", now.tm_year + 1900, s)),
// TODO: handle error
let now = time::OffsetDateTime::now_utc();
let (mut format, mut ts) = match s.chars().count() {
15 => (YYYYMMDDHHMM_DOT_SS_FORMAT, s.to_owned()),
12 => (YYYYMMDDHHMM_FORMAT, s.to_owned()),
13 => (YYMMDDHHMM_DOT_SS_FORMAT, s.to_owned()),
10 => (YYMMDDHHMM_FORMAT, s.to_owned()),
11 => (YYYYMMDDHHMM_DOT_SS_FORMAT, format!("{}{}", now.year(), s)),
8 => (YYYYMMDDHHMM_FORMAT, format!("{}{}", now.year(), s)),
_ => {
return Err(USimpleError::new(
1,
@@ -287,30 +391,53 @@ fn parse_timestamp(s: &str) -> UResult<FileTime> {
))
}
};
let tm = time::strptime(&ts, format)
.map_err(|_| USimpleError::new(1, format!("invalid date format {}", s.quote())))?;
let mut local = to_local(tm);
local.tm_isdst = -1;
let ft = local_tm_to_filetime(local);
// We have to check that ft is valid time. Due to daylight saving
// time switch, local time can jump from 1:59 AM to 3:00 AM,
// in which case any time between 2:00 AM and 2:59 AM is not valid.
// Convert back to local time and see if we got the same value back.
let ts = time::Timespec {
sec: ft.unix_seconds(),
nsec: 0,
};
let tm2 = time::at(ts);
if tm.tm_hour != tm2.tm_hour {
return Err(USimpleError::new(
1,
format!("invalid date format {}", s.quote()),
));
// workaround time returning Err(TryFromParsed(InsufficientInformation)) for year w/
// repr:last_two
// https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1ccfac7c07c5d1c7887a11decf0e1996
if s.chars().count() == 10 {
format = YYYYMMDDHHMM_FORMAT;
ts = "20".to_owned() + &ts;
} else if s.chars().count() == 13 {
format = YYYYMMDDHHMM_DOT_SS_FORMAT;
ts = "20".to_owned() + &ts;
}
let leap_sec = if (format == YYYYMMDDHHMM_DOT_SS_FORMAT || format == YYMMDDHHMM_DOT_SS_FORMAT)
&& ts.ends_with(".60")
{
// Work around to disable leap seconds
// Used in gnu/tests/touch/60-seconds
ts = ts.replace(".60", ".59");
true
} else {
false
};
let tm = time::PrimitiveDateTime::parse(&ts, &format)
.map_err(|_| USimpleError::new(1, format!("invalid date ts format {}", ts.quote())))?;
let mut local = to_local(tm);
if leap_sec {
// We are dealing with a leap second, add it
local = local.saturating_add(Duration::SECOND);
}
let ft = local_dt_to_filetime(local);
// // We have to check that ft is valid time. Due to daylight saving
// // time switch, local time can jump from 1:59 AM to 3:00 AM,
// // in which case any time between 2:00 AM and 2:59 AM is not valid.
// // Convert back to local time and see if we got the same value back.
// let ts = time::Timespec {
// sec: ft.unix_seconds(),
// nsec: 0,
// };
// let tm2 = time::at(ts);
// if tm.tm_hour != tm2.tm_hour {
// return Err(USimpleError::new(
// 1,
// format!("invalid date format {}", s.quote()),
// ));
// }
Ok(ft)
}

Some files were not shown because too many files have changed in this diff Show More