Debian Codegraph @

ansible_collections/community/general/plugins/modules/git_config.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2015, Marius Gedminas <[email protected]>
4 # Copyright (c) 2016, Matthew Gamble <[email protected]>
5 #
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: git_config
13 author:
14 - Matthew Gamble (@djmattyg007)
15 - Marius Gedminas (@mgedmin)
16 requirements: ['git']
17 short_description: Update git configuration
18 description:
19 - The M(community.general.git_config) module changes git configuration by invoking C(git config). This is needed if you
20 do not want to use M(ansible.builtin.template) for the entire git config file (for example because you need to change
21 just C(user.email) in C(/etc/.git/config)). Solutions involving M(ansible.builtin.command) are cumbersome or do not work
22 correctly in check mode.
23 extends_documentation_fragment:
24 - community.general._attributes
25 attributes:
26 check_mode:
27 support: full
28 diff_mode:
29 support: none
30 options:
31 name:
32 description:
33 - The name of the setting.
34 type: str
35 required: true
36 repo:
37 description:
38 - Path to a git repository for reading and writing values from a specific repo.
39 type: path
40 file:
41 description:
42 - Path to an adhoc git configuration file to be managed using the V(file) scope.
43 type: path
44 version_added: 2.0.0
45 scope:
46 description:
47 - Specify which scope to read/set values from.
48 - This is required when setting config values.
49 - If this is set to V(local), you must also specify the O(repo) parameter.
50 - If this is set to V(file), you must also specify the O(file) parameter.
51 - It defaults to system.
52 choices: ["file", "local", "global", "system"]
53 type: str
54 state:
55 description:
56 - 'Indicates the setting should be set/unset. This parameter has higher precedence than O(value) parameter: when O(state=absent)
57 and O(value) is defined, O(value) is discarded.'
58 choices: ['present', 'absent']
59 default: 'present'
60 type: str
61 value:
62 description:
63 - When specifying the name of a single setting, supply a value to set that setting to the given value.
64 - From community.general 11.0.0 on, O(value) is required if O(state=present). To read values, use the M(community.general.git_config_info)
65 module instead.
66 type: str
67 add_mode:
68 description:
69 - Specify if a value should replace the existing value(s) or if the new value should be added alongside other values
70 with the same name.
71 - This option is only relevant when adding/replacing values. If O(state=absent) or values are just read out, this option
72 is not considered.
73 choices: ["add", "replace-all"]
74 type: str
75 default: "replace-all"
76 version_added: 8.1.0
77 """
78
79 EXAMPLES = r"""
80 - name: Add a setting to ~/.gitconfig
81 community.general.git_config:
82 name: alias.ci
83 scope: global
84 value: commit
85
86 - name: Add a setting to ~/.gitconfig
87 community.general.git_config:
88 name: alias.st
89 scope: global
90 value: status
91
92 - name: Remove a setting from ~/.gitconfig
93 community.general.git_config:
94 name: alias.ci
95 scope: global
96 state: absent
97
98 - name: Add a setting to ~/.gitconfig
99 community.general.git_config:
100 name: core.editor
101 scope: global
102 value: vim
103
104 - name: Add a setting system-wide
105 community.general.git_config:
106 name: alias.remotev
107 scope: system
108 value: remote -v
109
110 - name: Add a setting to a system scope (default)
111 community.general.git_config:
112 name: alias.diffc
113 value: diff --cached
114
115 - name: Add a setting to a system scope (default)
116 community.general.git_config:
117 name: color.ui
118 value: auto
119
120 - name: Add several options for the same name
121 community.general.git_config:
122 name: push.pushoption
123 value: "{{ item }}"
124 add_mode: add
125 loop:
126 - merge_request.create
127 - merge_request.draft
128
129 - name: Make etckeeper not complaining when it is invoked by cron
130 community.general.git_config:
131 name: user.email
132 repo: /etc
133 scope: local
134 value: 'root@{{ ansible_fqdn }}'
135 """
136
137 RETURN = r"""
138 """
139
140 from ansible.module_utils.basic import AnsibleModule
141
142
143 def main():
144 module = AnsibleModule(
145 argument_spec=dict(
146 name=dict(type="str", required=True),
147 repo=dict(type="path"),
148 file=dict(type="path"),
149 add_mode=dict(type="str", default="replace-all", choices=["add", "replace-all"]),
150 scope=dict(type="str", choices=["file", "local", "global", "system"]),
151 state=dict(type="str", default="present", choices=["present", "absent"]),
152 value=dict(),
153 ),
154 required_if=[
155 ("scope", "local", ["repo"]),
156 ("scope", "file", ["file"]),
157 ("state", "present", ["value"]),
158 ],
159 supports_check_mode=True,
160 )
161 git_path = module.get_bin_path("git", True)
162
163 params = module.params
164 # We check error message for a pattern, so we need to make sure the messages appear in the form we're expecting.
165 # Set the locale to C to ensure consistent messages.
166 module.run_command_environ_update = dict(LANGUAGE="C", LC_ALL="C")
167
168 name = params["name"] or ""
169 unset = params["state"] == "absent"
170 new_value = params["value"] or ""
171 add_mode = params["add_mode"]
172
173 if not unset and not new_value:
174 module.fail_json(
175 msg="If state=present, a value must be specified. Use the community.general.git_config_info module to read a config value."
176 )
177
178 scope = determine_scope(params)
179 cwd = determine_cwd(scope, params)
180
181 base_args = [git_path, "config", "--includes"]
182
183 if scope == "file":
184 base_args.append("-f")
185 base_args.append(params["file"])
186 elif scope:
187 base_args.append(f"--{scope}")
188
189 list_args = list(base_args)
190
191 list_args.append("--get-all")
192 list_args.append(name)
193
194 (rc, out, err) = module.run_command(list_args, cwd=cwd, expand_user_and_vars=False)
195
196 if rc >= 2:
197 # If the return code is 1, it just means the option hasn't been set yet, which is fine.
198 module.fail_json(rc=rc, msg=err, cmd=" ".join(list_args))
199
200 old_values = out.rstrip().splitlines()
201
202 if unset and not out:
203 module.exit_json(changed=False, msg="no setting to unset")
204 elif new_value in old_values and (len(old_values) == 1 or add_mode == "add") and not unset:
205 module.exit_json(changed=False, msg="")
206
207 # Until this point, the git config was just read and in case no change is needed, the module has already exited.
208
209 set_args = list(base_args)
210 if unset:
211 set_args.append("--unset-all")
212 set_args.append(name)
213 else:
214 set_args.append(f"--{add_mode}")
215 set_args.append(name)
216 set_args.append(new_value)
217
218 if not module.check_mode:
219 (rc, out, err) = module.run_command(set_args, cwd=cwd, ignore_invalid_cwd=False, expand_user_and_vars=False)
220 if err:
221 module.fail_json(rc=rc, msg=err, cmd=set_args)
222
223 if unset:
224 after_values = []
225 elif add_mode == "add":
226 after_values = old_values + [new_value]
227 else:
228 after_values = [new_value]
229
230 module.exit_json(
231 msg="setting changed",
232 diff=dict(
233 before_header=" ".join(set_args),
234 before=build_diff_value(old_values),
235 after_header=" ".join(set_args),
236 after=build_diff_value(after_values),
237 ),
238 changed=True,
239 )
240
241
242 def determine_scope(params):
243 if params["scope"]:
244 return params["scope"]
245 return "system"
246
247
248 def build_diff_value(value):
249 if not value:
250 return "\n"
251 if len(value) == 1:
252 return f"{value[0]}\n"
253 return value
254
255
256 def determine_cwd(scope, params):
257 if scope == "local":
258 return params["repo"]
259 # Run from root directory to avoid accidentally picking up any local config settings
260 return "/"
261
262
263 if __name__ == "__main__":
264 main()