Skip to content

Commit

Permalink
Merge pull request #12 from rustcoreutils/pwd
Browse files Browse the repository at this point in the history
add util: pwd
  • Loading branch information
jgarzik authored Mar 20, 2024
2 parents b4d1e73 + 0b0e3e9 commit f5cae53
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ https://github.com/jgarzik/posixutils
- [ ] printf
- [ ] prs (SCCS)
- [ ] ps
- [ ] pwd
- [x] pwd
- [ ] qalter (Batch cat.)
- [ ] qdel (Batch cat.)
- [ ] qhold (Batch cat.)
Expand Down
4 changes: 4 additions & 0 deletions users/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ path = "src/logger.rs"
name = "mesg"
path = "src/mesg.rs"

[[bin]]
name = "pwd"
path = "src/pwd.rs"

[[bin]]
name = "tty"
path = "src/tty.rs"
Expand Down
77 changes: 77 additions & 0 deletions users/src/pwd.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//
// Copyright (c) 2024 Jeff Garzik
//
// This file is part of the posixutils-rs project covered under
// the MIT License. For the full license text, please see the LICENSE
// file in the root directory of this project.
// SPDX-License-Identifier: MIT
//
// TODO:
// - compliance: for -L mode, Rust performs unwanted normalization for "."
//

extern crate clap;
extern crate plib;

use clap::Parser;
use gettextrs::{bind_textdomain_codeset, textdomain};
use plib::PROJECT_NAME;
use std::ffi::OsStr;
use std::path::{Component, Path};

const PWD_ENV: &'static str = "PWD";

/// pwd - return working directory name
#[derive(Parser, Debug)]
#[command(author, version, about, long_about)]
struct Args {
/// Count number of bytes in each file
#[arg(short = 'L', long)]
env: bool,

/// Count number of bytes in each file
#[arg(short = 'P', long)]
process: bool,
}

fn dirname_valid(name: &OsStr) -> bool {
let path = Path::new(name);

let mut first = true;
for component in path.components() {
if first {
first = false;

if component != Component::RootDir {
return false;
}
} else {
if component == Component::CurDir || component == Component::ParentDir {
return false;
}
}
}

true
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
// parse command line arguments
let args = Args::parse();

textdomain(PROJECT_NAME)?;
bind_textdomain_codeset(PROJECT_NAME, "UTF-8")?;

let mut cwd = std::env::current_dir()?.into_os_string();
if args.env {
if let Some(dir) = std::env::var_os(PWD_ENV) {
if dirname_valid(&dir) {
cwd = dir.clone();
}
}
}

println!("{}", cwd.to_string_lossy());

Ok(())
}

0 comments on commit f5cae53

Please sign in to comment.