-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathdocs.rs
More file actions
210 lines (186 loc) · 6.89 KB
/
docs.rs
File metadata and controls
210 lines (186 loc) · 6.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// Copyright 2026 Google LLC
//
// Licensed 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 super::Helper;
use crate::auth;
use crate::error::GwsError;
use crate::executor;
use clap::{Arg, ArgMatches, Command};
use serde_json::json;
use std::future::Future;
use std::pin::Pin;
pub struct DocsHelper;
impl Helper for DocsHelper {
fn inject_commands(
&self,
mut cmd: Command,
_doc: &crate::discovery::RestDescription,
) -> Command {
cmd = cmd.subcommand(
Command::new("+write")
.about("[Helper] Append text to a document")
.arg(
Arg::new("document")
.long("document")
.help("Document ID")
.required(true)
.value_name("ID"),
)
.arg(
Arg::new("text")
.long("text")
.help("Text to append (plain text)")
.required(true)
.value_name("TEXT"),
)
.after_help(
"\
EXAMPLES:
gws docs +write --document DOC_ID --text 'Hello, world!'
TIPS:
Text is inserted at the end of the document body.
For rich formatting, use the raw batchUpdate API instead.",
),
);
cmd
}
fn handle<'a>(
&'a self,
doc: &'a crate::discovery::RestDescription,
matches: &'a ArgMatches,
_sanitize_config: &'a crate::helpers::modelarmor::SanitizeConfig,
) -> Pin<Box<dyn Future<Output = Result<bool, GwsError>> + Send + 'a>> {
Box::pin(async move {
if let Some(sub_matches) = matches.subcommand_matches("+write") {
let (params_str, body_str, scopes) = build_write_request(sub_matches, doc)?;
let output_format = matches
.get_one::<String>("format")
.map(|s| crate::formatter::OutputFormat::from_str(s))
.unwrap_or_default();
let scope_strs: Vec<&str> = scopes.iter().map(|s| s.as_str()).collect();
let (token, auth_method) = match auth::get_token(&scope_strs).await {
Ok(t) => (Some(t), executor::AuthMethod::OAuth),
Err(_) if matches.get_flag("dry-run") => (None, executor::AuthMethod::None),
Err(e) => return Err(GwsError::Auth(format!("Docs auth failed: {e}"))),
};
// Method: documents.batchUpdate
let documents_res = doc.resources.get("documents").ok_or_else(|| {
GwsError::Discovery("Resource 'documents' not found".to_string())
})?;
let batch_update_method =
documents_res.methods.get("batchUpdate").ok_or_else(|| {
GwsError::Discovery("Method 'documents.batchUpdate' not found".to_string())
})?;
let pagination = executor::PaginationConfig {
page_all: false,
page_limit: 10,
page_delay_ms: 100,
};
executor::execute_method(
doc,
batch_update_method,
Some(¶ms_str),
Some(&body_str),
token.as_deref(),
auth_method,
None,
None,
matches.get_flag("dry-run"),
&pagination,
None,
&crate::helpers::modelarmor::SanitizeMode::Warn,
&output_format,
false,
)
.await?;
return Ok(true);
}
Ok(false)
})
}
}
fn build_write_request(
matches: &ArgMatches,
doc: &crate::discovery::RestDescription,
) -> Result<(String, String, Vec<String>), GwsError> {
let document_id = matches.get_one::<String>("document").unwrap();
let text = matches.get_one::<String>("text").unwrap();
let documents_res = doc
.resources
.get("documents")
.ok_or_else(|| GwsError::Discovery("Resource 'documents' not found".to_string()))?;
let batch_update_method = documents_res.methods.get("batchUpdate").ok_or_else(|| {
GwsError::Discovery("Method 'documents.batchUpdate' not found".to_string())
})?;
let params = json!({
"documentId": document_id
});
let body = json!({
"requests": [
{
"insertText": {
"text": text,
"endOfSegmentLocation": {
"segmentId": "" // Empty means body
}
}
}
]
});
let scopes: Vec<String> = batch_update_method
.scopes
.iter()
.map(|s| s.to_string())
.collect();
Ok((params.to_string(), body.to_string(), scopes))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::discovery::{RestDescription, RestMethod, RestResource};
use std::collections::HashMap;
fn make_mock_doc() -> RestDescription {
let mut methods = HashMap::new();
methods.insert(
"batchUpdate".to_string(),
RestMethod {
scopes: vec!["https://scope".to_string()],
..Default::default()
},
);
let mut documents_res = RestResource::default();
documents_res.methods = methods;
let mut resources = HashMap::new();
resources.insert("documents".to_string(), documents_res);
RestDescription {
resources,
..Default::default()
}
}
fn make_matches_write(args: &[&str]) -> ArgMatches {
let cmd = Command::new("test")
.arg(Arg::new("document").long("document"))
.arg(Arg::new("text").long("text"));
cmd.try_get_matches_from(args).unwrap()
}
#[test]
fn test_build_write_request() {
let doc = make_mock_doc();
let matches = make_matches_write(&["test", "--document", "123", "--text", "hello world"]);
let (params, body, scopes) = build_write_request(&matches, &doc).unwrap();
assert!(params.contains("123"));
assert!(body.contains("hello world"));
assert!(body.contains("endOfSegmentLocation"));
assert_eq!(scopes[0], "https://scope");
}
}