You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opendal.apache.org by "knight42 (via GitHub)" <gi...@apache.org> on 2023/03/20 14:45:36 UTC

[GitHub] [incubator-opendal] knight42 opened a new pull request, #1706: feat(oli): add config file to oli

knight42 opened a new pull request, #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706

   Ref #422


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142885183


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   Please correct me if I misunderstand what your proposal is:
   You mean we should save bucket in the profile, so that a profile 1:1 maps to an OpenDAL operator. Besides, OpenDAL is already able to read credentials from aws cli config, we don't need to save credentials in the profile. Therefore, it is convenient to omit bucket from the uri.
   
   After deliberation, I think it makes sense. So the usage of `oli cp` should be
   ```
   oli cp profile1://<path> profile2://<path>
   ```
   and the format of profile is something like
   ```
   [profiles.mys3]
   type = "s3"
   region = "us-east-1"
   bucket = "bucket"
   access_key_id = "" # optional, since aws cli config will be read
   secret_access_key = "" # optional, ditto
   ```
   
   right?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] suyanhanx commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "suyanhanx (via GitHub)" <gi...@apache.org>.
suyanhanx commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142245765


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,

Review Comment:
   We tend to start it first~



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142885183


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   Please correct me if I misunderstand what your proposal is:
   You mean we should save bucket in the profile, so that a profile 1:1 maps to an OpenDAL operator. Besides, OpenDAL is already able to read credentials from aws cli config, we don't need to save credentials in the profile. Therefore, it is convenient to omit bucket from the uri.
   
   After deliberation, I think it makes sense. So the usage of `oli cp` should be
   ```
   oli cp profile1://<path> profile2://<path>
   ```
   right?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142872687


##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   Thanks for pointing it out, I can't believe I have overlooked such a nice feature! I will update the PR later.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142236005


##########
binaries/oli/Cargo.toml:
##########
@@ -32,9 +32,13 @@ anyhow = "1"
 clap = { version = "4", features = ["cargo", "string"] }
 env_logger = "0.10"
 futures = "0.3"
+home = "0.5.4"

Review Comment:
   How about using https://crates.io/crates/dirs which provides better support for config dir.



##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   It's more common to use `~/.config/oli/config.toml`



##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   Maybe we can treat `bucket` as a config value?



##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"

Review Comment:
   How about:
   
   ```suggestion
   [profiles.mys3]
   type = "s3"
   region = "us-east-1"
   access_key_id = "foo"
   enable_virtual_host_style = "on"
   ```



##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services

Review Comment:
   Can we handle them in a more general way? Add seperate field for every service seems boring.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142248128


##########
binaries/oli/Cargo.toml:
##########
@@ -32,9 +32,13 @@ anyhow = "1"
 clap = { version = "4", features = ["cargo", "string"] }
 env_logger = "0.10"
 futures = "0.3"
+home = "0.5.4"

Review Comment:
   👍 Will do!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] xxchan commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "xxchan (via GitHub)" <gi...@apache.org>.
xxchan commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142358174


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   I found another fact: actually 
   ```
   oli cp s3://bucket-a/.. s3://bucket-b/...
   ```
   is already supported (before this PR). You don't need any profile at all.
   
   Because of this I think including bucket in profile makes more sense.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] xxchan commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "xxchan (via GitHub)" <gi...@apache.org>.
xxchan commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142276535


##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   > It's more common to use `~/.config/oli/config.toml`
   
   Any references? 👀 There's e.g., `~/.config/nextest.toml`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] xxchan commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "xxchan (via GitHub)" <gi...@apache.org>.
xxchan commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142358174


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   I found another fact: actually 
   ```
   oli cp s3://bucket-a/.. s3://bucket-b/...
   ```
   is already supported (before this PR). You don't need any profile at all. `S3::default` reads `~/.aws/config`. You can try testing it.
   
   Because of this I think including bucket in profile makes more sense.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142371066


##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   > The [directories](https://crates.io/crates/directories/5.0.0) crate turns out to be helpful if we want to support `XDG_CONFIG_HOME`, should I use this crate?
   
   I think `dirs` should already support it?
   
   ```shell
   dirs::config_dir();
   // Lin: Some(/home/alice/.config)
   // Win: Some(C:\Users\Alice\AppData\Roaming)
   // Mac: Some(/Users/Alice/Library/Application Support)
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142264247


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   See https://github.com/apache/incubator-opendal/issues/422#issuecomment-1476365956
   > I am hesitant to add the bucket to the config file, as users might want to access different buckets in the same account. As a user, I don't want to create different profiles for different buckets in the same account.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] xxchan commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "xxchan (via GitHub)" <gi...@apache.org>.
xxchan commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1143197548


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   > You mean we should save bucket in the profile, so that a profile 1:1 maps to an OpenDAL operator. 
   
   This is exactly my idea.
   
   > Besides, OpenDAL is already able to read credentials from aws cli config, we don't need to save credentials in the profile.
   
   This looks also good. 🤔 But actually I mean we treat `s3://` specially. i.e., it's a **scheme** instead of a **profile**, which is the previous implementation (but you didn't delete it which confused me a little..). And in this case, we use the standard s3uri to parse it, and the UX for `oli` is similar to `aws s3`. We can access any bucket without defining a profile first.
   
   But maybe we can KISS now in the MVP and just include the profile design. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1143157122


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,162 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! update_options {
+    ($m: expr) => {{
+        let mut opts = $m.clone();
+        opts.remove("type");
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {

Review Comment:
   The purpose of this function is to make testing the config parser easy, otherwise we need to create a real file in the unit test.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1143230681


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   > I mean we treat s3:// specially. i.e., it's a scheme instead of a profile,
   
   What if a user need to copy data across different accounts, say `oli cp s3://bucket1/<path> s3://bucket2-in-another-account/<path>` 🤔.
   
   > We can access any bucket without defining a profile first.
   
   If you are worrying about the requirement of a profile before running `oli`, I think we could treat the `s3` scheme as a special profile. If a uri like `s3://bucket/<path>` is supplied, then we could use a default S3Builder.
   
   > but you didn't delete it which confused me a little..
   
   Thanks for reminding me of this, I actually forgot 😂



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#issuecomment-1477789921

   Thanks for all your patience and through review 👍 !


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142239196


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,

Review Comment:
   Should I add all services in this PR?



##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}

Review Comment:
   @Xuanwo I would like to describe the format of the config file, but I am not sure where is the right place?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142381094


##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   I prefer `dirs` becuase one of our deps always uses it :rofl: 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142312813


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"

Review Comment:
   Finished. PTAL



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] xxchan commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "xxchan (via GitHub)" <gi...@apache.org>.
xxchan commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1143197548


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   > You mean we should save bucket in the profile, so that a profile 1:1 maps to an OpenDAL operator. 
   
   This is exactly my idea.
   
   > Besides, OpenDAL is already able to read credentials from aws cli config, we don't need to save credentials in the profile.
   
   This looks also good. 🤔 But actually I mean we treat `s3://` specially. i.e., it's a **scheme** instead of a **profile**, which is the previous `parse_location` implementation (but you didn't delete it which confused me a little..). And in this case, we use the standard s3uri to parse it, and the UX for `oli` is similar to `aws s3`. We can access any bucket without defining a profile first.
   
   But maybe we can KISS now in the MVP and just include the profile design. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1143240240


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   > What if a user need to copy data across different accounts
   
   Please don't over thinking use cases before we really meet it. I prefer to deliver the minimum workable product. Let's focus on the simplest case.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo merged pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo merged PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142885183


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   Please correct me if I misunderstand what your proposal is:
   You mean we should save bucket in the profile, so that a profile 1:1 maps to an OpenDAL operator. Besides, OpenDAL is already able to read credentials from aws cli config, we don't need to save credentials in the profile. Therefore, it is convenient to omit bucket from the uri.
   
   After deliberation, I think it makes sense. So the usage of `oli cp` should be
   ```
   oli cp profile1://<path> profile2://<path>
   ```
   and the format of profile is still something like
   ```
   [profiles.mys3]
   type = "s3"
   region = "us-east-1"
   bucket = "bucket"
   access_key_id = "" # optional, since aws cli config will be read
   secret_access_key = "" # optional, ditto
   ```
   
   right?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142928274


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   Done. PTAL



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142250321


##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   I borrow this idea from `kubectl` 😂 , `~/.config/oli/config.toml` also lgtm. Should we respect `XDG_CONFIG_HOME` as well?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142365956


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   > I am hesitant to add the bucket to the config file, as users might want to access different buckets in the same account. As a user, I don't want to create different profiles for different buckets in the same account
   
   Nice catch. We can address this use case in the future~



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#issuecomment-1476476732

   I would get back to this tmr as it is already late now 😂 Have a good night!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142932256


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,162 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! update_options {
+    ($m: expr) => {{
+        let mut opts = $m.clone();
+        opts.remove("type");
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {

Review Comment:
   I prefer to merge this function if it's function only be used once.



##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,162 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! update_options {

Review Comment:
   maybe we can remove this macro rule?



##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,162 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;

Review Comment:
   I prefer remove this type, it's over designed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1143174405


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,162 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! update_options {

Review Comment:
   well.. I have to admit it makes sense 😂 will do



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1143169235


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,162 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! update_options {

Review Comment:
   don't worry, from_map handles this.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142371066


##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   > The [directories](https://crates.io/crates/directories/5.0.0) crate turns out to be helpful if we want to support `XDG_CONFIG_HOME`, should I use this crate?
   
   I think `dirs` should already support it?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142262904


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"

Review Comment:
   I understand your point. I would refactor this.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142921457


##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1143161032


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,162 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;

Review Comment:
   The purpose of this type is to save me some typings as well, I previously need to reference this type multiple times. Now that this type is only referenced once, I could remove this type.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142325304


##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   The [directories](https://crates.io/crates/directories/5.0.0) crate turns out to be helpful if we want to support `XDG_CONFIG_HOME`, should I use this crate?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] xxchan commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "xxchan (via GitHub)" <gi...@apache.org>.
xxchan commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142302433


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   I feel it's natural that 1 profile corresponds to a bucket (an OpenDAL operator), but also understand the need to access different buckets without duplicating buckets. 
   
   Maybe we need something like
   
   ```toml
   [s3]
   region = "us-east-1"
   ```
   
   which is a default configuration for `s3` (can be overriden by profiles). Then we use it like
   ```
   oli cp s3://... s3://...
   ```
   instead of profiles.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142302759


##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   > Should we respect `XDG_CONFIG_HOME` as well?
   
   Yep.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#issuecomment-1476370395

   /cc @Xuanwo 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142302385


##########
binaries/oli/src/bin/oli.rs:
##########
@@ -28,6 +28,23 @@ use std::path::PathBuf;
 
 use anyhow::anyhow;
 use anyhow::Result;
+use clap::{value_parser, Arg, Command};
+use home::home_dir;
+
+fn new_cmd(name: &'static str) -> Result<Command> {
+    let home = home_dir().ok_or_else(|| anyhow!("unknown home dir"))?;
+    let default_config_path = home.join(".oli/config.toml").as_os_str().to_owned();

Review Comment:
   > There's e.g., `~/.config/nextest.toml`
   
   Also LGTM.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142327476


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   @xxchan I am not sure if I understand how the default configuration interacts with the profiles 😂 Could you elaborate more?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] xxchan commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "xxchan (via GitHub)" <gi...@apache.org>.
xxchan commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142358174


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   I found another fact: actually 
   ```
   oli cp s3://bucket-a/.. s3://bucket-b/...
   ```
   is already supported (before this PR). You can try it.
   
   Because of this I think including bucket in profile makes more sense.



##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,161 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! update_options {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone();
+        opts.remove("type");
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];

Review Comment:
   Not all services have bucket concept? 🤔



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142368129


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,159 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! set_bucket {
+    ($m: expr, $bucket: ident) => {{
+        let mut opts = $m.clone().unwrap();
+        opts.insert("bucket".to_string(), $bucket.to_string());
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<Profile>,
+}
+
+#[derive(Deserialize, Default)]
+pub struct Profile {
+    // TODO: add more services
+    s3: Option<StringMap<String>>,
+    oss: Option<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {
+        Ok(toml::from_str(s)?)
+    }
+
+    /// Parse `<profile>://abc/def` into `op` and `location`.
+    pub fn parse_location<'a>(&self, s: &'a str) -> Result<(Operator, &'a str)> {
+        if !s.contains("://") {
+            let mut fs = services::Fs::default();
+
+            let filename = match s.rsplit_once(['/', '\\']) {
+                Some((base, filename)) => {
+                    fs.root(base);
+                    filename
+                }
+                None => s,
+            };
+
+            return Ok((Operator::new(fs)?.finish(), filename));
+        }
+
+        let parts = s.splitn(2, "://").collect::<Vec<_>>();
+        debug_assert!(parts.len() == 2);
+
+        let profile_name = parts[0];
+
+        let bucket_and_path = parts[1].splitn(2, '/').collect::<Vec<_>>();
+        debug_assert!(bucket_and_path.len() == 2);
+
+        let bucket = bucket_and_path[0];
+        let path = bucket_and_path[1];
+
+        let profile = self
+            .profiles
+            .get(profile_name)
+            .ok_or_else(|| anyhow!("unknown profile: {}", profile_name))?;
+
+        if profile.s3.is_some() {
+            let opts = set_bucket!(profile.s3, bucket);
+            Ok((Operator::from_map::<services::S3>(opts)?.finish(), path))
+        } else if profile.oss.is_some() {
+            let opts = set_bucket!(profile.oss, bucket);
+            Ok((Operator::from_map::<services::Oss>(opts)?.finish(), path))
+        } else {
+            Err(anyhow!("invalid profile"))
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use opendal::Scheme;
+
+    #[test]
+    fn test_load_toml() {
+        let cfg = Config::load_from_str(
+            r#"
+[profiles.mys3.s3]
+region = "us-east-1"
+access_key_id = "foo"
+enable_virtual_host_style = "on"
+"#,
+        )
+        .expect("load config");
+        let profile = cfg.profiles["mys3"].s3.clone().unwrap();
+        assert_eq!(profile["region"], "us-east-1");
+        assert_eq!(profile["access_key_id"], "foo");
+        assert_eq!(profile["enable_virtual_host_style"], "on");
+    }
+
+    #[test]
+    fn test_parse_fs_location() {
+        let cfg = Config::default();
+        let (op, path) = cfg.parse_location("./foo/bar/1.txt").unwrap();
+        assert_eq!("1.txt", path);
+        let info = op.info();
+        assert!(info.root().ends_with("foo/bar"));
+        assert_eq!(Scheme::Fs, info.scheme());
+    }
+
+    #[test]
+    fn test_parse_s3_location() {
+        let cfg = Config {
+            profiles: StringMap::from([(
+                "mys3".into(),
+                Profile {
+                    s3: Some(StringMap::from([("region".into(), "us-east-1".into())])),
+                    ..Default::default()
+                },
+            )]),
+        };
+        let (op, path) = cfg.parse_location("mys3://mybucket/foo/1.txt").unwrap();

Review Comment:
   I had considered `s3` and `azblob` as special cases, but did not give them serious consideration. Nonetheless, it is sufficient to prioritize the use of `bucket` in the `profile` initially.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] Xuanwo commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "Xuanwo (via GitHub)" <gi...@apache.org>.
Xuanwo commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1142932256


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,162 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! update_options {
+    ($m: expr) => {{
+        let mut opts = $m.clone();
+        opts.remove("type");
+        opts
+    }};
+}
+
+#[derive(Deserialize, Default)]
+pub struct Config {
+    profiles: StringMap<StringMap<String>>,
+}
+
+impl Config {
+    /// Parse a local config file.
+    ///
+    /// - If the config file is not present, a default Config is returned.
+    pub fn load_from_file<P: AsRef<Path>>(fp: P) -> Result<Config> {
+        let config_path = fp.as_ref();
+        if !config_path.exists() {
+            return Ok(Config::default());
+        }
+        let data = fs::read_to_string(config_path)?;
+        Config::load_from_str(&data)
+    }
+
+    pub(crate) fn load_from_str(s: &str) -> Result<Config> {

Review Comment:
   I prefer to merge this function if it's only be used once.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1143155512


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,162 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;
+
+macro_rules! update_options {

Review Comment:
   This purpose of this macro is to save me some typings, otherwise I need to execute these statements in every case listed in https://github.com/apache/incubator-opendal/blob/8439153fbedcf1b303cac85befed7dd4b2e9b7de/binaries/oli/src/config/mod.rs#L98-L105
   which I think is repetitive



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [incubator-opendal] knight42 commented on a diff in pull request #1706: feat(oli): add config file to oli

Posted by "knight42 (via GitHub)" <gi...@apache.org>.
knight42 commented on code in PR #1706:
URL: https://github.com/apache/incubator-opendal/pull/1706#discussion_r1143164784


##########
binaries/oli/src/config/mod.rs:
##########
@@ -0,0 +1,162 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::collections::HashMap;
+use std::fs;
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::{anyhow, Result};
+use opendal::{services, Operator, Scheme};
+use serde::Deserialize;
+use toml;
+
+type StringMap<T> = HashMap<String, T>;

Review Comment:
   Done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opendal.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org